-------------------siwuxie095
使用过滤器进行权限校验
一个简单的权限校验过滤器实例:
登录状态校验:如果没有成功登录就没有权限访问特定页面
当访问首页要进入
hello.jsp 页面时,首先判断是否处于登录状态:
(1)如果是,直接点击进入
hello.jsp
(2)如果否,则点击 hello.jsp 时进入 login.jsp,登录成功后自动跳转回 hello.jsp
工程结构目录如下:
后端代码:
LoginServlet.java:
package com.siwuxie095.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // LoginServlet 继承自 HttpServlet public class LoginServlet extends HttpServlet { /** * 用于序列化和反序列化的 ID */ private static final //覆盖父类 HttpServlet 的 doGet() 方法 @Override protected System.out.println("===== doGet ====="); //在 doGet() 方法里调用 doPost() 方法 //这样,GET请求和POST请求可以共用一套处理逻辑 doPost(req, resp); } //覆盖父类 HttpServlet 的 doPost() 方法 @Override protected System.out.println("===== doPost ====="); String userName=req.getParameter("uname"); String password=req.getParameter("upwd"); /** * returnUri是用户访问登录页面之前所访问的页面 * 通过这个值,登录成功后,可以跳转回登录前的页面 */ String returnUri=req.getParameter("return_uri"); System.out.println("用户名:"+userName); System.out.println("密码:"+password); System.out.println("return uri:"+returnUri); String forward=null; if (userName.equals("李白")&&password.equals("8888")) { //如果用户登录成功,就在当前用户的session对象中 //保存key为flag,value为login_success的字符串 //表明当前用户处于登录状态 req.getSession().setAttribute("flag", "login_success"); //如果returnUri不为空,就进入用户访问登录页面之前所访问的页面 if (returnUri!=null) { forward=returnUri; }else{ forward="/index.jsp"; } }else { req.getSession().setAttribute("flag", "login_error"); req.setAttribute("msg", "用户名或密码错误!!!"); forward="/login.jsp"; } RequestDispatcher rd=req.getRequestDispatcher(forward); rd.forward(req, resp); } } |
LogoutServlet.java:
package com.siwuxie095.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LogoutServlet extends HttpServlet { private static final public LogoutServlet() { super(); } protected doPost(req, resp); } protected //退出逻辑,直接删除session对象 req.getSession().invalidate(); //跳转回首页 resp.sendRedirect(req.getContextPath()+"/index.jsp"); } } |
EncodingFilter.java:
package com.siwuxie095.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 EncodingFilter implements Filter { //声明一个成员变量 private String charEncoding=null; public EncodingFilter() { } public //在部署描述符中设置该应用的默认字符编码集 charEncoding=fConfig.getInitParameter("encoding"); //如果字符编码的名称没有设置 if (charEncoding==null) { throw new ServletException("EncodingFilter中的编码设置为空!!!"); } } public //如果当前应用的默认编码,与请求中的编码值不一致 if (!charEncoding.equals(request.getCharacterEncoding())) { //那么就将请求中的编码设置成当前默认的编码设置 request.setCharacterEncoding(charEncoding); } //将响应的编码设置也改成当前默认的编码设置 response.setCharacterEncoding(charEncoding); chain.doFilter(request, response); } public } } |
PermissionFilter.java:
package com.siwuxie095.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.RequestDispatcher; 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; public class PermissionFilter implements Filter { public PermissionFilter() { } public } public throws IOException, ServletException { /** * 首先将参数中的ServletRequest和ServletResponse强制转换为 * HttpServletRequest和HttpServletResponse */ HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; // 获取请求中的ServletPath,即servlet的路径 String servletPath = req.getServletPath(); // 获取session对象 HttpSession session = req.getSession(); // 获取session对象中的flag值,需强转 String flag = (String) session.getAttribute("flag"); // 如果用户访问的是首页index.jsp 或者是login.jsp //或者执行登录操作 if (servletPath != null && (servletPath.equals("/login.jsp") || (servletPath.equals("/index.jsp")) || (servletPath.equals("/loginServlet")))) { chain.doFilter(request, response); } else { /** * 业务逻辑: * * 如果用户处于登录状态 */ if (flag != null && flag.equals("login_success")) { chain.doFilter(request, response); } else if (flag != null && flag.equals("login_error")) { /** * 如果用户登录失败 * 同时提示用户,登录失败 */ req.setAttribute("msg", "登录失败,请重新登录!!!<br/>"); // 把用户所访问的url保存到request对象中 req.setAttribute("return_uri", servletPath); RequestDispatcher rd = req.getRequestDispatcher("/login.jsp"); rd.forward(req, resp); } else { // 如果用户没有登录 req.setAttribute("msg", "您尚为登录!!!"); // 同样将用户访问的url保存到request对象中 req.setAttribute("return_uri", servletPath); RequestDispatcher rd = req.getRequestDispatcher("/login.jsp"); rd.forward(req, resp); } } } public } } |
前端代码:
login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <html> <head> <meta <title>登录页面</title> <script function check(form){ if(document.forms.loginForm.uname.value==""){ alert("请输入用户名!"); document.forms.loginForm.uname.focus(); return false; } if(document.forms.loginForm.upwd.value==""){ alert("请输入密码!"); document.forms.loginForm.upwd.focus(); return false; } } </script> <style type="text/css"> body { color: #000; font-size =14px; margin: 20px, auto; } </style> </head> <body> <!-- 添加表单,url在部署描述符中进行配置,使用post方式来提交 --> <form <!-- 添加一个隐藏域,用于保存returnUri --> <% <input <% } %> <table <tr> <td </tr> <tr> <td>用户名:</td> <td><input </tr> <tr> <td>密码:</td> <td><input </tr> <tr> <td <input <input </td> </tr> </table> </form> </body> </html> |
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <html> <head> <meta <title>首页</title> </head> <body> 首页<br/><br/> <a <%-- 从 session 中获取用户的登录状态 --%> <% String flag = ""; Object obj=session.getAttribute("flag"); if(obj!=null){ flag=obj.toString(); } if(flag.equals("login_success")){ %> <a <% }else{ %> <a <% } %> </body> </html> |
hello.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" <html> <head> <meta <title>Hello World</title> </head> <body> <% out.print("Hello World<br/>"); %> <a </body> </html> |
在部署描述符
web.xml 中注册 servlet 和 filter:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <display-name>MyFilter</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.siwuxie095.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>LogoutServlet</servlet-name> <servlet-class>com.siwuxie095.servlet.LogoutServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LogoutServlet</servlet-name> <url-pattern>/logoutServlet</url-pattern> </servlet-mapping> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>com.siwuxie095.filter.EncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>PermissionFilter</filter-name> <filter-class>com.siwuxie095.filter.PermissionFilter</filter-class> </filter> <filter-mapping> <filter-name>PermissionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> |
部署描述符
web.xml 在 WEB-INF 目录下,如果没有,手动创建即可
选择工程
MyFilter,右键->Java EE Tools->Generate Deployment Descriptor Stub
访问:localhost:8080/MyFilter/index.jsp
点击 hello.jsp,跳转到:localhost:8080/MyFilter/hello.jsp,
分别输入
李白
和 8888
登录成功,跳转回
hello.jsp 页面的内容
点击
首页,此时
index.jsp 页面的内容
【made by siwuxie095】