案例:
用户登录
login.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录页面</title> </head> <body> <form action="${ pageContext.request.contextPath }/login.action" method="post"> <table align="center"> <caption><h3>用户登录</h3></caption> <tr> <td>用户名:</td> <td><input type="text" name="username" /></td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="password" /></td> </tr> <tr align="center"> <td colspan="2"><input type="submit" value="登录" /> <input type="reset" value="重置" /></td> </tr> </table> </form> </body> </html>
LoginAction代码:
package com.itheima.action; import com.itheima.domain.User; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class LoginAction extends ActionSupport implements ModelDriven<User> { private static final long serialVersionUID = 6114481653813951691L; private User user = new User(); @Override public User getModel() { return user; } public String login() { if ("tom".equals(user.getUsername()) && "123".equals(user.getPassword())) { return "success"; } else { return "fail"; } } }
Welcome.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录成功页面</title> </head> <body> <p>Welcome!</p> </body> </html>
error.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登录失败页面</title> </head> <body> <p>Fail!!!</p> </body> </html>
struts.xml配置:
<?xml version="1.0" encoding="UTF-8" ?> <!-- 指定Struts2配置文件的DTD信息 --> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <!-- struts是Struts2配置文件的根元素 --> <struts> <constant name="struts.devMode" value="true" /> <!-- Struts2的Action必须在指定的包空间下定义 --> <package name="default" namespace="/" extends="struts-default"> <!-- 定义login的Action,该Action的实现类为 com.itheima.action.LoginAction 类 --> <action name="login" class="com.itheima.action.LoginAction" method="login"> <!-- 定义处理结果与资源之间映射关系 --> <result name="success">/welcome.jsp</result> <result name="fail">/error.jsp</result> </action> </package> </struts>
web.xml配置:
<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>