35.7、SSM框架整合及实现登陆的小“呆萌”

这篇博客介绍了如何在Spring MVC中整合MyBatis,配置数据源、SqlSessionFactory和MapperScannerConfigurer。接着,展示了如何使用AOP进行事务管理,并配置了切点和事务属性。此外,还讲解了全局异常处理和控制器的实现。最后,通过创建日志记录切面,展示了如何在用户登录后记录日志。整个过程涉及到了Spring的IoC、AOP和事务管理等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

 

 

CREATE TABLE `users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `userpwd` varchar(30) NOT NULL,
  PRIMARY KEY (`userid`),
  UNIQUE KEY `username_uk` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

<?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"
       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">

<!--    配置解析Properties文件的工具类-->
    <context:property-placeholder location="classpath:db.properties"/>

<!--    配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

<!--    配置SqlSessionFactory-->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.bjsxt.pojo"/>
    </bean>

<!--    配置MapperScannerConfigurer-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjsxt.mapper"/>
    </bean>
</beans>

 

 spring的事务管理就是由aop技术实现的它通过一个能做事务管理的切面,然后通过这个切面的配置来实现事务管理

 

<?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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--    配置事务管理切面-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    配置事务属性-->
    <tx:advice id="myAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="modify*" propagation="REQUIRED"/>
            <tx:method name="drop*" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true"/>
        </tx:attributes>
    </tx:advice>

<!--    配置切点-->
    <aop:config>
        <aop:pointcut id="myPointcut" expression="execution(* com.bjsxt.service.*.*(..))"/>
        <aop:advisor advice-ref="myAdvice" pointcut-ref="myPointcut"/>
    </aop:config>
</beans>

 

 

 

<?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"
       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">

<!--    配置注解扫描-->
    <context:component-scan base-package="com.bjsxt.service"/>
</beans>

<?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">

<!--    配置注解扫描-->
    <context:component-scan base-package="com.bjsxt.web.controller"/>

<!--    配置注解驱动-->
    <mvc:annotation-driven/>

<!--    配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

<!--    配置静态资源映射器-->
    <mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
    <mvc:resources mapping="/img/**" location="/WEB-INF/img/"/>
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
</beans>

 

 

 

<?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">

<!--    指定Spring配置文件的位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    
<!--    配置启动Spring框架的监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

<!--    配置SpringMVC的前端控制器-->
    <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:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

<!--    配置字符编码过滤器-->
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

 创建业务层:

 创建自定义异常:

 

 用户登录处理器:

package com.bjsxt.web.controller;

import com.bjsxt.pojo.Users;
import com.bjsxt.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 用户管理控制器
 */
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UsersController  {
    @Autowired
    private UsersService usersService;
    /**
     * 处理用户登录请求
     */
    @RequestMapping("/userLogin")
    public String userLogin(Users users, HttpSession session){
        Users user = this.usersService.userLogin(users);
        session.setAttribute("user",user);
        return "redirect:/page/index";
    }
}

 全局异常处理器:

 

package com.bjsxt.web.controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * 全局异常处理器
 */
@ControllerAdvice
public class GlobalExceptionController {

    @ExceptionHandler({com.bjsxt.exception.UserNotFoundException.class})
    public String userNotFoundExceptionHandler(Exception e, Model model){
        model.addAttribute("msg",e.getMessage());
        return "login";
    }

    @ExceptionHandler({java.lang.Exception.class})
    public String exceptionHandler(Exception e){
        return "redirect:/page/error";
    }
}

 

 

 

 

 

 修改springmvc.xml文件配置拦截器:

创建一个logs表格:

 创建logs表格的pojo与mapper:  这里用到的是逆向工程就是那个mybatisgenerator

 创建日志记录切面:

package com.bjsxt.aop;

import com.bjsxt.mapper.LogsMapper;
import com.bjsxt.pojo.Logs;
import com.bjsxt.pojo.Users;
import com.bjsxt.pojo.UsersExt;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class UsersLoginLogAOP {
    @Autowired
    private LogsMapper logsMapper;
    /**
     * 配置切点
     */
    @Pointcut("execution(* com.bjsxt.service.UsersService.userLogin(..))")
    public void myPointcut(){
    }

    /**
     * 在后置通知中记录登录日志
     */
    @AfterReturning("myPointcut()")
    public void userLoginLog(JoinPoint joinPoint){
        Object[] objects = joinPoint.getArgs();
        UsersExt users = (UsersExt) objects[0];
        Logs logs = new Logs();
        logs.setLogtime(new Date());
        logs.setUsername(users.getUsername());
        logs.setIp(users.getIp());
         this.logsMapper.insertSelective(logs);
    }
}

 创建一个新的Users扩展实体类,UsersExt继承Users:

 修改控制器:

package com.bjsxt.web.controller;

import com.bjsxt.pojo.Users;
import com.bjsxt.pojo.UsersExt;
import com.bjsxt.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 用户管理控制器
 */
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UsersController  {
    @Autowired
    private UsersService usersService;
    /**
     * 处理用户登录请求
     */
    @RequestMapping("/userLogin")
    public String userLogin(UsersExt users, HttpSession session, HttpServletRequest request){
        String ip = request.getRemoteAddr();
        users.setIp(ip);
        Users user = this.usersService.userLogin(users);
        session.setAttribute("user",user);
        return "redirect:/page/index";
    }
}

 配置切面:

 修改springmvc.xml配置文件:

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值