SSM框架整合-搭建简单账号登录系统

项目介绍

这就是一个简单的SSM项目, 输入正确的账号密码, 才能登录成功. 用来练手学习SSM项目的搭建

账号密码
SSM框架整合-搭建简单账号登录系统_第1张图片
登录页面

登录成功
SSM框架整合-搭建简单账号登录系统_第2张图片
下面开始手把手教你搭建这个项目

1.创建数据库

1.创建数据库db_springtest

步骤大同小异, 看你用的是什么可视化数据库管理软件, 动动鼠标的事, 我用的是软件SQLyog
SSM框架整合-搭建简单账号登录系统_第3张图片
SSM框架整合-搭建简单账号登录系统_第4张图片
SSM框架整合-搭建简单账号登录系统_第5张图片

2.创建表t_user

CREATE TABLE `t_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(50) DEFAULT NULL,
  `pass_word` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4

SSM框架整合-搭建简单账号登录系统_第6张图片

SSM框架整合-搭建简单账号登录系统_第7张图片

新增数据

insert  into `t_user`(`id`,`user_name`,`pass_word`) values (1,'up123','2222'),(2,'bob','666666'),(3,'cindy','123456'),(4,'eason_update','update'),(5,'newUser1','123456'),(6,'lisi','lisi'),(7,'aaa','123456'),(8,'bbba','1111'),(9,'gg','121212'),(10,'ff11','11111');

SSM框架整合-搭建简单账号登录系统_第8张图片

2.创建工程

1.开发环境

IDE:idea 2019.1.3
构建工具:maven3.6.1
服务器:tomcat8.0.2
java版本: 1.8.0_45

2.新建项目

1.使用idea新建maven工程, 选择maven-archetype-webapp
SSM框架整合-搭建简单账号登录系统_第9张图片
SSM框架整合-搭建简单账号登录系统_第10张图片
2.给项目取个名字
SSM框架整合-搭建简单账号登录系统_第11张图片

3.next
SSM框架整合-搭建简单账号登录系统_第12张图片
4.Finish
SSM框架整合-搭建简单账号登录系统_第13张图片
5.创建成功
SSM框架整合-搭建简单账号登录系统_第14张图片

3.修改项目结构

我们对项目的目录、文件进行修改、添加或删除

1.新增目录

SSM框架整合-搭建简单账号登录系统_第15张图片

2.标记目录

1.标记main下的java目录为Sources Root
SSM框架整合-搭建简单账号登录系统_第16张图片
SSM框架整合-搭建简单账号登录系统_第17张图片
2.标记resources目录为Resources Root
SSM框架整合-搭建简单账号登录系统_第18张图片
SSM框架整合-搭建简单账号登录系统_第19张图片
3.标记test下的java目录为Test Sources Root
SSM框架整合-搭建简单账号登录系统_第20张图片
SSM框架整合-搭建简单账号登录系统_第21张图片

3.删除jsp文件

jsp太古老了, 我们使用HTML5+Thymeleaf, 所以把它删了
SSM框架整合-搭建简单账号登录系统_第22张图片
在这里插入图片描述
SSM框架整合-搭建简单账号登录系统_第23张图片

4.使用pom导入依赖

SSM框架整合-搭建简单账号登录系统_第24张图片

pom.xml文件内容修改如下



<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.limigroupId>
  <artifactId>ssm-test2artifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <name>ssm-test2 Maven Webappname>
  
  <url>http://www.example.comurl>

  
  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <spring.version>5.0.2.RELEASEspring.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>2.11.1log4j.version>
    <mysql.version>5.1.6mysql.version>
    <mybatis.version>3.4.5mybatis.version>
  properties>


  <dependencies>
    
    <dependency>
      <groupId>org.aspectjgroupId>
      <artifactId>aspectjweaverartifactId>
      <version>1.6.8version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>compilescope>
    dependency>
    <dependency>
      <groupId>org.junit.jupitergroupId>
      <artifactId>junit-jupiter-apiartifactId>
      <version>5.9.0-M1version>
      <scope>compilescope>
    dependency>

    
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>4.0.1version>
      <scope>providedscope>
    dependency>

    
    <dependency>
      <groupId>org.thymeleafgroupId>
      <artifactId>thymeleaf-spring5artifactId>
      <version>3.0.12.RELEASEversion>
    dependency>

    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-slf4j-implartifactId>
      <version>${log4j.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-webartifactId>
      <version>${log4j.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-jclartifactId>
      <version>${log4j.version}version>
    dependency>
    
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.0version>
    dependency>
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.2.6version>
    dependency>
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>5.1.10version>
    dependency>
  dependencies>

  
  <build>
    <resources>
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
    resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-pluginartifactId>
        <version>3.1version>
        <configuration>
          <source>1.8source>
          <target>1.8target>
        configuration>
      plugin>
    plugins>
  build>
project>

5.编辑配置文件

我们新增或修改所需的配置文件
在resources目录下新增图中5个配置文件, 修改WEB-INF目录下的web.xml配置文件
SSM框架整合-搭建简单账号登录系统_第25张图片

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_springtest?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456

log4j2.xml




<configuration status="DEBUG">
    
    <appenders>
        
        <console name="Console" target="SYSTEM_OUT">
            
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        console>
    appenders>
    
    
    <loggers>
        
        <root level="DEBUG">
            <appender-ref ref="Console"/>
        root>
    loggers>
configuration>

mybatis-config.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>



    
    <settings>
        
        <setting name="logImpl" value="LOG4J2"/>


        
        <setting name="useGeneratedKeys" value="true" />

        
        <setting name="useColumnLabel" value="true" />

        
        <setting name="mapUnderscoreToCamelCase" value="true" />

    settings>

    
    <plugins>
        <plugin interceptor ="com.github.pagehelper.PageInterceptor" />
    plugins>

    
    

configuration>

spring.xml


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

    
    <context:component-scan base-package="com.limi" >
        
        
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>

    
    
    <context:property-placeholder location="classpath:jdbc.properties"/>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
    bean>

    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
        
        <property name="mapperLocations" value="classpath:com/limi/dao/xml/*.xml"/>
        
        <property name="dataSource" ref="dataSource" />
    bean>

    
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="com.limi.dao"/>
    bean>

    
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource">property>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />

beans>

spring-mvc.xml


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

    
    <context:component-scan base-package="com.limi.controller"/>

    
    <mvc:annotation-driven>
        <mvc:message-converters>
            
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8" />
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/htmlvalue>
                        <value>application/jsonvalue>
                    list>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>


    
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />

                        
                        <property name="cacheable" value="false"/>
                    bean>
                property>
            bean>
        property>
    bean>

    
    
    <mvc:default-servlet-handler/>

    
    


    
    <mvc:interceptors>
        <mvc:interceptor>
            
            <mvc:mapping path="/**"/>
            <mvc:exclude-mapping path="/index"/>
            <mvc:exclude-mapping path="/login"/>

            
            <mvc:exclude-mapping path="/static/**"/>
            
            <ref bean="firstInterceptor">ref>
            
        mvc:interceptor>
    mvc:interceptors>

    
    <aop:aspectj-autoproxy proxy-target-class="true">aop:aspectj-autoproxy>
beans>

web.xml


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



  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
  listener>

  
  <listener>
    <listener-class>org.apache.logging.log4j.web.Log4jServletContextListenerlistener-class>
  listener>

  
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring.xmlparam-value>
  context-param>
  





  
  <filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    <init-param>
      
      <param-name>forceResponseEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  
  <filter>
    <filter-name>HiddenHttpMethodFilterfilter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>



  
  <servlet>
    <servlet-name>springMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      
      <param-name>contextConfigLocationparam-name>
      
      <param-value>classpath:spring-mvc.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>springMVCservlet-name>
    
    <url-pattern>/url-pattern>
  servlet-mapping>

web-app>

6.编写后端代码

一共有10个代码文件
SSM框架整合-搭建简单账号登录系统_第26张图片

1.实体entity

这个包里的类一般对应数据库中的表
User

package com.limi.entity;


public class User {

    private Integer id;

    private String userName;

    private String passWord;

    public User(){}

    public User(Integer id, String userName, String passWord) {
        this.id = id;
        this.userName = userName;
        this.passWord = passWord;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", passWord='" + passWord + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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;
    }
}

2.数据库操作dao

这个包里的类是执行数据库操作的代码
UserDao

package com.limi.dao;

import com.limi.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public interface UserDao {

    User getUserById(Integer id);

    boolean updateUserById(User user);

    boolean insertUser(User user);

    List<User> getAllUser();

    boolean deleteUserById(Integer id);
}

UserDao.xml


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.limi.dao.UserDao">

    <select id="getUserById" resultType="com.limi.entity.User">
        select * from t_user where id = #{id}
    select>

    <select id="getAllUser" resultType="com.limi.entity.User">
        
        select * from t_user
    select>

    
    <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
        insert into t_user(user_name, pass_word)
        values(#{userName},#{passWord})
    insert>

    <update id="updateUserById">
        update t_user
        set user_name = #{userName}, pass_word = #{passWord}
        where id = #{id}
    update>

    <delete id="deleteUserById">
        delete from t_user
        where id = #{id}
    delete>
mapper>

3.服务service

UserService

package com.limi.service;

import com.limi.entity.User;

import java.util.List;

public interface UserService {

    User getUserById(Integer id);

    boolean updateUserById(User user);

    boolean insertUser(User user);

    List<User> getAllUser();

    boolean deleteUserById(Integer id);
}

UserServiceImpl

package com.limi.service.impl;

import com.limi.dao.UserDao;
import com.limi.entity.User;
import com.limi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Transactional
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User getUserById(Integer id) {
        if (id!=null)
            return userDao.getUserById(id);
        return null;
    }

    @Override
    public boolean updateUserById(User user) {
        if(user!=null&&user.getId()!=null){
            boolean res = userDao.updateUserById(user);
            return res;
        }

        return false;
    }

    @Override
    public boolean insertUser(User user) {
        return userDao.insertUser(user);
    }

    @Override
    public List<User> getAllUser() {
        return userDao.getAllUser();
    }

    @Override
    public boolean deleteUserById(Integer id) {
        return userDao.deleteUserById(id);
    }


}

4.控制器controller

LoginController

package com.limi.controller;

import com.limi.entity.User;
import com.limi.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @GetMapping("/index")
    public String index(){
        logger.info("--------info>>>>>>>>>index---------");
        logger.warn("-------warn>>>>>>>>>index---------");
        return "index";
    }


    @PostMapping("/login")
    public String login(HttpSession session, Integer id, String password){
        System.out.println("id:"+id+"   password:"+password);
        User user = userService.getUserById(id);
        if(user!=null)
            System.out.println(user);
            if(user.getId()==id&&user.getPassWord().equals(password)) { //账号密码匹配成功
                System.out.println("匹配成功...");
                session.setAttribute("username", user.getUserName());
                return "redirect:/success";
            }
        return "redirect:/index";
    }

    @GetMapping("/success")
    public ModelAndView test1(HttpSession session){
        System.out.println("======执行控制器中方法success======");
        String name = (String)session.getAttribute("username");
        ModelAndView mv = new ModelAndView();
        mv.addObject("name", name);
        mv.setViewName("success");
        return mv;
    }

    //测试异常处理页面的跳转
    @GetMapping("/test")
    public void test(){
        int i = 10/0;
    }
}

ExceptionController

package com.limi.controller;

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

//@ControllerAdvice将当前类标识为异常处理的组件
@ControllerAdvice
public class ExceptionController {

    //@ExceptionHandler用于设置所标识方法处理的异常
    @ExceptionHandler(ArithmeticException.class)
    //ex表示当前请求处理中出现的异常对象
    public String handleArithmeticException(Exception ex, Model model){
        model.addAttribute("ex", ex);
        return "error";
    }
}

5.拦截器interceptor

FirstInterceptor

package com.limi.interceptor;

import org.springframework.stereotype.Component;
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;


@Component
public class FirstInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("==========FirstInterceptor preHandle==========");
        HttpSession session = request.getSession();
        if(session.getAttribute("username")!=null) //已登录
            return true;//放行
        else{
            //未登录, 重定向到登录页
            response.sendRedirect(request.getContextPath()+"/index");
        }
        return false;//拦截
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==========FirstInterceptor postHandle==========");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("==========FirstInterceptor afterCompletion==========");
    }
}

6.切面aspect

LogAspect

package com.limi.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class LogAspect {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //所有controller包下的方法都要经过切面
    @Pointcut("execution(* com.limi.controller..*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        logger.info("------------doBefore-------------");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        Map requestLog = new HashMap();
        requestLog.put("url",url);
        requestLog.put("ip", ip);
        requestLog.put("classMethod", classMethod);
        requestLog.put("args", args);
        logger.info("Request:{}",requestLog);
        System.out.println("aop...");
    }

    @After("log()")
    public void doAfter(JoinPoint joinPoint){
        logger.info("-------------doAfter-------------");
        System.out.println("aop...");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterReturn(Object result){
        logger.info("--------doAfterReturning---------");
        logger.info("Result:{}",result);
        System.out.println("aop...");
    }


}

7.测试test

Jtest5

package com.limi;

import com.github.pagehelper.PageHelper;
import com.limi.entity.User;
import com.limi.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;

import java.util.List;


@ExtendWith(SpringExtension.class) //选择单元测试框架
//1.加载xml配置文件,classpath就是src目录
@ContextConfiguration(locations = {"classpath:spring.xml", "classpath:spring-mvc.xml"})
@WebAppConfiguration
//给测试类添加注解 @WebAppConfiguration 或 @WebAppConfiguration("src/main/resources") ,此注解在类上,
//用来声明加载的ApplicationContex 是一个WebApplicationContext ,它的属性指定的是Web资源的位置,默认为 src/main/webapp,
public class Jtest5 {

    @Autowired
    private UserService userService;

    //测试根据id查询user
    @Test
    public void test1(){
        System.out.println(userService.getUserById(1).toString());
    }

    @Test
    public void test2(){
        System.out.println("123456789");
    }

    //测试更新数据库
    @Test
    public void test3(){
        User user = new User(1,"up123","2222");
        userService.updateUserById(user);
    }

    //测试新增user
    @Test
    public void test4(){
        User user = new User(null,"ins111","2222");
        userService.insertUser(user);
    }

    //测试删除user
    @Test
    public void test5(){
        userService.deleteUserById(11);
    }

    //测试mybatis分页
    @Test
    public void test6(){
        PageHelper.startPage(1, 3);
        List<User> userList = userService.getAllUser();
        userList.forEach(user -> System.out.println(user));
        //会执行
        //SELECT count(0) FROM t_user
        //select * from t_user LIMIT 3

    }

}

7.编写前端代码

我们需编写2个css, 1个js, 3个html页面, 以及添加2张图片
SSM框架整合-搭建简单账号登录系统_第27张图片

1.images

bg.jpg
SSM框架整合-搭建简单账号登录系统_第28张图片

spring.jpg
SSM框架整合-搭建简单账号登录系统_第29张图片

2.css

index.css



body{
    margin:0;
    padding: 0;
    font-family: sans-serif;
    background: url("../images/bg.jpg");
    background-size: cover;
}
.box
{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    width:400px;
    padding: 40px;
    background:rgba(0,0,0,.8);
    box-sizing:border-box;
    box-shadow:0 15px 25px rgba(0,0,0,.5);
    border-radius: 10px;/*登录窗口边角圆滑*/
}
.box h2
{
    margin:0 0 30px;
    padding:0;
    color:#fff;
    text-align:center;
}
.box .inputBox
{
    position:relative;
}
.box .inputBox input
{
    width: 100%;
    padding: 10px 0;
    font-side:16px;
    color: #fff;
    letter-spacing: 1px;
    margin-bottom:30px;/*输入框设置*/
    border:none;
    border-bottom:1px solid #fff;
    outline:none;
    background:transparent;
}
.box .inputBox label
{
    position: absolute;
    top: 0;
    left: 0;
    padding: 10px 0;
    font-size: 16px;
    color: #fff;
    pointer-events: none;
    transition: .5s;
}
.box .inputBox input:focus ~ label,
.box .inputBox input:valid ~ label
{
    top: -18px;
    left: 0;
    color: #03a9f4;
    font-size: 12px;
}
.box  input[type="submit"]
{
    background: transparent;
    border: none;
    outline: none;
    color: #fff;
    background: #03a9f4;
    padding: 10px 20px;
    cursor: pointer;
    border-radius: 5px;
}

success.css


#area{
    width: 500px;
    height: 400px;
    background-color: blueviolet;
}
#show{
    width: 200px;
    height: 50px;
    background-color: yellowgreen;
}

3.js

move.js

window.onload = function(){

    var area = document.getElementById("area");
    var show = document.getElementById("show");


    area.onmousemove = function(event){
        var x = event.clientX;
        var y = event.clientY;

        console.log("x="+x+" y="+y);
        show.textContent = "x="+x+" y="+y;
    }
}

4.templates

index.html


DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <title>login UItitle>
    <link rel="stylesheet" th:href="@{/static/css/index.css}">
head>
<body>
<div class="box">
    <h2>系统登录h2>
    <form th:action="@{/login}" method="post">
        <div class="inputBox">
            <input type="number" name="id" required="">
            <label>账号label>
        div>
        <div class="inputBox">
            <input type="password" name="password" required="">
            <label>密码label>
        div>
        <input type="submit" name="" value="登录">
    form>
div>
body>
html>

success.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <link rel="stylesheet" th:href="@{/static/css/success.css}">
    <script th:src="@{/static/js/move.js}">script>
head>
<body>
<img th:src="@{/static/images/spring.jpg}"/>
<h1>login success!h1>
<p>欢迎<span th:text="${name}">的来临!span>p>
<a th:href="@{/test}">测试异常跳转a>
<p>下面是测试js的区域,请将鼠标光标放置在色块内移动进行测试!p>
    <div id="area">div>
    <div id="show">div>
body>
html>

error.html

DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<h1 class="tips">抱歉, 服务器出错了呀!h1>
<p th:text="${ex}">p>
body>
html>

8.测试类运行

我们来运行一下测试类, 看看测试类Jtest5能否正常运行

1.测试根据id查询

在这里插入图片描述

执行结果, 可以看到执行成功
SSM框架整合-搭建简单账号登录系统_第30张图片

2.测试分页功能

SSM框架整合-搭建简单账号登录系统_第31张图片

执行结果, 可以看到执行成功
SSM框架整合-搭建简单账号登录系统_第32张图片
因此可知测试类功能正常

9.项目运行

最后我们就来运行一下这个登录系统,看看最终的效果

1.配置Tomcat

1.创建Tomcat
SSM框架整合-搭建简单账号登录系统_第33张图片

SSM框架整合-搭建简单账号登录系统_第34张图片
SSM框架整合-搭建简单账号登录系统_第35张图片
SSM框架整合-搭建简单账号登录系统_第36张图片
2.配置服务器名称
随意,我写成Tomcat8
SSM框架整合-搭建简单账号登录系统_第37张图片
3.配置部署
SSM框架整合-搭建简单账号登录系统_第38张图片
SSM框架整合-搭建简单账号登录系统_第39张图片
SSM框架整合-搭建简单账号登录系统_第40张图片
SSM框架整合-搭建简单账号登录系统_第41张图片
SSM框架整合-搭建简单账号登录系统_第42张图片
4.配置Application context
SSM框架整合-搭建简单账号登录系统_第43张图片
其实这个就是配置访问路径, 然后访问路径就是http://localhost:8080/ssmtest2_war_exploded+你的controller里写的映射路径
但是这样不修改的话,.每次都要加上/ssmtest2_war_exploded,多麻烦呀, 所以我们直接删掉/ssmtest2_war_exploded (当然你写成你喜欢的路径名也行)

SSM框架整合-搭建简单账号登录系统_第44张图片
这样我们的访问路径就简单了, 问路径就是http://localhost:8080+你的controller里写的映射路径
比如访问登录成功页面
SSM框架整合-搭建简单账号登录系统_第45张图片
对应访问路径: http://localhost:8080/success
5.其它配置
SSM框架整合-搭建简单账号登录系统_第46张图片

2.项目启动

1.以DEBUG方式启动
SSM框架整合-搭建简单账号登录系统_第47张图片
2.启动成功

3.功能测试

1.测试拦截器
不登录账号, 直接输入登录成功页面的网址进行访问
SSM框架整合-搭建简单账号登录系统_第48张图片
按下回车

可以看到访问请求被拦截, 被重定向到登录页面

2.测试登录成功
输入正确的账号密码,登录成功
SSM框架整合-搭建简单账号登录系统_第49张图片
SSM框架整合-搭建简单账号登录系统_第50张图片
3.测试js功能
将鼠标光标放置在色块内移动进行测试
SSM框架整合-搭建简单账号登录系统_第51张图片
4.测试自定义异常页面跳转
我写了一个int i = 10/0来模拟异常
SSM框架整合-搭建简单账号登录系统_第52张图片

点击 测试异常跳转
SSM框架整合-搭建简单账号登录系统_第53张图片

10.完整项目代码下载

可能对于有些新手按照本博客所写步骤来搭建项目还是有些困难, 所以在这直接给出完整项目代码
完整项目代码下载地址:https://download.csdn.net/download/qq_41865229/85564989

你可能感兴趣的:(后端开发问题解决,intellij-idea,maven,java,ssm)