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>

 

posted @ 2018-05-09 22:28  marost  阅读(304)  评论(0编辑  收藏  举报