MVC思想
Sturts2的下载与安装
Struts2的流程
Struts2应用的开发步骤
1.在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_4_0.xsd"
version="4.0">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.编写相应请求
如果需要以POST方式提交请求,则定义包含表单数据的JSP页面。如果仅仅只是以GET方式发送请求则无需经过这一步
编写loginForm.jsp
<%@ taglib prefix="S" uri="/struts-tags" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%--
Created by IntelliJ IDEA.
User: gao
Date: 2020/3/12
Time: 13:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title><s:text name="loginPage"/></title>
</head>
<body>
<S:form action="login">
<S:textfield name="user" key="pass"/>
<S:textfield name="password" key="pass"/>
<S:submit key="login"/>
</S:form>
</body>
</html>
3.定义处理用户请求的Action类
该类相当于MVC中的C
编写LoginAction.java
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String userName;
private String pass;
public String getUsername(){
return userName;
}
public void setUser(String username) {
userName = username;
}
public String getPassword(){
return pass;
}
public void setPassword(String password){
this.pass=password;
}
public String execute() throws Exception {
if(getUsername().equals("aaa")&&getPassword().equals("aaa")){
return SUCCESS;
}else{
return ERROR;
}
}
}
当用户提交请求后,Servlet或者Filter接受到用户的请求,通常会对用户的请求进行简单的预处理,然后通过反射来创建Action实例,并调用Action指定的方法。
如何实现映射:
利用配置文件,或者利用约定。
4.配置Action
<action name="login" class="LoginAction">
</action>
如果用户的请求名为login则使用LoginAction来处理。
5.配置处理结果和物理视图资源之间的对应关系
<result name="error">error.jsp</result>
<result name="success">welocme.jsp</result>
当Action处理用户请求结束后,通常会返回一个结果,
将这个结果与指定的物理视图资源关联。
4~5操作均在strtus.xml文件中
6.编辑视图资源
<%--
Created by IntelliJ IDEA.
User: gao
Date: 2020/3/12
Time: 13:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
登陆成功
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: gao
Date: 2020/3/12
Time: 13:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
登陆失败
</body>
</html>
运行结果
Struts2运行流程
由图可知StrutsPrepareAndExcuteFilter和XXXAction共同组成Struts2的控制器。StrutsPrepareAndExcuteFilter核心控制器,XXXAction业务控制器。
点击链接加入群聊【程序员技术交流群】:添加链接描述