关闭

filter的应用

176人阅读 评论(0) 收藏 举报

1、设置字符集

package net.company.web.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 CharacterEncoding implements Filter {
    private String encode;
 public void destroy() {
 }
 public void doFilter(ServletRequest req, ServletResponse resp,
   FilterChain chain) throws IOException, ServletException {
  //设置所以的request和response的字符集为encode
  req.setCharacterEncoding(encode);
  resp.setCharacterEncoding(encode);
  chain.doFilter(req, resp);
 }

 public void init(FilterConfig config) throws ServletException {
  //从web.xml中读取配置信息
  this.encode=config.getInitParameter("code");
 }

}

 

 

2、粗粒度的权限控制

package net.company.web.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;

import net.company.entity.Employees;

public class PrivilegeFilter implements Filter{

 public void destroy() {
  // TODO Auto-generated method stub
  
 }
    //粗粒度的权限控制
 public void doFilter(ServletRequest arg0, ServletResponse arg1,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest req=(HttpServletRequest)arg0;
  HttpServletResponse resp=(HttpServletResponse)arg1;
  Employees employee=(Employees)req.getSession().getAttribute("employee");
  if(employee==null){
   req.setAttribute("result", "please logon ....");
   req.getRequestDispatcher("/logon.jsp").forward(req, resp);
      return;
  }
  chain.doFilter(req, resp);
  
 }

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

}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:126482次
    • 积分:2719
    • 等级:
    • 排名:第14148名
    • 原创:106篇
    • 转载:49篇
    • 译文:1篇
    • 评论:5条
    文章分类
    最新评论