springMVC的学习拦截器之验证用户登录案例

文章目录

  • 实现思路
  • 关于环境和配置文件
    • pom
    • spring的配置文件
    • 关于idea的通病/常见500错误的避坑
  • 实现步骤
    • 编写登陆页面
    • 编写Controller处理请求
    • 编写登录成功的页面
    • 编写登录拦截器

实现思路

  1. 有一个登录页面,需要写一个controller访问页面
  2. 登陆页面提供填写用户名和密码的表单。需要在controller中进行判断处理,如果正确,向session中写入用户信息,返回登录成功
  3. 拦截用户请求,判断用户是否登录。如果用户已经登录,就放行;否则,跳转到登录页面

关于环境和配置文件

pom


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.yanggroupId>
    <artifactId>springmvc-07-InterceptorartifactId>
    <packaging>pompackaging>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.18version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.2version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

    dependencies>


    
    <build>
        <resources>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
        resources>
    build>

project>

spring的配置文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:mv="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd">
    
    <context:component-scan base-package="com.yang.controller"/>

    
    <mvc:default-servlet-handler />
    <mvc:annotation-driven />
    


    
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    bean>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/" />
        
        <property name="suffix" value=".jsp" />
    bean>

    
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean id="loginInterceptor" class="com.yang.config.LoginInterceptor"/>
        mvc:interceptor>
    mvc:interceptors>

beans>

关于idea的通病/常见500错误的避坑

  • 就是要在项目结构–>工件中,手动配置lib目录导入所有的依赖
    springMVC的学习拦截器之验证用户登录案例_第1张图片

实现步骤

编写登陆页面

<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2022/8/1
  Time: 19:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>login</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login">
    用户名:<input type="text" name="username" required> <br>
    密码: <input type="password" name="pwd" required> <br>
    <input type="submit" value="提交">
</form>

</body>
</html>

编写Controller处理请求

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author 缘友一世
 * @date 2022/8/1-20:05
 */
@Controller
@RequestMapping("/user")
public class LoginController {
    //跳转到登陆页面
    @RequestMapping("/jumpLogin")
    public String jumpLogin() throws Exception {
        return "login";
    }
    //跳转到成功页面
    @RequestMapping("/jumpSuccess")
    public String jumpSuccess() throws Exception {
        return "success";
    }
    //登陆提交
    @RequestMapping("/login")
    public String login(HttpSession session, String username, String pwd) throws Exception {
        // 向session记录用户身份信息
        //System.out.println("接收前端==="+username);
        session.setAttribute("user", username);
        session.setAttribute("password", pwd);
        return "success";
    }
    //退出登陆
    @RequestMapping("logout")
    public String logout(HttpSession session) throws Exception {
        // session 过期
        session.invalidate();
        return "login";
    }

}

编写登录成功的页面

<%--
  Created by IntelliJ IDEA.
  User: HP
  Date: 2022/8/1
  Time: 20:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>successtitle>
head>
<body>
    <h1>登录成功页面h1>
    <hr>
    恭喜,${user},登陆成功
    <a href="${pageContext.request.contextPath}/user/logout">注销a>
body>
html>

编写登录拦截器

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

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

/**
 * @author 缘友一世
 * @date 2022/8/1-20:30
 */
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是登陆页面则放行
        //System.out.println("uri: " + request.getRequestURI());
        //request.getRequestURI() 返回除去host(域名或者ip)部分的路径
        //逻辑判断 路径中是否包含login,确定是否在登陆页面 如果是,就通行
        if (request.getRequestURI().contains("login")) {
            return true;
        }
        HttpSession session = request.getSession();
        // 如果用户已登陆也放行
        if(session.getAttribute("user") != null) {
            return true;
        }
        // 用户没有登陆跳转到登陆页面
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
  • 最后启动tomcat进行测试

你可能感兴趣的:(#,SpringMVC,学习,servlet,java)