配置Struts2后如何使用servlet

有时候,我们在配置了Struts2后还会想用servlet,但是默认是用不了的,都被struts2拦截了,并在struts.xml中匹配是否有该action

那么,如何使用呢?

1.新建一个filter,用于过滤servlet

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

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

public class ReDispatcherFilter implements Filter {
	private ArrayList<String> includes = new ArrayList<String>();

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String target = request.getRequestURI();
		target = target.lastIndexOf("?") > 0 ? target.substring(
				target.lastIndexOf("/") + 1,
				target.lastIndexOf("?") - target.lastIndexOf("/")) : target
				.substring(target.lastIndexOf("/") + 1);
		if (this.includes.contains(target)) {
			RequestDispatcher rdsp = request.getRequestDispatcher(target);
			rdsp.forward(req,resp);
		} else
			chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		this.includes.addAll(Arrays.asList(config.getInitParameter(
				"includeServlets").split(",")));
	}

}


2.在web.xml中做适当配置,在struts2的配置前加上下面的代码:

 <filter>
    <filter-name>redisp</filter-name>
    <filter-class>com.kcjxkj.filter.ReDispatcherFilter</filter-class>
    <init-param>
      <param-name>includeServlets</param-name>
      <param-value>ValidateEmail</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>redisp</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

其中,<param-value></param-value>中为web.xml中配置的要过滤的servlet名,多个之间用","逗号隔开

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值