使用Filter过滤器,控制不能直接访问JSP文件

在项目中,我们需要控制用户不能直接访问JSP页面,需要实现此功能很简单,1.使用过滤器控制如果用户请求了JSP页面,直接跳转到指定的URL,如主页,2.在web.xml文件中配置,当服务器启动时,自动加载过滤器


1、编码JspFilter过滤器,需要实现Filter

package com.weixin.common.filter;

import java.io.IOException;

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;

/**
 * JSP过滤器,不能直接访问JSP
 * 
 * @author Administrator
 *
 */
public class JspFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		String url = httpServletRequest.getRequestURI();
		if (url != null && url.endsWith(".jsp")) {
			// TODO 这里可以跳转到主页
			String contextPath = httpServletRequest.getContextPath();
			httpServletResponse.sendRedirect(contextPath + "/user/index.do");
			return;
		}
		chain.doFilter(httpServletRequest, httpServletResponse);

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}


2、web.xml中配置过滤器,当服务器启动时,自动加载过滤器

  
  
  	jspFilter
  	com.weixin.common.filter.JspFilter
  
  
  	jspFilter
  	/*
  
  



你可能感兴趣的:(使用Filter过滤器,控制不能直接访问JSP文件)