Struts2是基于过滤器的一个MVC框架。
准备工作:新建一个web项目,向WEB-INF里面的lib下添加必要的jar并引用到项目中,配置web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Struts2</display-name>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
这里添加了一个过滤器,让所有页面必须经过我们的struts2
接下来在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>
<package name="default" namespace="/" extends="struts-default">
<action name="Structs" class="com.imooc.action.struts2">
<result>
/result.jsp
</result>
</action>
</package>
</struts>
然后创建action就是一个类,
package com.imooc.action;
import com.opensymphony.xwork2.ActionSupport;
public class struts2 extends ActionSupport {
@Override
public String execute() throws Exception{
System.out.println("执行Action");
return SUCCESS;
}
}
最后把这个result.jsp,放在index.jsp一个目录即可
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
this is result.jsp
</body>
</html>
这里说一下
struts2的工作原理
用户请求经过过滤器到达ActionMapper,ActionMapper把action后缀的请求发给ActionProxy,ActionProxy找到struts.xml,找到对应的类,执行后经拦截器输出result
再经拦截器响应用户
struts核心文件
web.xml 配置拦截器
struts2.xml 写action的映射,并写处理Result等等作用
主要标签有: include用于包含其他的struts2文件,这个可以用来区分功能模块
package:name值为包名,子标签可以配置拦截器,子标签action用于定义action