最近要用到Struts2 先研究一下 strtus2
1.先下载一个 Struts2
http://struts.apache.org 下载一个 Struts2
2. 新建一个web项目
加入如下包 commons-fileupload-1.2.1.jar, freemarker-2.3.15.jar, ognl- 2.7.3.jar, struts2-core-2.1.8.1.jar, xwork-core-2.1.6.jar 包
3. 配置 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 定义Struts 2的FilterDispatcher的Filter -->
<filter>
<!-- 定义核心Filter的名字 -->
<filter-name>struts2</filter-name>
<!-- 定义核心Filter的实现类 -->
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<!-- FilterDispatcher用来初始化Struts 2并且处理所有的Web请求 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
据说 以前的 filter 是
org.apache.struts2.dispatcher.FilterDispatcher
现在版本都改成:
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
4.写个页面
<br> <form action="Login.action" method="post"> <table align="center"> <caption> <h3> 用户登录 </h3> </caption> <tr> <!-- 用户名的表单域 --> <td> 用户名: <input type="text" name="userName" /> </td> </tr> <tr> <!-- 密码的表单域 --> <td> 密 码: <input type="text" name="password" /> </td> </tr> <tr align="center"> <td colspan="2"> <input type="submit" value="登录" /> <input type="reset" value="重填" /> </td> </tr> </table> </form>
5. 写个action
package com.test.web.action; public class LoginAction { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String execute() throws Exception { // 当用户请求参数的username等于scott,密码请求参数为tiger时,返回success字符串 // 否则返回error字符串 if (getUserName().equals("scott")&& getPassword().equals("tiger")){ return "success"; }else{ return "error"; } } }
6. 配置 struts.xml 文件
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <!-- struts是Struts 2配置文件的根元素 --> <struts> <!-- Struts 2的Action必须放在指定的包空间下定义 --> <package name="com.test.web.action" extends="struts-default"> <!-- 定义login的Action,该Action的实现类为lee.Action类 --> <action name="Login" class="com.test.web.action.LoginAction"> <!-- 定义处理结果和资源之间映射关系。 --> <result name="error">/error.jsp</result> <result name="success">/welcome.jsp</result> </action> </package> </struts>
好了运行一下。结果ok