Struts2配置文件及filer运行原理探析

Struts2作为一个成熟的web框架,以其使用的便捷性赢得了大量拥簇,今天我就来手动创建一个类似于struts.xml的配置文件,并手动编写一个与struts2主过滤器作用相同的filter,仅供大家参考。

1、创建web项目。修改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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Struts2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
        <filter-name>struts</filter-name>
        <filter-class>com.js.filter.StrutsFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>


2、创建配置文件,struts.xml(位于src目录下),内容如下:

<?xml version="1.0" encoding="UTF-8" ?>
<struts>
    	<action name="hello" class="com.js.action.HelloAction" method="say">
    		<result name="good">/hello.jsp</result>
    	</action>
</struts>


3、编写主过滤器,StrutsFilter,以及action类,HelloAction,代码如下:

package com.js.filter;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class StrutsFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
//		1、强转
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;
//		2、操作
//	    2.1、得到请求资源路径
		String uri = request.getRequestURI();
		String context = request.getContextPath();
		String path = uri.substring(context.length()+1);
//		2.2、使用path去struts.xml文件中查找某一个action name = path值的action
		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(new File(this.getClass().getResource("/struts.xml").getPath()));
			Element element = (Element) document.selectSingleNode("//action[@name='"+path+"']");//查找<action name="hello">这样的标签
			if(element!=null){
				//得到action的class属性和method属性
				String className = element.attributeValue("class");
				String methodName = element.attributeValue("method");
//				2.3、通过反射,得到Class对象、得到Method对象
				Class actionclClass = Class.forName(className);
				Method method = actionclClass.getDeclaredMethod(methodName);
//				2.4、让method方法执行
				String returnValueString=(String) method.invoke(actionclClass.newInstance());
//				2.5、使用returnValue去action下查找其子元素result的name属性值,与returnValue做对比
				Element resultElement = element.element("result");
				String  namestrString = resultElement.attributeValue("name");
				if(returnValueString.equals(namestrString)){
//				2.6、得到了要跳转的路径
					String skipPath = resultElement.getText();
					request.getRequestDispatcher(skipPath).forward(request, response);
					return;
				}
			}
		} catch (DocumentException | ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
//	    3、放行
		arg2.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
}

package com.js.action;

public class HelloAction {
	public String say() {
		return "good";
	}
}



5、编写页面index.jsp和hello.jsp,内容如下(名称、内容一一对应):

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/hello">手动实现struts2</a>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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=utf-8">
<title>Insert title here</title>
</head>
<body>
	<h1>hello struts2</h1>
</body>
</html>

部署项目并运行,点击index.jsp页面的超链接,也实现了跳转到hello.jsp页面的功能,说明手动实现了过滤功能,并能根据请求路径去查找对应的action类对http请求进行处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值