实现用户登录案例,并进行非法拦截
实现当用户未登录时,无法跳转到出登录页面以外的任何页面,拦截用户仍在登陆页面;当用户登录成功即可跳转到其他页面
(1)导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.32</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.5.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> <!-- https://mvnrepository.com/artifact/javax/javaee-api --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.0</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.22</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
(2)jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/invoicingsystem?useUniCode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=123
(3)mybatis-config.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <!--配置别名--> <typeAliases> <package name="com.invoicingsystem.entity"/> </typeAliases> <!-- 引入 pageHelper插件 --> <!--注意这里要写成PageInterceptor, 5.0之前的版本都是写PageHelper, 5.0之后要换成PageInterceptor--> <plugins> <plugin interceptor="com.github.pagehelper.PageHelper"></plugin> </plugins> <!--加载小配置文件--> <mappers> <package name="com.invoicingsystem.dao"/> </mappers> </configuration>
(4)applicationContext.xml配置文件
<?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: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.xsd"> <!--1.导入jdbc.properties文件--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations" > <array> <value>classpath*:*.properties</value> </array> </property> </bean> <!--2.配置数据源 spring内置的数据源--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--3.配置mybatis的核心对象SqlSessionFatcoryBean--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="typeAliasesPackage" value="com.invoicingsystem.entity"></property> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <!--4.Mybatis的Dao接口的包扫描器(借助Dao接口生成动态代理)--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.invoicingsystem.dao"></property> </bean> <!--开启各种注解配置--> <mvc:annotation-driven/> <context:component-scan base-package="com.invoicingsystem"></context:component-scan> <!--配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/jsp/"></property> <!--return "index" /jsp/.jsp--> <property name="suffix" value=".jsp"></property> </bean> <!--释放静态资源--> <mvc:default-servlet-handler/> </beans>
(5)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--spring和mytatis整合的核心配置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
(6)User实体类
package com.invoicingsystem.entity; import org.springframework.stereotype.Repository; @Repository public class User { private Integer uid; private String userName; private String password; private String realName; public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } }
(7)UserDao层
package com.invoicingsystem.dao; import com.invoicingsystem.entity.User; import org.springframework.stereotype.Repository; @Repository public interface UserDao { //登录的方法 public User login(User user); }
(8)UserDao.xml小配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--namespace需要指向接口全路径--> <mapper namespace="com.invoicingsystem.dao.UserDao"> <select id="login" resultType="com.invoicingsystem.entity.User"> select * from users where userName=#{userName} and password=#{password} </select> </mapper>
(9)UserService层
package com.invoicingsystem.service; import com.invoicingsystem.entity.User; public interface UserService { //登录的方法 public User login(User user); }
(10)UserServiceImpl
package com.invoicingsystem.service.impl; import com.invoicingsystem.dao.UserDao; import com.invoicingsystem.entity.User; import com.invoicingsystem.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Override public User login(User user) { return userDao.login(user); } }
(11)UserController
package com.invoicingsystem.controller; import com.invoicingsystem.entity.User; import com.invoicingsystem.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping(value = "/user") public class UserController { @Resource UserService userService; @RequestMapping("/login") @ResponseBody public ModelAndView login(User user,HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView){ User login = userService.login(user); if (login!=null){ System.out.println("登陆成功!"); request.getSession().setAttribute("login",login); modelAndView.setViewName("index"); }else { modelAndView.setViewName("login"); } return modelAndView; } }
(12)LoginFilter拦截
package com.invoicingsystem.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; @WebFilter(urlPatterns = {"/*"}) public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest servletRequest=(HttpServletRequest) request; //放行URL if(servletRequest.getRequestURI().equals("/user/login")){ filterChain.doFilter(request,response); } Object user = servletRequest.getSession().getAttribute("user"); if (user==null){ servletRequest.getRequestDispatcher("login.jsp").forward(request,response); }else { //放行请求 filterChain.doFilter(request,response); } } @Override public void destroy() { } }
(13)login.jsp页面
<!DOCTYPE html> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head lang="en"> <meta charset="UTF-8"> <title>系统登录 - 小型进销存系统</title> <link rel="stylesheet" href="css/style.css"/> <style> #parent{ width:500px; height:200px; margin-top:20%; margin-left:50%; transform:translate(-50%,-50%) ; background:#009688; } .password,.subBtn{ margin-top: 2%; margin-left: 3%; } .loginHeader{ padding-top: 1%; } </style> </head> <body class="login_bg"> <div id="parent"> <section class="loginBox"> <header class="loginHeader" style="text-align:center; "> <h1>小型进销存系统</h1> </header> <section class="loginCont"> <form class="loginForm" action="/user/login" method="post" onsubmit="return check()" > <div class="inputbox" style="text-align:center; "> <label for="user">用户名:</label> <input id="user" type="text" name="userName" placeholder="请输入用户名" /> </div> <div class="password" style="text-align:center; " > <label for="mima">密码:</label> <input id="mima" type="password" name="password" placeholder="请输入密码" /> </div> <div class="subBtn" style="text-align:center; "> <input type="submit" value="登录" /> <input type="reset" value="重置"/> </div> </form> </section> </section> </div> <script src="/js/jquery.js"></script> <script> function check(){ var user=$("#user").val(); var mima=$("#mima").val(); if (user==""){ alert("请输入用户名!"); return false; } else if (mima==""){ alert("请输入密码"); return false; } } </script> </body> </html>