[Java] 纯文本查看 复制代码
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
User user = (User) req.getSession().getAttribute("existUser");
StringBuffer url = req.getRequestURL();
String contextPath = req.getContextPath();
String[] split = url.toString().split(contextPath);
String[] urls = {"/jsp/order_list.jsp","/jsp/order_info.jsp",
"/OrderServlet","/CartServlet",
"/jsp/cart.jsp"};
boolean flag = false;
for (String string : urls) {
flag = split[1].startsWith(string);
if(flag && user == null ){
req.setAttribute("msg", "您还没登录,请先登录");
req.getRequestDispatcher("/jsp/msg.jsp").forward(req, resp);
return;
}
}
//往当前线程中存已登陆用户
User exitUser = (User) req.getSession().getAttribute("existUser");
MyThreadLocalUtils.setObject(exitUser);
chain.doFilter(request, response);
}
[Java] 纯文本查看 复制代码
public class BeanFactory {
public static Object getBean(String objId){
try {
//读取配置文件
SAXReader saxReader = new SAXReader();
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("applicationContext.xml");
Document document = saxReader.read(in);
//获取配置文件中的对应的class属性值
Element ele = (Element) document.selectSingleNode("//bean[@id='"+objId+"']");
//根据class属性值获取创建对象
String classPath = ele.attributeValue("class");
Class clazz = Class.forName(classPath);
final Object obj = clazz.newInstance();
ClassLoader classLoader = obj.getClass().getClassLoader();
Class<?>[] interfaces = obj.getClass().getInterfaces();
MyInvocationHandler mih = new MyInvocationHandler(obj);
if(objId.endsWith("Dao")){
Object proxyInstance = Proxy.newProxyInstance(classLoader,interfaces,mih );
return proxyInstance;
}
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
class MyInvocationHandler implements InvocationHandler{
private Object obj;
public MyInvocationHandler(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().startsWith("save")){
System.out.println("权限校验=================");
//从ThreadLocal中获取User对象
User user = MyThreadLocalUtils.getUser();
if(user.getType() == 1){//管理员,可以执行保存操作
Object object = method.invoke(obj, args);
System.out.println("管理员,可以执行保存操作****************************");
return object;
}else{//普通用户,不可以执行保存操作
System.out.println("普通用户,不可以执行保存操作=================");
return null;
}
}
Object object = method.invoke(obj, args);
return object;
}
}