前段时间再网上找了OA系统的源码,里面附带了一部分单点登录和身份校验的东西,我觉得他的单点有挺多我不满意的地方,一时
又没有好的解决办法,因此就只将里面的身份校验取了出来。
此处的身份校验主要用的是ThreadLocal,这个校验用的内网我感觉还是可以满足需求的,,先讲下思路:
session中存储一个visitor对象(visitor对象里面包含User),后台的每个请求都会访问Filter,然后取出session放进
ThreadLocal,到后台中从ThreadLocal中取出user进行当前登录对象判断。
这就是思路,听着简单,实现着应该会有些困难,详见代码
package cn.ljp.util;
import java.io.IOException;
import java.util.ResourceBundle;
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 javax.servlet.http.HttpSession;
import org.apache.log4j.PropertyConfigurator;
import cn.ljp.entity.User;
public class MyFilter implements Filter{
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest RQ =(HttpServletRequest) request;
HttpServletResponse rp=(HttpServletResponse) response;
HttpSession session = RQ.getSession();
Visitor v=(Visitor)session.getAttribute("visitor");
if(v==null){
Visitor vositor = new Visitor();
session.setAttribute("visitor", vositor);
}
myThreadLocal.setCurrentVisitor(v);
chain.doFilter(request, response);
}
public void login(){
user u =new user();
myThreadLocal.getCurrentVisitor().setU(u);
}
public String addIser(){
user u = myThreadLocal.getcurrentUser();
return null;
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
package cn.ljp.util;
public class Visitor {
private user u;
public user getU() {
return u;
}
public void setU(user u) {
this.u = u;
}
}
package cn.ljp.util;
public class myThreadLocal {
private static final ThreadLocal<Visitor> tl =new ThreadLocal<Visitor>();
public static synchronized void setCurrentVisitor(Visitor visitor){
tl.set(visitor);
}
public static Visitor getCurrentVisitor(){
return tl.get();
}
public static user getcurrentUser(){
Visitor currentVisitor = getCurrentVisitor();
return currentVisitor.getU();
}
}
ThreadLocal这个东西存储的key-value,不过他的生命周期仅限于一次请求,而且一个ThreadLocal只能存储一对key-value,
ThreadLocal这个东西是个好东西,多了解了解,以后工作中估计会用到不少