今天开始学习Struts2了,Struts2使用了MVC的设计模式,使Java web应用层次更分明,是非常流行的一种框架,下面我记录在Java web应用中添加Struts2支持的几个步骤:
一、在MyEclipse中新建普通的Java web应用
这里我们给工程取名为Struts2App,项目结构如上图所示
二、在lib文件夹中加入Struts2依赖的jar包
其实MyEclipse可以自动给我们创建的web应用添加Struts支持,但是这里我不打算使用MyEclipse的功能,而是自己手动将Struts2加入到工程里,导入的jar包主要有如下几个:
上面的jar包可以从http://www.apache.org/的官网上获取
三、编写web.xml文件
默认情况下,新建的Java web项目中的web.xml文件是这样子的:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
web.xml文件在项目的/WebRoot/WEB-INF路径下,我们需要编辑该文件,在文件中加入过滤器,通过配置过滤器,使url请求交给Struts来处理,编辑好的web.xml文件代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
我们在web.xml文件中加入了filter和filter-mapping标签,这样就设置了struts2的过滤器,上面的url-pattern指定了过滤的url的类型为/*,即过滤所有类型的url
四、编写struts.xml文件
struts.xml文件是Struts2框架中的核心文件,所有被过滤的请求都会通过struts.xml文件来处理,我们在项目的src目录下新建xml文件,命名为struts.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd" >
<struts>
<package name="example" extends="struts-default">
<action name="login" class="com.test.action.LoginAction">
<result name="ok">/ok.jsp</result>
</action>
</package>
</struts>
上面的配置文件里,指定了package和action、result等标签,package类似于Java工程里的包,不过上面的包继承了struts-default包,然后在包中有一个action,名字为login,对应的class为com.test.action.LoginAction,这里的意思就是,名为login的请求,会交给com.test.action.LoginAction的类来处理,这个LoginAction类,是一个普通的Java类,不继承任何类,不实现任何接口,其代码如下:
package com.test.action;
public class LoginAction {
public String execute() throws Exception{
return "ok";
}
}
可以看到,LoginAction类中的代码,就一个方法:execute(),该方法返回值为String类型,这里的返回值对应了上面的struts.xml文件中的result标签,即当LoginAction返回"ok"时,会在struts.xml文件中找到ok对应的JSP页面即ok.jsp,然后请求会转发给ok.jsp
五、编写ok.jsp页面
六、测试运行
我们将项目部署到tomcat,在浏览器中输入:http://localhost:8080/Struts2App/login,访问后出现的即为ok.jsp页面中的内容