JavaWeb上的Servlet拦截器_u010800530的专栏-程序员宅基地_java拦截servlet

技术标签: filter  java  javaweb  servlet  web.xml  

今天就是别人教做一个拦截器,然后就跟着做了,下边就是写下怎么做出来拦截器的。

拦截器就是在做一个网站的时候,如果没有通过界面登陆,却要进入某个页面,就会拦截下来。

首先要写的是一个myFilter.java函数:

package com.newtest.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;

public class myFilter implements Filter{

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

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		
		
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse reponse = (HttpServletResponse) arg1;
		
		if(request.getSession().getAttribute("student") == null && request.getRequestURI().indexOf("Test.jsp") ==-1){
			
			reponse.sendRedirect("Test.jsp");
			
		}
		arg2.doFilter(arg0, arg1);
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}

然后做一下web.xml的配置:

<filter>
	
	<filter-name>myFilter</filter-name>
	<filter-class>com.newtest.filter.myFilter</filter-class>
	</filter>
	<filter-mapping>
	
	<filter-name>myFilter</filter-name>
	<url-pattern>/*</url-pattern>
	
	</filter-mapping>

基本上一个简单的拦截器就完成了

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u010800530/article/details/36175987

智能推荐

随便推点