记住我 验证码

package cn.itcast.elec.util;

 

import java.io.IOException;

import java.net.URLDecoder;

import java.util.ArrayList;

import java.util.List;

 

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.Cookie;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import cn.itcast.elec.domain.ElecUser;

 

public class SystemFilter implements Filter {

 

//存放需要放行的连接

List<String> list = new ArrayList<String>();

 

public void init(FilterConfig config) throws ServletException {

//定义系统在没有Session之前哪些连接需要放行

list.add("/index.jsp");

list.add("/image.jsp");

list.add("/system/elecMenuAction_home.do");

 

list.add("/error.jsp");

list.add("/system/elecMenuAction_logout.do");

}

 

public void doFilter(ServletRequest req, ServletResponse res,

FilterChain chain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;

HttpServletResponse response = (HttpServletResponse) res;

//获取访问的路径path

String path = request.getServletPath();

//当访问的路径path包含index.jsp的时候,此时从Cookie中获取登录名和密码,并在index.jsp中进行显示,处理记住我的功能

this.forwardIndexPage(path,request);

 

//使用Session控制系统的粗颗粒度权限控制

//如果访问的路径path包含在定义的连接内,此时都需要放行

if(list.contains(path)){

chain.doFilter(request, response);

return;

}

//从Session中获取当前用户的信息

ElecUser elecUser = (ElecUser) request.getSession().getAttribute("globle_user");

if(elecUser!=null){

//使用页面地址栏输入访问的url,实现细颗粒度权限控制

//从Session中获取当前登录人所能够操作的url

List<String> urlList = (List<String>) request.getSession().getAttribute("globle_url");

if(urlList.contains(path)){

chain.doFilter(request, response);

return;

}

}

//重定向到登录页面

//response.sendRedirect(request.getContextPath()+"/");

//跳转到错误页面,5秒钟后跳转到登录页面(友好)

response.sendRedirect(request.getContextPath()+"/error.jsp");

}

 

 

 

public void destroy() {

 

}

 

/**当访问的路径path包含index.jsp的时候,此时从Cookie中获取登录名和密码,并在index.jsp中进行显示,处理记住我的功能*/

private void forwardIndexPage(String path, HttpServletRequest request) {

if(path.contains("/index.jsp")){

String name = "";

String password = "";

String checked = "";

Cookie [] cookies = request.getCookies();

if(cookies!=null && cookies.length>0){

for(int i=0;i<cookies.length;i++){

Cookie cookie = cookies[i];

if(cookie!=null && cookie.getName().equals("name")){

name = cookie.getValue();

//如果name中存在中文的话,对值进行解码

try {

name = URLDecoder.decode(name, "UTF-8");

} catch (Exception e) {

e.printStackTrace();

}

checked = "checked";

}

else if(cookie!=null && cookie.getName().equals("password")){

password = cookie.getValue();

}

}

}

//将3个值放置到request中

request.setAttribute("name", name);

request.setAttribute("password", password);

request.setAttribute("checked", checked);

}

 

}

 

 

 

 

}

 

你可能感兴趣的:(验证码)