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就可以了。