struts2就是對mvc的實現,爲了方便,我只講解web上的mvc。在web上m就是model,你理解成web上的實體就可以了。c,controller,對應struts上的action,v就是view,視圖對應你的那些JSP,html等等。
先說一下struts2的核心,org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter這個類就是struts2的核心,struts2就是通過它來攔截對web服務器所有的請求,然後開發人員在通過實際需求來實現不同的web應用。
大家看名字就應該可以猜到,這個類是一個攔截器,因此需要配置在web.xml中。
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
爲了前期減少大家的誤區,就不講解包的依賴性了,在你下載的struts2中會自帶一個struts2_blank的工程,然後你把這個工程下的lib中包拷貝到你的工程中就可以了。
然後編寫一個簡單action,也就是控制器:
package action;
import com.opensymphony.xwork2.ActionSupport;
public class Hello extends ActionSupport{
@Override
public String execute(){
System.out.println("Hello the world!");
return SUCCESS;
}
}
和一個視圖:
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title><s:text name="HelloWorld.message"/></title>
</head>
<body>
<h2>Hello the world!</h2>
</body>
</html>
只是目錄結構:
然後把工程部署到服務器上,這個不會的話自己百度。
在輸入url:
好了這就完成了。
我強調一下可能出錯的地方,在struts.xml中必須有這個包:
<package name="default" namespace="/" extends="struts-default">
</package>
其他的包在extends屬性上直接寫default就可以了。