Java进阶知识03 Struts2下的拦截器(interceptor)和 过滤器(Filter)
一、拦截器
1.1、首先创建一个拦截器类
1 package com.bw.bms.interceptor; 2 3 import com.opensymphony.xwork2.ActionContext; 4 import com.opensymphony.xwork2.ActionInvocation; 5 import com.opensymphony.xwork2.ActionProxy; 6 import com.opensymphony.xwork2.interceptor.AbstractInterceptor; 7 8 /** 9 * @author DSHORE/2019-9-5 10 * 拦截器:拦截action 11 */ 12 public class LoginInterceptor extends AbstractInterceptor { 13 14 @Override //对Action的方法的拦截(核心方法),注:这里,其他方法都删掉了,只留了核心方法 15 public String intercept(ActionInvocation invocation) throws Exception { 16 // 拿到当前执行的方法名,判断,只要当前方法名不是login,就要进行验证 17 // 获取ActionContext对象 18 ActionContext context = invocation.getInvocationContext(); 19 // 获取action的代理对象 20 ActionProxy proxy = invocation.getProxy(); 21 // 获取当前执行的方法名 22 String methodName = proxy.getMethod(); 23 // 判断 24 //System.out.println("methodName:" + methodName); 25 if (!"login".equals(methodName)) { 26 // 先获取当前登录的用户 27 String account = (String) context.getSession().get("account"); 28 System.out.println("account:" + account); 29 if (account == null) { // 未登录 30 return "input"; 31 } else { // 当前用户已经登录 32 return invocation.invoke(); //invocation.invoke():返回值 success/error 33 } 34 } else { 35 // 正在执行login操作 36 return invocation.invoke(); 37 } 38 } 39 }
1.2、配置拦截器 struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 6 <struts> 7 <!-- true支持动态方法调用 --> 8 <constant name="struts.enable.DynamicMethodInvocation" value="true" /> 9 <constant name="struts.devMode" value="true" /> <!-- true --> 10 11 12 13 <package name="manager" namespace="/manager" extends="struts-default"> 14 15 <!-- -------------------------------------------------------------- --> 16 <!-- 【拦截器配置,开始】 --> 17 <interceptors> 18 <!-- 配置用户自定义的拦截器 --> 19 <interceptor name="loginInterceptor" class="com.bw.bms.interceptor.LoginInterceptor"></interceptor> 20 <!-- 自定义一个栈: 要引用默认栈、自定义的拦截器 --> 21 <interceptor-stack name="loginStack"> 22 <!-- 引用默认栈 (一定要放到第一行) --> 23 <interceptor-ref name="defaultStack"></interceptor-ref> 24 <!-- 引用自定义拦截器 --> 25 <interceptor-ref name="loginInterceptor"></interceptor-ref> 26 <!-- 指定拦截哪些方法需要防止表单重复提交(add) --> 27 <interceptor-ref name="token"> 28 <param name="includeMethods">login,add,update,delete</param> <!-- excludeMethods:指定哪些不拦截 --> 29 </interceptor-ref> 30 </interceptor-stack> 31 </interceptors> <!-- 【拦截器配置,结束】 --> 32 33 <!-- 【执行拦截器】 --> 34 <default-interceptor-ref name="loginStack"></default-interceptor-ref> 35 <!-- -------------------------------------------------------------- --> 36 37 <action name="*_*" class="com.bw.bms.action.{1}Action" method="{2}"> 38 <result name="success">/manager/{1}_{2}_Success.jsp</result><!-- 登陆成功、查询所有 --> 39 <result name="error">/manager/{1}_{2}_Error.jsp</result><!-- 登录时,账号或密码错误 --> 40 <result name="input" type="redirect">/index.jsp</result><!-- 用户不存在、注销成功、未登录转态 --> 41 <result name="operateSuccess" type="redirectAction">Book_list</result><!-- 添加、删除、修改操作 --> 42 <result name="update">/manager/Book_update.jsp</result><!-- 根据id查询指数据 --> 43 44 <!-- 防止表单重复提交,第三步: 如果用户重复提交了跳转到指定的错误页面 --> 45 <result name="invalid.token" type="redirectAction">Book_list</result> 46 </action> 47 </package> 48 </struts>
1.3、登录和注销的代码
1 package com.bw.bms.action; 2 3 import java.util.Map; 4 5 import com.bw.bms.model.Admin; 6 import com.bw.bms.service.IAdminService; 7 import com.bw.bms.service.impl.AdminService; 8 import com.opensymphony.xwork2.ActionContext; 9 import com.opensymphony.xwork2.ActionSupport; 10 import com.opensymphony.xwork2.ModelDriven; 11 12 /** 13 * @author DSHORE/2019-9-5 14 * 15 */ 16 public class AdminAction extends ActionSupport implements ModelDriven<Admin> { 17 // 使用了模型驱动进行传参,对象必须创建 18 private Admin admin = new Admin(); 19 20 IAdminService adminService = new AdminService(); 21 22 @Override 23 public Admin getModel() { 24 return admin; 25 } 26 27 //登录 28 public String login() { 29 String account = admin.getAccount().trim(); 30 String password = admin.getPassword().trim(); 31 Admin adm = adminService.findByAccount(account); 32 if (adm == null) { // 用户不存在,重新登录 33 return INPUT; 34 } else { 35 if (password.equals(adm.getPassword())) { 36 ActionContext.getContext().getSession().put("account", account); 37 return SUCCESS; 38 } else { // 密码错误,重新登录 39 return ERROR; 40 } 41 } 42 } 43 44 //注销 45 public String logout() { 46 Map<String, Object> session = ActionContext.getContext().getSession(); 47 //String acc = (String) session.get("account"); //Map<"account","huang"> 48 if (session.get("account") != null) { 49 session.remove("account"); 50 } 51 return INPUT; 52 } 53 54 public Admin getAdmin() { 55 return admin; 56 } 57 58 public void setAdmin(Admin admin) { 59 this.admin = admin; 60 } 61 }
1.4、其他代码(上方struts.xml配置文件中action里面相关的代码)
1 package com.bw.bms.action; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 import com.bw.bms.model.Book; 7 import com.bw.bms.service.IBookService; 8 import com.bw.bms.service.impl.BookService; 9 import com.opensymphony.xwork2.ActionContext; 10 import com.opensymphony.xwork2.ActionSupport; 11 import com.opensymphony.xwork2.ModelDriven; 12 import com.opensymphony.xwork2.util.ValueStack; 13 14 /** 15 * @author DSHORE/2019-9-5 16 * 17 */ 18 public class BookAction extends ActionSupport implements ModelDriven<Book> { 19 private Book book = new Book(); 20 private List<Book> books = new ArrayList<Book>(); 21 22 IBookService bookService = new BookService(); 23 24 //查询所有 25 public String list() { 26 books = bookService.listAll(); 27 return SUCCESS; 28 } 29 30 //添加 31 public String add() { 32 bookService.add(book); 33 return "operateSuccess"; 34 } 35 36 //删除 37 public String delete() { 38 Integer id = book.getId(); 39 bookService.delete(id); 40 return "operateSuccess"; 41 } 42 43 //查询指定id的数据(执行修改操作前,需要先查询出要修改的那条数据) 44 public String toUpdate() { 45 Integer id = book.getId(); 46 Book updateBook = bookService.findById(id); 47 ValueStack valueStack = ActionContext.getContext().getValueStack();// 先进后出 48 valueStack.pop(); // 移除栈顶元素 49 valueStack.push(updateBook); // 压栈 50 return "update"; 51 } 52 53 //修改 54 public String update() { 55 bookService.update(book); 56 return "operateSuccess"; 57 } 58 59 @Override 60 public Book getModel() { 61 return book; 62 } 63 64 public Book getBook() { 65 return book; 66 } 67 68 public void setBook(Book book) { 69 this.book = book; 70 } 71 72 public List<Book> getBooks() { 73 return books; 74 } 75 76 public void setBooks(List<Book> books) { 77 this.books = books; 78 } 79 }
二、过滤器
2.1、自定义一个过滤器(和上面的拦截器是一套代码里面的)
EntranceFilter.Java 类
1 package com.bw.bms.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import javax.servlet.http.HttpSession; 14 15 /** 16 * @author DSHORE/2019-9-5 17 * 过滤器:过滤页面(jsp、html等页面) 18 */ 19 public class EntranceFilter implements Filter { 20 21 @Override 22 public void destroy() { 23 // TODO Auto-generated method stub 24 } 25 26 @Override 27 public void doFilter(ServletRequest request, ServletResponse response, 28 FilterChain chain) throws IOException, ServletException { 29 HttpServletRequest servletRequest = (HttpServletRequest) request; 30 HttpServletResponse servletResponse = (HttpServletResponse) response; 31 HttpSession session = servletRequest.getSession(); 32 33 // 获得用户请求的URI 34 String path = servletRequest.getRequestURI(); 35 System.out.println("###########path:" + path); 36 // 从session里取 37 String account = (String) session.getAttribute("account"); 38 // 判断当前的jsp是否是index.jsp,如果是放行,否则的话:(1)已经登录——放行、(2)未登录——index.jsp 39 if ((path.indexOf("login.action") > -1 ) || (path.indexOf("index.jsp") > -1 )) { 40 /** 41 * index.jsp 不需要过过滤 Admin_login.action 不需要过过滤, 42 * Admin_login_Success.jsp 需要过滤,不允许进来 Admin_login_Error.jsp 43 */ 44 System.out.println("!!!!!!!!!!!!!path:" + path); 45 chain.doFilter(servletRequest, servletResponse); 46 return; 47 } else { 48 // 判断如果没有取到管理员信息,就跳转到登陆页面 49 if (account == null || "".equals(account)) { // account.equals("")错误 50 // 跳转到登陆页面 51 String basePath = request.getScheme() + "://" 52 + request.getServerName() + ":" 53 + request.getServerPort() 54 + ((HttpServletRequest) request).getContextPath(); 55 servletResponse.sendRedirect(basePath + "/index.jsp"); 56 } else { // 通过 57 // 已经登陆,继续此次请求 58 chain.doFilter(request, response); 59 } 60 } 61 } 62 63 @Override 64 public void init(FilterConfig arg0) throws ServletException { 65 // TODO Auto-generated method stub 66 } 67 }
web.xml 配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 6 <display-name></display-name> 7 <welcome-file-list> 8 <welcome-file>index.jsp</welcome-file> 9 </welcome-file-list> 10 11 <filter><!-- 自定义过滤器 开始--> 12 <filter-name>EntranceFilter</filter-name> 13 <filter-class>com.bw.bms.filter.EntranceFilter</filter-class> 14 </filter> 15 <filter-mapping> 16 <filter-name>EntranceFilter</filter-name> 17 <url-pattern>/*</url-pattern> 18 <url-pattern>/manager/*</url-pattern> 19 </filter-mapping><!-- 自定义过滤器 结束--> 20 21 <filter> 22 <filter-name>struts2</filter-name> 23 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 24 </filter> 25 <filter-mapping> 26 <filter-name>struts2</filter-name> 27 <url-pattern>/*</url-pattern> 28 </filter-mapping> 29 </web-app>
Servlet下的过滤器(filter)
原创作者:DSHORE 作者主页:http://www.cnblogs.com/dshore123/ 原文出自:https://www.cnblogs.com/dshore123/p/11469227.html 欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!) |