SSM登陆验证之过滤器实现

日常开发中登陆验证是必不可少的,这里介绍过滤器实现的登陆验证。

第一步:创建一个过滤器

package com.test.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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
public class LoginFilter implements Filter{
    
    private String dispatchUrl = "";
    private String excludeUrl = "";
    
    @Override
    public void destroy() {
        
    }
 
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)arg0;
        HttpServletResponse response =(HttpServletResponse)arg1;
        String servletPath = request.getServletPath();
        
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute("loginUser");
        
        /*登陆界面和登陆方法不进行过滤*/
        if(servletPath.equals(dispatchUrl) || servletPath.equals(excludeUrl)){
            arg2.doFilter(arg0, arg1);
        }else{
            if (userObj != null) {
                arg2.doFilter(arg0, arg1);
            }else{
                response.sendRedirect(request.getContextPath()+dispatchUrl);
            }
        }
    }
 
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        dispatchUrl = arg0.getInitParameter("dispatchUrl");
        excludeUrl = arg0.getInitParameter("excludeUrl");
    }
 
}
 

第二步:配置web.xml文件(),在springmvc启动配置后加入以下代码

 <!--登陆过滤器 start -->
    <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.test.filter.LoginFilter</filter-class>
        <init-param>
            <!--不进行过滤的url,因为它就是跳转到登陆界面, -->
            <param-name>excludeUrl</param-name>
            <param-value>/login</param-value>
        </init-param>
        <init-param>
            <!--未登录用户跳转的url -->
            <param-name>dispatchUrl</param-name>
        <param-value>/login.jsp</param-value>
    </init-param>
    </filter>
    <filter-mapping>
        <filter-name>loginFilter</filter-name>
    <url-pattern>*.jsp</url-pattern>
    </filter-mapping>
    <!--登陆过滤器end -->
 

第三步:创建登陆页面login.jsp,路径在WebContent目录下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"></c:set>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title></title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  <body>
      <form action="${ctx}/login.do" method="post"><br>
          用户名:<input type="text" name="username" id="username" value=""/><br><br>
          密 码:<input type="password" name="password" id="password" value=""/>
          <input type="submit" value="登录">
      </form>
  </body>
</html>

第四步:创建LoginController类

package com.test.controller;
 
 
import javax.servlet.http.HttpSession;
 
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.test.domain.User;
import com.test.service.UserService;
import com.test.vo.Result;
 
 
 
@Controller
public class LoginController {
 
    @Autowired
    private UserService userService;
    
    @ResponseBody
    @RequestMapping("login.do")
    public Result login(String userName,String password, HttpSession session) {
        User user = this.userService.findUserByUserName(userName);
        
        if (user == null) {
            return Result.fail(404, "用户不存在");
        }
        
        if (!DigestUtils.md5Hex(password).equals(user.getPassword())) {
            return Result.fail(403, "用户密码不正确");
        }
        
        session.setAttribute("loginUser", user);
 
        return Result.succeed("/jsp/main.jsp");
    }
    
    @RequestMapping("logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.html";
    }
    
}
第五步:相同路径下添加一个测试页面index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<c:set var="ctx" value="${pageContext.request.contextPath}"></c:set>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title></title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  <body>
      首页---这是测试页面!!!
  </body>
</html>

扫描二维码关注公众号,回复: 3931771 查看本文章

第六步:部署启动项目

访问 localhost:8080/ssm-login 默认进入登陆页面

访问 localhost:8080/ssm-login/index.jsp经过过滤器跳转到登陆页面

测试成功!!

转载:https://blog.csdn.net/qq_16206321/article/details/80999811

猜你喜欢

转载自blog.csdn.net/qq_28773851/article/details/81359253