jsp,servlet利用过滤器解决中文乱码,和控制访问权限

  


encodingFitler
com.accp.filter.EcondingFilter


encoding
UTF-8





LoginFilter
com.accp.filter.LoginFilter


encodingFitler

/*


LoginFilter

/page/*

这个是过滤器解决中文乱码的类

 

package com.accp.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;
//过滤器类
public class EcondingFilter implements Filter {
private String charset = null;
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("filter销毁");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		System.out.println("doFilter前");
		//对请求的转码
		request.setCharacterEncoding(charset);
		//对回应的转码
		response.setCharacterEncoding(charset);
		chain.doFilter(request, response);
		System.out.println("doFilter后");
		
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("filter初始化");
		//读取初始化filter的参数
		charset=filterConfig.getInitParameter("encoding");
		System.out.println(charset);
	}

}
这个是过滤器控制用户权限的类

 

 

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

public class LoginFilter implements Filter {
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("filter销毁");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		System.out.println("doFilter前面");
		//获取HttpServletRequest通过,它的实例获取一个session
		HttpSession session = ((HttpServletRequest)request).getSession();
		//判断session中是否有数据
		if(session.getAttribute("user")!=null){
			System.out.println(session.getAttribute("user"));
			chain.doFilter(request, response);
			System.out.println("doFilter后");
		}else{
			String mes = "你还没有登录";
			System.out.println(mes);
			request.setAttribute("mes", mes);
			request.getRequestDispatcher("../login.jsp").forward(request, response);
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("filter被实例化");
		
	}

}

 过滤器无需我们在程序中调用,每次当我们获取web请求时,会首先自动的进入过滤器类。

 

你可能感兴趣的:(java)