• SSM(Spring,SpringMVC,MyBatis)用户登录


    参考教程:https://blog.csdn.net/u014427391/article/details/51419521

    网页访问流程:

    1、只有在用户成功登录时才能访问网站链接;

    2、否则跳转到登录页面或注册页面;

    3、登录成功跳转到成功页面

    4、登录失败继续保留在登录页面

    dispatcher-servlet.xml增加如下配置:

    <!-- 拦截器 -->  
        <mvc:interceptors>  
            <!-- 多个拦截器,顺序执行 -->  
            <mvc:interceptor>  
                <mvc:mapping path="/**"/>  
                <bean class="com.qs.interceptor.LoginInterceptor"></bean>  
            </mvc:interceptor>  
        </mvc:interceptors>
    

     java代码中创建包com.qs.interceptor并创建类LoginInterceptor

    package com.qs.interceptor;
    
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpServletResponse;  
    import javax.servlet.http.HttpSession;  
      
    import org.springframework.web.servlet.HandlerInterceptor;  
    import org.springframework.web.servlet.ModelAndView;  
    /** 
     * 登录认证的拦截器 
     */  
    public class LoginInterceptor implements HandlerInterceptor{  
      
        /** 
         * Handler执行完成之后调用这个方法 
         */  
        public void afterCompletion(HttpServletRequest request,  
                HttpServletResponse response, Object handler, Exception exc)  
                throws Exception {  
              
        }  
      
        /** 
         * Handler执行之后,ModelAndView返回之前调用这个方法 
         */  
        public void postHandle(HttpServletRequest request, HttpServletResponse response,  
                Object handler, ModelAndView modelAndView) throws Exception {  
        }  
      
        /** 
         * Handler执行之前调用这个方法 
         */  
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  
                Object handler) throws Exception {  
            //获取请求的URL  
            String url = request.getRequestURI();  
            //URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的,其它的URL都进行拦截控制  
            if(url.indexOf("login")>=0){  
                return true;  
            }  
            //获取Session  
            HttpSession session = request.getSession();  
            String username = (String)session.getAttribute("username");  
              
            if(username != null){  
                return true;  
            }  
            //不符合条件的,跳转到登录界面  
            request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);  
              
            return false;  
        }  
      
    }
    View Code

    在controller包中添加LoginControl类

    package com.qs.controller;
    
    import javax.servlet.http.HttpSession;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class LoginControl {
    	@RequestMapping(value="/login")  
        public String login(HttpSession session,String username,String password) throws Exception{        
            //在Session里保存信息  
            session.setAttribute("username", username); 
            //設置session的失效時間單位為秒
            session.setMaxInactiveInterval(30*60);//30分鐘
            //重定向  
            return "redirect:test";   
        }  
          
        @RequestMapping(value="/logout")  
        public String logout(HttpSession session) throws Exception{  
            //清除Session  
            session.invalidate();          
            return "redirect:login";  
        }
    }
    

     在controller包中创建任意类放置test成功页面的跳转【也可放在上面loginControl类中】

    @RequestMapping("/test")  
        public String test(Model model) {  
        	String message = "SpringMVC";  
            //为model添加Attribute  
            model.addAttribute("message",message);
            System.out.println("test"); 
            return "test"; 
        }
    

     在src/main/webapp/WEB-INF/views中增加login.jsp和test.jsp【test.jsp作为成功页面】

    <body>
        <form action="login" method="post">  
            用户名:<input type="text" name="username" /><br>  
            密码:<input type="text" name="password" /><br>  
            <input type="submit" value="登录" />  
          </form>
      </body>

    上面为login.jsp的主要代码

    test.jsp的代码如下:

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>  
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %> 
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%
    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>My JSP 'test.jsp' starting page</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">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
    
      </head>
      
      <body>
         当前用户:${username}
        <c:if test="${username!=null}">  
            <a href="logout">退出</a>  
        </c:if>
        ${message}
      </body>
    </html>
    
  • 相关阅读:
    CSS3 resize 属性
    FE_UPWARD (Numerics) – C 中文开发手册
    Redis Renamenx 命令
    ASP Execute 方法
    Java面试题:什么时候用断言(assert)?
    Chrome DevTools谷歌浏览器开发者工具远程调试协议
    折叠 | Collapse (Components: Collapse) – Bootstrap 4 中文开发手册
    Java 之 数学相关类 Math、BigInteger、BigDecimal
    Java 之 Arrays 类
    Java 之 Random 类
  • 原文地址:https://www.cnblogs.com/marost/p/9017068.html
Copyright © 2020-2023  润新知