判断用户是否登陆的过滤器要怎么写?
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录</title> <link rel="stylesheet" href="css/login.css"> <script type="text/javascript"> function changeImg(){ var codeImg=document.getElementById("codeImg"); codeImg.src="${pageContext.request.contextPath}/CheckImgServlet?time="+new Date().getTime(); } </script> </head> <body> <div class="login"> <div class="header"> <h1> <a href="/login.do">登录</a> </h1> <button></button> </div> <p style="margin-left:50px;">${requestScope.msg }</p> <form action="${pageContext.request.contextPath}/LoginServlet" method="post"> <div class="name"> <input type="text" id="name" name="username"> <p></p> </div> <div class="pwd"> <input type="password" id="pwd" name="password"> <p></p> </div> <div class="code"> <input type="text" id="code" name="verifyCode" style="width: 150px"> <img id="codeImg" onclick="changeImg()" src="${pageContext.request.contextPath}/CheckImgServlet" style="width: 150px;height: 42px;vertical-align: middle;"> <p></p> </div> <div class="btn-red"> <input type="submit" value="登录" id="login-btn"> </div> </form> </div> </body> </html>
LoginServlet.java
package com.imooc1.web.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.imooc1.domain.User; import com.imooc1.service.UserService; import com.imooc1.service.impl.UserServiceImpl; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 完成验证码的校验 // 获得session中保存的验证码信息 String code1=(String)request.getSession().getAttribute("checkCode"); // 接收前台表单提交的验证码的信息 String code2=request.getParameter("verifyCode"); if(code2==null||!code2.equalsIgnoreCase(code1)) { request.setAttribute("msg","验证码输入不正确"); request.getRequestDispatcher("/login.jsp").forward(request, response); return; } // 接收数据: String username=request.getParameter("username"); String password=request.getParameter("password"); // 封装数据: User user=new User(); user.setUsername(username); user.setPassword(password); // 处理数据:完成登录. UserService userService=new UserServiceImpl(); // 获得用户列表的集合 List<User> userList=(List<User>)getServletContext().getAttribute("userList"); User existUser=userService.login(userList,user); // 显示结果: if(existUser==null) { // 登录失败 request.setAttribute("msg", "用户名或密码错误"); request.getRequestDispatcher("/login.jsp").forward(request, response); }else{ // 登录成功 // 将用户信息保存 request.getSession().setAttribute("existUser", existUser); response.sendRedirect(request.getContextPath()+"/categoryList.html"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
AuthFilter.java
package com.imooc1.web.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; import javax.servlet.annotation.WebFilter; /** * Servlet Filter implementation class AuthFilter */ @WebFilter("/AuthFilter") public class AuthFilter implements Filter { /** * Default constructor. */ public AuthFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub String username=request.getParameter("username"); if(username==null) { // 未登录 request.setAttribute("msg", "用户未登陆"); request.getRequestDispatcher("/login.jsp").forward(request, response); }else { chain.doFilter(request, response); } } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>book_management</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> <filter> <filter-name>AuthFilter</filter-name> <filter-class>com.imooc1.web.filter.AuthFilter</filter-class> </filter> <filter-mapping> <filter-name>AuthFilter</filter-name> <url-pattern>/LoginServlet</url-pattern> </filter-mapping> </web-app>
从login.jsp页面发来的请求会先被过滤器拦截,如果然后才可能到LoginServlet,对吗?
xml中的<url-pattern>标签要怎么写?
在LoginServlet 中已经对用户登录信息进行判断了,如果登录信息为空或者不正确都不能登录。过滤器是在登录信息传到LoginServlet 之前就拦截一下,判断是否为空吗?
如果不为空就执行chain.doFilter(request, response) 这这句话吗?
执行了chain.doFilter(request, response) 这句话信息就能往后传给LoginServlet 吗?
如果为空要怎么拦截,用请求转发给login.jsp页面行吗?
正在回答 回答被采纳积分+1
package com.imooc1.web.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; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.imooc1.domain.User; @WebFilter("/AuthFilter") public class AuthFilter implements Filter { public AuthFilter() { // TODO Auto-generated constructor stub } public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println("过滤器已生效"); String str=((HttpServletRequest) request).getRequestURI().toString(); System.out.println(str+"<————————"); if(str.indexOf(".css")>0||str.indexOf(".jpg")>0||str.indexOf(".png")>0||str.indexOf("login")>0||str.indexOf("LoginServlet")>0||str.indexOf("UserService")>0||str.indexOf("CheckImgServlet")>0) { System.out.println("过滤器已生效A"); chain.doFilter(request, response); //return; }else { User user= (User) ((HttpServletRequest) request).getSession().getAttribute("existUser"); if(user==null||"".equals(user)) { System.out.println("过滤器已生效B"); // 未登录 request.setAttribute("msg1", "用户未登陆"); ((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/login.jsp"); return; }else { System.out.println("过滤器已生效C"); chain.doFilter(request, response); return; } } // if(str.indexOf(".css")>0||str.indexOf(".jpg")>0||str.indexOf(".png")>0||str.indexOf("login")>0||str.indexOf("LoginServlet")>0||str.indexOf("UserService")>0||str.indexOf("CheckImgServlet")>0) { // System.out.println("过滤器已生效A"); // chain.doFilter(request, response); // return; // } // User user= (User) ((HttpServletRequest) request).getSession().getAttribute("existUser"); // if(user==null||"".equals(user)) { // System.out.println("过滤器已生效B"); // // 未登录 // request.setAttribute("msg1", "用户未登陆"); // ((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/login.jsp"); // return; // }else { // System.out.println("过滤器已生效C"); // chain.doFilter(request, response); // return; // } } public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
之前这个过滤器有问题,我现在把其他功能都写完了,然后又来写这个过滤器。 这个过滤器这么写对不对? 这样写完之后各种效果运行正常。
是不是在if判断中还要加上 ||str.indexOf("LoginServlet")>0||str.indexOf("UserService")>0||str.indexOf("CheckImgServlet")>0 才行? 这样才能生成existUser,然后才能在过滤器里去进行后面的if判断。 还有加上这些才能在login.jsp页面生成验证码图片。
同学你好,同学可以先放行css,js,png图片以及访问login相关方法,然后进行过滤user为null的。如果为null,则直接跳转到login.jsp文件中。修改后代码如下:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println("过滤器已生效"); String str=((HttpServletRequest) request).getRequestURI().toString(); System.out.println(str+"<————————"); if(str.indexOf(".css")>0||str.indexOf(".jpg")>0||str.indexOf(".png")>0 || str.indexOf("login")>0) { System.out.println("过滤器已生效A"); chain.doFilter(request, response); return; } User user= (User) ((HttpServletRequest) request).getSession().getAttribute("existUser"); if(user==null || "".equals(user)) { System.out.println("过滤器已生效B"); // 未登录 request.setAttribute("msg", "用户未登陆"); ((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/login.jsp"); return; }else { System.out.println("过滤器已生效C"); chain.doFilter(request, response); return; } }
如果我的回答解决了你的问题,请采纳!祝学习愉快!
package com.imooc1.web.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; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.imooc1.domain.User; @WebFilter("/AuthFilter") public class AuthFilter implements Filter { public AuthFilter() { // TODO Auto-generated constructor stub } public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub System.out.println("过滤器已生效"); String str=((HttpServletRequest) request).getRequestURL().toString(); System.out.println(str+"<————————"); if(str.indexOf("css")!=-1||str.indexOf("ogin")!=-1) { System.out.println("过滤器已生效A"); chain.doFilter(request, response); } User user= (User) ((HttpServletRequest) request).getSession().getAttribute("existUser"); if(user==null) { System.out.println("过滤器已生效B"); // 未登录 request.setAttribute("msg", "用户未登陆"); ((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath()+"/login.jsp"); }else { System.out.println("过滤器已生效C"); chain.doFilter(request, response); } } public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub } }
还是没成功。
请问,哪里写错了?
同学你好,
首先,我们判断用户是否登录不应该是request域中获取,而是要在session域中获取。
所以
User user= (User) request.getSession().getAttribute("existUser");
并且,我们不应该是拦截登录的Servlet,我们应该拦截的是除了的登录的servlet以及登录的jsp和css样式。
所以我们可以配置
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.imooc1.web.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
并且在过滤器中获取一下这个url,判断一下,包含.css的放行一下,包含login的放行一下。
其他的都要判断User user= (User) request.getSession().getAttribute("existUser");中user是否为null,如果是,则重定向会登陆的页面。如果不是null,说明登录了,就可以放行了。
如果我的回答解决了你的问题,请采纳,祝学习愉快.
- 参与学习 人
- 提交作业 676 份
- 解答问题 9666 个
本阶段将从前端网页搭建入手,到Java Web基础,前后端结合助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星