SpringMvc学习7之拦截器案例(登陆)

21 篇文章 0 订阅
8 篇文章 0 订阅

第一步:在LoginController类中,先写@RequestMapping(value = “/login”, method = RequestMethod.GET)注解方法

@Controller
public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String Login() {
        return "login";
    }

上面的意思就是,挡在浏览器输入地址127.0.0.0:8080/login,然后就会进入到这个注解的方法里面,然而这个方法是用来返回login.jsp内容的。

第二步:先写login.jsp登陆页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>查询商品列表</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/login" method="post">
    <table>
        <tr>
            <td>用户名:<input name="username" type="text"/></td>
        </tr>
        <tr>
            <td>密码:<input name="pwd" type="password"/></td>
        </tr>
        <tr>
            <td><input value="登录" type="submit"/></td>
        </tr>
    </table>
</form>
</body>
</html>

如图所示,这里创建了一个表单并且嵌套了表格的使用,分别创建了一个用户名输入框、密码输入框以及登陆按钮。点击登陆后就会使用的post方法将action="${pageContext.request.contextPath }/login" method="post"将页面数据传送到后台。

第三步:在com.pp.controller中,使用注解@RequestMapping(value = “/login”, method = RequestMethod.POST)的方法。

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String Login(String username, String pwd, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if (username != null) {
            session.setAttribute("usernaem", username);
        }
        return "redirect:/items/list";
    }

这里返回的参数是string,方法里面的参数有一个String类型的username,String类型的pwd.然后还需要一个HttpServletRequest类型的request。方法内先通过request的get面的Session()方法获取前端页面的session会话。然后去判断用户名是否为空,如果不为空,就session的setAttribute()方法将username存储到session中去。最后使用return重定向到/item/list控制器中注解的路径上去,这里是ItemsController中使用注解的位置。具体位置如下:

在这里插入图片描述
上面的步骤就是通过登陆然后跳转到后面商品列表的页面,但是我们tomcat服务器关闭后在打开,应该session关闭,就不能访问登陆后面的页面,但是我们在打开服务器之家访问localhost:8080/items/list还是直接可以访问。所以我们需要一个拦截器,如果登陆就放行,如果不登陆就禁止访问后面的页面或者直接跳转到登陆页面让其登陆。

第四步:拦截器的设置

1. 在intercepter包下创建HandlerInterceptor,然后继承和实现HandlerInterceptor的类

package com.pp.intercepter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginIntercepter implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        if (!requestURI.contains("/login")){
            String  username =(String) request.getSession().getAttribute("username");
            if (username==username){
                response.sendRedirect(request.getContextPath()+"/login");
                return false;
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

上面主要的部分就是第一个方法preHandle只有返回true才能够放行,跳转到其他页面。

 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        if (!requestURI.contains("/login")){
            String  username =(String) request.getSession().getAttribute("username");
            if (username==username){
                response.sendRedirect(request.getContextPath()+"/login");
                return false;
            }
        }
        return true;
    }
  1. 我们先在这个函数中使用request.getRequestURI()获取前面页面的url并且使用requestURI 变量存起来,
  2. 在判断这个页面使用requestURI.contains("/login")方法判断是否包含/login,
  3. 如果不包含/login, 然后通过request.getSession().getAttribute(“username”)获取username的值。
  4. 如果在页面中获取的username不为空就使用response.sendRedirect(request.getContextPath()+"/login")将页面重定向到注解@RequestMapping("/login")的函数中,最终需要重新登陆。

2.在SpringMvc.xml配置文件中配置LoginIntercepter拦截器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
">
    <!--注解扫描-->
    <context:component-scan base-package="com.pp.controller"/>  <!--扫描根目录-->
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
        <property name="order" value="0"/>
    </bean>
    <!--不让springmvc拦截我们的js文件-->
    <mvc:resources mapping="/js/**" location="/js/"/>

    <!--拦截器配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!--<bean class="com.pp.intercepter.Intercepter1"/>-->
            <bean class="com.pp.intercepter.LoginIntercepter"/>
        </mvc:interceptor>
    </mvc:interceptors>
    <!--上传文件配置-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="500000"/>
    </bean>
    <!--使用了RequestMapping注解-->
    <mvc:annotation-driven conversion-service="conversionService"/>
    <!--搞定日期的转换问题-->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.pp.controller.converter.CustomGlobalStrToDateConvter"/>
            </set>
        </property>
    </bean>
</beans>

上面的代码中拦截器部分为:

 <!--拦截器配置-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!--<bean class="com.pp.intercepter.Intercepter1"/>-->
            <bean class="com.pp.intercepter.LoginIntercepter"/>
        </mvc:interceptor>
    </mvc:interceptors>

这里只需要将拦截器的class修改为我们的LoginIntercepter的路径即可。
源码地址:https://gitee.com/yangforever/project-learning/tree/master/demo/SpringMvc/springmvcday3

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值