1 MVC 思想概述
2 Struts 2 的下载和安装
添加 Struts 2 的 jar 到项目 lib 目录,修改 web.xml 文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--定义 Struts 2 的核心 Filter--> <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>
src 目录下增加 struts.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <constant name="struts.enable.DynamicMethodInvocation" value="false"/> <constant name="struts.devMode" value="true"/> <constant name="struts.custom.i18n.resources" value="mess"/><!--src/mess.properties--> <package name="struts2" namespace="/" extends="struts-default"> <!--处理所有用户请求,直接呈现/WEB-INF/content下的同名JSP文件: 请求:http://localhost/loginForm 访问:/WEB-INF/content/loginForm.jsp --> <action name="*"> <result>WEB-INF/content/{1}.jsp</result> </action> </package> </struts>
loginPage=登录页面 errorPage=错误页面 succPage=成功页面 failTip=登陆失败 succTip=欢迎,{0},登陆成功 user=用户名 pass=密码 login=登陆
<%-- loginForm.jsp --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title><s:text name="loginPage"/></title> </head> <body> <s:form action="login"> <s:textfield key="user" name="username"/> <s:textfield key="pass" name="password"/> <s:submit key="login"/> </s:form> </body> </html>
public class LoginAction extends ActionSupport { 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; } @Override public String execute() throws Exception { if (getUsername().equals("admin") && getPassword().equals("123456")) { ActionContext.getContext().getSession().put("user", getUsername()); return SUCCESS; } else { return ERROR; } } }
在 struts.xml 增加一个 name 为“login的 action:
<action name="login" class="com.hundsun.action.LoginAction"> <result name="success">/WEB-INF/content/welcome.jsp</result> <result name="error">/WEB-INF/content/error.jsp</result> </action>
3 Struts 2 的流程
4 Struts 2 的常规配置
时间: 2024-10-26 21:06:26