下面两张图,用 viso 画了1个小时~ viso 很强大啊!
工作原理
Struts2的工作原理(图解)详解
Struts2基本原理
工作流程
Hello World Demo
web.xml
配置 Struts 2
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>HelloWorld.jsp</welcome-file>
</welcome-file-list>
<!-- Struts2配置 -->
<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>
struts.xml
配置每个Action。
<?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>
<package name="struts2" extends="struts-default">
<global-results>
<result name="login">/HelloWorld.jsp</result>
</global-results>
<action name="loginPerson" class="action.LoginAction">
<result name="success">/welcome.jsp</result>
</action>
</package>
</struts>
HelloWorld.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登录界面</title>
</head>
<body>
<form action="loginPerson">
<table>
<tr>
<td>账号</td>
<td><input type="text" name="account"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>欢迎界面</title>
</head>
<body>
welcome!
<%=request.getAttribute("account")%>
</body>
</html>
LoginAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String account;
private String password;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String execute() throws Exception {
if ("yano".equals(account) && "123456".equals(password)) {
return SUCCESS;
}
return LOGIN;
}
}