ssm实现登录功能及拦截器配置
程序员文章站
2022-07-02 23:20:45
...
关于Spring SpringMVC MyBatis的一个综合案例
要用到的jar包
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<!-- 设置请求参数字符编码过滤 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>\/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
db.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
jdbc.maxActive=20
log4j.properties文件
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
# 配置日志
# 规则 log4j.logger.映射接口的包=日志级别
# 总共五个级别(error:错误,info:普通信息,debug:调试信息,warn:警告,trae/all:所有情况)
# 当前开发阶段配置debug/ (all/trace),项目上线以后配置error
log4j.logger.com.ywq.ssm.mapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
springdao.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置包扫描 -->
<context:component-scan base-package="com.ywq.ssm"/>
<!-- 读取数据库配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置连接池 -->
<!-- 配置阿里巴巴连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="${jdbc.maxActive}"/>
</bean>
<!-- MyBatis集成 -->
<!-- 1.配置MyBatis的工厂对象SqlSessionFacotry -->
<bean id="sqlSessionFacoyry" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 2.使用包扫描创建映射接口代理对象 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置映射接口的包 -->
<property name="basePackage" value="com.ywq.ssm.mapper"/>
</bean>
<!-- 事务配置 -->
<!-- 1.配置事务管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<!-- DQL 查询方法 -->
<tx:method name="select*" read-only="true"/>
<!-- DML 增删改 -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 3.使用aop将事务通知切入到Servicec层 -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ywq.ssm.service..*.*(..))"/>
</aop:config>
</beans>
springmvc.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 开启SpringMVC注解驱动 -->
<mvc:annotation-driven/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 配置具体拦截器 -->
<mvc:interceptor>
<!-- 配置要拦截的资源请求
/* :拦截一级所有请求 /isnert.do /delte.do /update.do
/** :拦截多级多请求 /user/insert.do /user/delte.do
拦截器只会拦截SpringMVC的【控制器方法】,不会拦截jsp,html等其他资源
-->
<mvc:mapping path="/**"/>
<!-- 配置需要放行的资源,多个要放行的请求资源逗号隔开
/user/login.do,/user/xxx.do,/user/abc.do
-->
<mvc:exclude-mapping path="/user/login.do"/>
<!-- 配置拦截器对象 -->
<bean class="com.ywq.ssm.interceptor.CheckLoginlnterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
登录页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h3>登录页面</h3>
<span style="color: red;" >${msg}</span>
<form action="${pageContext.request.contextPath}/user/login.do" method="post">
账号:<input type="text" name="name"><br>
密码:<input type="password" name="password"><br>
<button type="submit">登录</button>
</form>
数据列表页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 引入jstl核心标签库 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<table border="1" style="width: 500px;border-collapse: collapse;">
<tr>
<th>id</th>
<th>name</th>
<th>password</th>
<th>age</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.password}</td>
<td>${user.age}</td>
<td>
<!--
javascript:void(0); 禁用超链接的跳转
-->
<a href="javascript:void(0);" onclick="deleteUser(${user.id})">删除</a> <a href=""> 修改</a>
</td>
</tr>
</c:forEach>
</table>
<script type="text/javascript">
function deleteUser(userId){
if(confirm("您确定要删除此条数据吗?")){
location.href="${pageContext.request.contextPath}/user/delete.do?userId="+userId
}
}
</script>
pojoUser代码
package com.ywq.ssm.pojo;
public class User {
private Integer id ;
private String name;
private String password;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(Integer id, String name, String password, Integer age) {
super();
this.id = id;
this.name = name;
this.password = password;
this.age = age;
}
public User() {
super();
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + "]";
}
}
UserMapper代码
package com.ywq.ssm.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import com.ywq.ssm.pojo.User;
public interface UserMapper {
@Insert("insert into user (name,password,age) values(#{name},#{password},#{age})")
int insert(User user);
@Select("select * from user where id = #{id}")
User selectByPrimaryKey(Integer id);
@Select("select * from user")
List<User> selectList();
@Delete("delete from user where id = #{id}")
int deleteByPrimaryKey(Integer id);
@Select("select * from user where name = #{name} and password = #{password} ")
User selectNameAndPassword(@Param("name") String name, @Param("password") String password);
}
UserService接口
package com.ywq.ssm.service;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import com.ywq.ssm.pojo.User;
public interface UserService {
int insert(User user);
User selectByPrimaryKey(Integer id);
List<User> selectList();
int deleteByPrimaryKey(Integer id);
User selectNameAndPassword(String name, String password);
}
UserService实现类
package com.ywq.ssm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ywq.ssm.mapper.UserMapper;
import com.ywq.ssm.pojo.User;
import com.ywq.ssm.service.UserService;
@Service
public class UserServiceImpl implements UserService{
/*
* 问题:UserMapper映射接口的代理对象如何创建?
*
*
* 一,使用Spring之前
* 1.读取mybatis-config.mxl主配置文件,创建SqlSessionFactory工厂对象
*
* 2.使用工厂对象创建SqlSession 会话对象
*
* 3.使用SqlSession的getMapper方法创建映射接口代理对象
* UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
*
* 4.提交事务
*
* 5.关闭SqlSession
* 所有步骤全部开发者自己编写代码完成
*
* 二,和Spring集成,全部操作交给Spring管理
*
* MyBatis框架已经和Spring集成好了,在MyBatis和Spring集成的桥梁包中
* mybatis-spring-1.3.1.jar,开发者只需要将创建代码配置到Spring即可
*
*
* 1.Spring帮忙创建SqlSessionFactory对象
* MyBatis框架已经和Spring集成好了,而且编写好了创建SqlSessionFacoty对象的代码
* 桥梁包:org.mybatis.spring.SqlSessionFactoryBean
*
*
* 2.和Spring集成不用创建SqlSession对象,每次创建映射接口代理对象会自动底层先创建
* SqlSession,再创建映射接口的代理对象
*
* 3,创建映射接口的代理对象
* 3.1创建单个映射接口代理对象
* 桥梁包:org.mybatis.spring.mapper.MapperFactoryBean<T>
*
* 3.2使用包扫面创建包下面所有的映射接口代理对象(推荐)
* 桥梁包:org.mybatis.spring.mapper.MapperScannerConfigurer
* */
@Autowired
private UserMapper UserMapper;
@Override
public int insert(User user) {
return UserMapper.insert(user);
}
@Override
public User selectByPrimaryKey(Integer id) {
return UserMapper.selectByPrimaryKey(id);
}
public List<User> selectList() {
// TODO Auto-generated method stub
return UserMapper.selectList();
}
public int deleteByPrimaryKey(Integer id) {
// TODO Auto-generated method stub
return UserMapper.deleteByPrimaryKey(id);
}
@Override
public User selectNameAndPassword(String name, String password) {
return UserMapper.selectNameAndPassword( name, password);
}
}
UserController代码
package com.ywq.ssm.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ywq.ssm.pojo.User;
import com.ywq.ssm.service.UserService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list")
public String list(Model m) {
List<User> users = userService.selectList();
m.addAttribute("users", users);
return "userList";
}
@RequestMapping("/delete")
public String delet(Integer userId) {
userService.deleteByPrimaryKey(userId);
//重定向跳转到列表页面
return "redirect:/user/list.do";
}
@RequestMapping("/login")
public String login(String name,String password,Model m,HttpSession session) {
User user = userService.selectNameAndPassword(name,password);
if (user ==null) {
m.addAttribute("msg", "亲,账号或密码错误! 请重新登录!");
// 返回登录页
return "forward:/login.jsp";
}else {
session.setAttribute("USER_IN_SESSION", user);
}
//重定向到用户列表
return "redirect:/user/list.do";
}
}
CheckLoginlnterceptor代码
package com.ywq.ssm.interceptor;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.ywq.ssm.pojo.User;
public class CheckLoginlnterceptor implements HandlerInterceptor {
/*
* 此方法再控制器的方法执行之前进行拦截,可以做登录检查,权限判断等
*
* return boolean 返回boolean类型
* 1. true 说明满足条件,放行
* 2.false 说明不满足条件,不放行。同时开始自己编写调转到登录页面,没有权限访问提示页面等
*
* */
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//从session获取登录储存User对象
User user = (User) request.getSession().getAttribute("USER_IN_SESSION");
System.out.println("user:"+user);
if (user == null) {
//跳转页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}
return true;
}
/*
* 此方法是后续处理方法,再控制器方法执行完毕以后执行,可以记录操作日志等
* */
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
User user = (User) request.getSession().getAttribute("USER_IN_SESSION");
Date date = new Date();
String currentTime = date.toLocaleString();
System.out.println(user.getName()+"在"+currentTime+",做了"+handler+"操作");
}
/*
*此方法再视图渲染完毕以后执行,可以释放资源等操作
* */
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
上一篇: 使用react 脚手架创建项目