当前位置:网站首页>Using SSM framework to realize user login

Using SSM framework to realize user login

2022-06-22 01:10:00 Yushijuj

One 、SSM frame

( One )SSM What is it

  • SSM(Spring+SpringMVC+MyBatis) The frameset is made up of Spring、MyBatis Integration of two open source frameworks (SpringMVC yes Spring Part of ), Often used as a simple data source Web Project framework .

( Two )Spring frame

  • Spring It's like assembling the whole project Bean Big factory of , In the configuration file, you can specify to use specific parameters to call the constructor of entity class to instantiate the object . It can also be called the adhesive in the project .Spring The core idea of IoC( Inversion of control ), That is, there is no need for programmers to explicitly new An object , Rather let Spring The framework helps you do all this .

( 3、 ... and )Spring MVC frame

  • Spring MVC Intercept user requests in the project , The core of it Servlet namely DispatcherServlet Take on the role of an intermediary or front desk , Pass the user request through HandlerMapping To match Controller,Controller It is the specific operation corresponding to the request .Spring MVC amount to SSH In the frame Struts.
  • M: The model layer 、V: View layer 、C: Control layer
  • MVC Initially present in the desktop program ,M The business model ,V User interface ,C Controller , Use MVC The goal is to M and V Implementation code separation of , So that the same program can use different forms of expression . For example, a batch of statistical data can be used as a histogram 、 Pie chart to show .C The purpose of existence is to ensure that M and V Synchronization of , once M change ,V It should be updated synchronously .
  • Model - View - controller (MVC) yes Xerox PARC It was a programming language in the 1980s Smalltalk-80 A software design pattern invented , Has been widely used . Later recommended as Oracle its Sun company Java EE Design mode of the platform , And it's used more and more ColdFusion and PHP Welcome to developers . Model - View - Controller mode is a useful toolbox , It has many advantages , But there are also some disadvantages .

( Four )MyBatis frame

  • MyBatis It's right JDBC (Java DataBase Connectivity) Encapsulation , It makes the underlying database operations transparent .MyBatis The operations are all around a sqlSessionFactory Examples expand .MyBatis Through the configuration file associated with each entity class Mapper file ,Mapper The file configures what each class needs to do with the database SQL Statements mapping . Every time you interact with the database , adopt sqlSessionFactory To get a sqlSession, Re execution SQL command . Page send request to controller , The controller calls the business layer processing logic , The logic layer sends requests to the persistence layer , The persistence layer interacts with the database , Then return the result to the business layer , The business layer sends the processing logic to the controller , The controller calls the view to display the data .

Two 、 User login operation effect

  • The client has a non null check
  • Login successful , Jump to the main page
  • Login failed , Jump to login page again
     Insert picture description here

3、 ... and 、 utilize SSM The framework realizes user login

( One ) Create databases and tables

1. Create database

  • Carry out orders :CREATE DATABASE ssmdb CHARSET='utf8mb4';
     Insert picture description here

  • View the created database
     Insert picture description here

2. Create a user table

  • perform SQL Command to generate user table t_user
     Insert picture description here
    CREATE TABLE `t_user` (
    	  `id` int(11) NOT NULL AUTO_INCREMENT,
    	  `username` varchar(20) NOT NULL,
    	  `password` varchar(20) DEFAULT NULL,
    	  `telephone` varchar(11) DEFAULT NULL,
    	  `register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    	  `popedom` int(11) DEFAULT NULL COMMENT '0: Administrators ;1: Ordinary users ',
    	  PRIMARY KEY (`id`)
    	) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    

3. User table add record

  • perform SQL Command addition 4 Bar record
     Insert picture description here
    INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2021-09-02 08:40:35', '0');
    INSERT INTO `t_user` VALUES ('2', 'alice', '11111', '13956567889', '2021-10-20 09:51:43', '1');
    INSERT INTO `t_user` VALUES ('3', 'brown', '22222', '13956678907', '2022-03-21 09:52:36', '1');
    INSERT INTO `t_user` VALUES ('4', 'linda', '33333', '15890905678', '2022-05-25 09:52:56', '1');
    

( Two ) establish Maven project

  • establish Maven project - SSMLogin

  • Set project commands 、 Project location 、 Group ID And projects ID
     Insert picture description here

  • single click 【Finish】 Button
     Insert picture description here

( 3、 ... and ) Add dependencies

  • stay pom.xml Add related dependencies to the file
     Insert picture description here

    <?xml version="1.0" encoding="UTF-8"?>
    <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.0</modelVersion>
    
       <groupId>net.qzj.ssm</groupId>
       <artifactId>SSMLogin</artifactId>
       <version>1.0-SNAPSHOT</version>
    
       <properties>
           <!-- spring.version -->
           <spring.version>5.3.20</spring.version>
       </properties>
    
       <dependencies>
           <!--Spring The core -->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-core</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!--Spring Bean-->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-beans</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!--Spring Containers -->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-context</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!--Spring test -->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-test</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!--Spring Database support -->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-jdbc</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!-- Database driver toolkit -->
           <dependency>
               <groupId>mysql</groupId>
               <artifactId>mysql-connector-java</artifactId>
               <version>5.1.49</version>
           </dependency>
           <!-- Database connection pool framework -->
           <dependency>
               <groupId>com.alibaba</groupId>
               <artifactId>druid</artifactId>
               <version>1.2.10</version>
           </dependency>
           <!-- Persistence layer frame -->
           <dependency>
               <groupId>org.mybatis</groupId>
               <artifactId>mybatis</artifactId>
               <version>3.5.10</version>
           </dependency>
           <!-- Provide MyBatis And Spring Integrated support -->
           <dependency>
               <groupId>org.mybatis</groupId>
               <artifactId>mybatis-spring</artifactId>
               <version>2.0.7</version>
           </dependency>
           <!-- Log framework -->
           <dependency>
               <groupId>log4j</groupId>
               <artifactId>log4j</artifactId>
               <version>1.2.17</version>
           </dependency>
           <!-- unit testing -->
           <dependency>
               <groupId>junit</groupId>
               <artifactId>junit</artifactId>
               <version>4.13.2</version>
               <scope>test</scope>
           </dependency>
           <!--Spring Web-->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-web</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!--Spring MVC-->
           <dependency>
               <groupId>org.springframework</groupId>
               <artifactId>spring-webmvc</artifactId>
               <version>${spring.version}</version>
           </dependency>
           <!--JSP Standard label library -->
           <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>jstl</artifactId>
               <version>1.2</version>
           </dependency>
           <!--Servlet-->
           <dependency>
               <groupId>javax.servlet</groupId>
               <artifactId>javax.servlet-api</artifactId>
               <version>3.1.0</version>
               <scope>provided</scope>
           </dependency>
       </dependencies>
    </project>
    
  • open Maven window , Click the refresh button , Download dependency
     Insert picture description here

  • Dependent on successful download
     Insert picture description here

( Four ) Create log properties file

  • stay resources Create in directory log4j.properties file
     Insert picture description here
    log4j.rootLogger=WARN, stdout, logfile
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
    log4j.appender.logfile=org.apache.log4j.FileAppender
    log4j.appender.logfile.File=target/ssm.log
    log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
    log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
    

( 5、 ... and ) Create database configuration properties file

  • stay resources Create in directory jdbc.properties
     Insert picture description here

    jdbc.driverClassName = com.mysql.jdbc.Driver
    jdbc.url = jdbc:mysql://localhost:3306/ssmdb?useSSL=false
    jdbc.username = root
    jdbc.password = 123456
    
  • explain :jdbc.url Sometimes you may also need to set the code and time zone , Change the database password to your own computer database password

( 6、 ... and ) Add to project Web function

  • Click... On the toolbar 【Project Structure】 Button
     Insert picture description here

  • without 【Project Structure】 Button , Click on File
     Insert picture description here

  • see 【Modules】 Content
     Insert picture description here

  • single click 【SSMLogin】 Upper left corner + ++ Button
     Insert picture description here
     Insert picture description here

  • single click 【Create Artifact】 Button
     Insert picture description here

  • Default SSMLogin:Web exploded Renamed as SSMLogin
     Insert picture description here

  • WEB-INF Directory classes In the subdirectory are the byte code files compiled by the source program written by the user , But the project depends on jar The package needs to create a lib Catalog
     Insert picture description here
     Insert picture description here

  • Put the one on the right Available Elements select all , Right click , Pop up the shortcut menu
     Insert picture description here

  • single click Put into /WEB-INF/lib A menu item , Put the selected jar Add the package to the left /WEB-INF/lib Catalog
     Insert picture description here

  • single click 【OK】 Button
     Insert picture description here

( 7、 ... and ) To configure Tomcat The server

1. install Tomcat The server

  • download tomcat-8.5.58.rar, Unzip to E disc IDE Catalog
     Insert picture description here

  • Enter the executable Directory bin
     Insert picture description here

  • To configure Tomcat environment variable
     Insert picture description here
     Insert picture description here

2. start-up Tomcat service

  • Execute... In the command window :startup.bat, start-up Tomcat service ( Of course, you can double-click directly in the Explorer window startup.bat Icon )
     Insert picture description here

3. visit Tomcat Home page

  • Home page in E:\IDE\tomcat-8.5.58\webapps\ROOT Directory
     Insert picture description here

  • Access in browser http://localhost:8080( or http://localhost:8080/index.jsp
     Insert picture description here

4. Accessing static resources on the server

  • stay webapps Create in directory qzj subdirectories , Put some static resources in it
     Insert picture description here

  • Check the local area network IP Address
     Insert picture description here

  • It can be accessed locally or remotely http://10.225.92.49:8080/qzj/welcome.txt

  • It can be accessed locally or remotely http://10.225.92.49:8080/qzj/bear.png

5. Project configuration Tomcat The server

  • Delete Selected 【Add Configuration…】
     Insert picture description here
     Insert picture description here
     Insert picture description here
     Insert picture description here
     Insert picture description here
     Insert picture description here
     Insert picture description here
     Insert picture description here

( 8、 ... and ) Create user entity class

  • establish net.qzj.ssm.bean package , Create in package User class
     Insert picture description here
    package net.qzj.ssm.bean;
    
    import java.util.Date;
    
    /**
    *  function : User entity class 
    */
    public class User {
       private int id;
       private String username;
       private String password;
       private String telephone;
       private Date registerTime;
       private int popedom;
    
       public int getId() {
           return id;
       }
    
       public void setId(int 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;
       }
    
       public String getTelephone() {
           return telephone;
       }
    
       public void setTelephone(String telephone) {
           this.telephone = telephone;
       }
    
       public Date getRegisterTime() {
           return registerTime;
       }
    
       public void setRegisterTime(Date registerTime) {
           this.registerTime = registerTime;
       }
    
       public int getPopedom() {
           return popedom;
       }
    
       public void setPopedom(int popedom) {
           this.popedom = popedom;
       }
    
       @Override
       public String toString() {
           return "User{" +
                   "id=" + id +
                   ", username='" + username + '\'' +
                   ", password='" + password + '\'' +
                   ", telephone='" + telephone + '\'' +
                   ", registerTime=" + registerTime +
                   ", popedom=" + popedom +
                   '}';
       }
    }
    

( Nine ) Create a user mapper interface

  • establish net.qzj.ssm.mapper package , Create in package UserMapper Interface
     Insert picture description here
    package net.qzj.ssm.mapper;
    
    import net.qzj.ssm.bean.User;
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Param;
    
    /**
    *  function : User mapper interface 
    */
    @Mapper //  hand Spring Container management 
    public interface UserMapper {
       User login(@Param("username") String username, @Param("password") String password);
    }
    

( Ten ) Create a user service class

  • stay net.qzj.ssm Create in package service subpackage , Then create in the sub package UserService class
     Insert picture description here
package net.qzj.ssm.service;

import net.qzj.ssm.bean.User;
import net.qzj.ssm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
*  function : User service class 
*/
@Service //  hand Spring Container management 
public class UserService {
   @Autowired //  Automatic assembly 
   private UserMapper userMapper;

   public User login(String username, String password) {
       return userMapper.login(username, password);
   }
}

( 11、 ... and ) Create user controller

  • stay net.qzj.ssm Create in package controller subpackage , Then create in the sub package UserController class
     Insert picture description here
    package net.qzj.ssm.controller;
    
    import net.qzj.ssm.bean.User;
    import net.qzj.ssm.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import javax.servlet.http.HttpSession;
    
    /**
    *  function : User controller 
    */
    @Controller //  hand Spring Container management 
    @RequestMapping("/user") //  Total route 
    public class UserController {
       @Autowired
       private UserService userService;
    
       @RequestMapping("/login") //  Sub route 
       public String login(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           HttpSession session) {
           //  Call the login method of the user service object 
           User user = userService.login(username, password);
           //  Determine whether the user has successfully logged in 
           if (user != null) {
               //  Write the login user name to the session 
               session.setAttribute("username", username);
               //  Delete the login error message that may exist in the session 
               if (session.getAttribute("loginMsg") != null) {
                   session.removeAttribute("loginMsg");
               }
               System.out.println(user);
    
               //  Judge the user role , Jump to a different page 
               if (user.getPopedom() == 0) { //  Administrators 
                   //  Jump to the background management page 、
                   return "backend/management"; //  Logical view name 
               } else { //  Ordinary users 
                   //  Jump to the front page 
                   return "frontend/index"; //  Logical view name 
               }
           } else {
               //  Write login error information to session 
               session.setAttribute("loginMsg", " Wrong user name or password !");
               //  Jump to the front desk login page 
               return "frontend/login"; //  Logical view name 
           }
       }
    
       @RequestMapping("/logout")
       public String logout(HttpSession session) {
           //  Delete the user name information saved in the session 
           session.removeAttribute("username");
           //  End the conversation 
           session.invalidate();
           //  Jump to the front desk login page 
           return "frontend/login"; //  Logical view name 
       }
    }
    

( Twelve ) Create a user mapper profile

  • stay resources Created in mapper subdirectories , Then create in the subdirectory UserMapper.xml
     Insert picture description here
    <?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">
    
    <mapper namespace="net.qzj.ssm.mapper.UserMapper">
       <!-- Define the result mapping , Because the table field name is not consistent with the entity attribute name -->
       <resultMap id="userMap" type="net.qzj.ssm.bean.User">
           <result property="id" column="id"/>
           <result property="username" column="username"/>
           <result property="password" column="password"/>
           <result property="telephone" column="telephone"/>
           <result property="registerTime" javaType="java.util.Date" column="register_time" jdbcType="TIMESTAMP"/>
           <result property="popedom" column="popedom"/>
       </resultMap>
       
       <!-- Define login mapping statements -->
       <select id="login" resultMap="userMap">
           SELECT * FROM t_user WHERE username = #{username} AND password = #{password};
       </select> 
    </mapper>
    
  • jdbctype Type a :REAL 、VARCHAR 、BINARY 、BIT、FLOAT、CHAR 、TIMESTAMP 、 OTHER 、UNDEFINEDTINYINT 、BLOB NVARCHAR、SMALLINT 、DOUBLE 、DECIMAL 、TIME 、NULL、CURSOR、LONGVARCHAR 、VARBINARY 、CLOB、NCHAR、INTEGER、 NUMERIC、DATE 、LONGVARBINARY 、BOOLEAN 、NCLOB、BIGINT

( 13、 ... and ) Prepare static resources

1. Prepare picture resources

  • stay WEB-INF Created in images Catalog , Used to store picture resources - bear.png
     Insert picture description here

2. Create a style file

  • stay WEB-INF Created in css subdirectories , Then create in the subdirectory login.css
     Insert picture description here
    /*  style  */
    body {
       margin: 0px;
       text-align: center;
       background: #cccccc;
    }
    

3. Create script file

  • stay WEB-INF Created in js subdirectories , Then create in the subdirectory check.js
     Insert picture description here
    /**
    *  Verify the login form 
    * @returns {Boolean}
    */
    function checkLoginForm() {	
       //  Get user name text box 
       var username = document.getElementById("username");
       //  Get password text box 
       var password = document.getElementById("password");
       //  Non empty verification 
       if (username.value == "") {
       	alert(" The username cannot be empty !");
       	//  Let the user name text box get focus 
       	username.focus();
       	return false;
       }
       if (password.value == "") {
       	alert(" The password cannot be empty !");
       	//  Let the password text box get focus 
       	password.focus();
       	return false;
       }	
       	
       return true; //  Indicates that the data can be submitted to the server 
    }
    

( fourteen ) Create a page

1. Create directory structure

  • stay WEB-INF Created in views subdirectories , stay views Created in frontend and backend Two subdirectories
     Insert picture description here

2. Create a landing page

  • stay views/frontend Created in login.jsp
     Insert picture description here

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <c:set var="path" value="${pageContext.request.contextPath}"/>
    <c:set var="basePath"
          value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
    <html>
    <head>
       <title> The user login </title>
       <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
       <base href="${basePath}">
       <script src="js/check.js"></script>
       <link href="css/login.css" rel="stylesheet" type="text/css"/>
    </head>
    <body>
    <h3 style="text-align: center"> The user login </h3>
    <form id="frmLogin" action="user/login" method="post">
       <table class="tb" border="1" cellpadding="10" style="margin: 0px auto">
           <tr>
               <td align="center"> account number </td>
               <td><input id="username" type="text" name="username"/></td>
           </tr>
           <tr>
               <td align="center"> password </td>
               <td><input id="password" type="password" name="password"/></td>
           </tr>
           <tr align="center">
               <td colspan="2">
                   <input type="submit" value=" Sign in " onclick="return checkLoginForm()"/>
                   <input type="reset" value=" Reset "/>
               </td>
           </tr>
       </table>
    </form>
    <c:if test="${loginMsg!=null}">
       <script type="text/javascript">alert("${loginMsg}")</script>
       <c:remove var="loginMsg"/>
    </c:if>
    </body>
    </html>
    
  • Client request , The service gets the data submitted by the login form , Call the login method of the service class for business processing , Jump to different pages according to the business processing results

3. Create a homepage

  • stay views/frontend Created in index.jsp
     Insert picture description here
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <c:set var="path" value="${pageContext.request.contextPath}"/>
    <c:set var="basePath"
          value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
    <html>
    <head>
       <title> home page </title>
       <base href="${basePath}">    
    </head>
    <body>
    <h3> Welcome to Simon shopping </h3>
     The logged in user :${username} —— <a href="user/logout"> Cancellation </a><br/>
    <img src="images/bear.png" width="300" height="250">
    </body>
    </html>
    

4. Create a background management page

  • stay views/backend Created in management.jsp
     Insert picture description here
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <c:set var="path" value="${pageContext.request.contextPath}"/>
    <c:set var="basePath"
          value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
    <html>
    <head>
       <title> Background management </title>
       <base href="${basePath}">
    </head>
    <body>
    <h3> Simon shopping network background management </h3>
     Administrators :${username} —— <a href="user/logout"> Cancellation </a><br/>
    <img src="images/bear.png" width="300" height="250">
    </body>
    </html>
    

( 15、 ... and ) establish Spring The configuration file

  • stay resources Created in config subdirectories , Then create in the subdirectory spring-config.xml
     Insert picture description here

    <?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">
    
       <!-- Component scan -->
       <context:component-scan base-package="net.qzj.ssm"/>
    
       <!-- Read jdbc Properties file , For creating data sources -->
       <context:property-placeholder location="classpath:jdbc.properties"/>
    
       <!-- Configure data sources Bean, Use Ali's Druid Database connection pool -->
       <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
           <!-- Configure the basic properties of the data source -->
           <property name="driverClassName" value="${jdbc.driverClassName}"/>
           <property name="url" value="${jdbc.url}"/>
           <property name="username" value="${jdbc.username}"/>
           <property name="password" value="${jdbc.password}"/>
       </bean>
    
       <!-- Define the persistence layer framework MyBatis Of SQL Conversational factory -->
       <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
           <!-- Configure data sources , Responsible for operating objects -->
           <property name="dataSource" ref="dataSource"/>
           <!-- Configure mapper location , Responsible for the operation method -->
           <property name="mapperLocations" value="classpath:mapper/*Mapper.xml"/>
       </bean>
    
       <!-- To configure MyB Mapper scan -->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
           <!-- binding SQL Conversational factory -->
           <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
           <!-- Configure the root package scanned by the mapper -->
           <property name="basePackage" value="net.qzj.ssm.mapper"/>
       </bean>
    </beans>
    
  • explain : This case does not update the database , Therefore, transaction management is not introduced

  • If the database is updated in the project , that UserService You should add @Transactional annotation , and Spring Add transaction management to the configuration file .

    <!--  Transaction annotation driven , mark @Transactional Your classes and methods will be transactional  -->                                                 
    <tx:annotation-driven transaction-manager="txManager" />                                    
                                                                                               
    <!-- Define transaction management notifications -->                                                                             
    <tx:advice id="txAdvice" transaction-manager="txManager">                                   
       <tx:attributes>                                                                         
           <tx:method name="find*" read-only="true"/>                                          
           <tx:method name="add*" propagation="REQUIRED"/>                                     
           <tx:method name="delete*" propagation="REQUIRED"/>                                  
           <tx:method name="update*" propagation="REQUIRED"/>                                  
       </tx:attributes>                                                                        
    </tx:advice>                                                                                
                                                                                               
    <!-- Declarative transaction Notifier , Need to be in pom.xml Add based on AspectJ Of AOP Support -->                                                
    <aop:config>                                                                                
       <aop:pointcut id="mypt" expression="execution(public * net.hw.shop.service..*.*(..))"/> 
       <aop:advisor advice-ref="txAdvice" pointcut-ref="mypt"/>                                
    </aop:config>                                                                               
    

( sixteen ) establish Spring MVC The configuration file

  • stay resources/config Create in directory spring-mvc-config.xml
     Insert picture description here
    <?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"
          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/mvc
          https://www.springframework.org/schema/mvc/spring-mvc.xsd
          http://www.springframework.org/schema/context
          https://www.springframework.org/schema/context/spring-context.xsd">
    
       <!-- Handle requests for static resources -->
       <mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
       <mvc:resources mapping="/images/**" location="/WEB-INF/images/"/>
       <mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
    
       <!-- Annotation driven -->
       <mvc:annotation-driven />
    
       <!-- Scanning controller ( Added @Controller Annotated classes )-->
       <context:component-scan base-package="net.qzj.ssm.controller"/>
    
       <!-- Do not scan service classes ( Added @Service Annotated classes ), Remain spring-config.xml Inside scan , Prevent transaction failures -->
       <context:component-scan base-package="net.qzj.ssm">
           <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
       </context:component-scan>
    
       <!-- Define the internal resource view parser -->
       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
           <property name="prefix" value="/WEB-INF/views/"/>
           <property name="suffix" value=".jsp"/>
       </bean>
       
       <!-- Define the view controller ( Responsible for page Jump )-->
       <mvc:view-controller path="user/login" view-name="frontend/login"/>
    </beans>
    

( seventeen ) edit Web Deployment description file

  • stay WEB-INF Written in the directory web.xml file
     Insert picture description here
    <?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">
    
       <display-name>simonshop</display-name>
       <welcome-file-list>
           <welcome-file>/WEB-INF/views/frontend/login.jsp</welcome-file>
       </welcome-file-list>
    
       <!--Spring Monitor , Give Way Spring along with Web Project startup and initialization -->
       <listener>
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener>
    
       <!--  Appoint Spring Profile location  -->
       <context-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:config/spring-config.xml</param-value>
       </context-param>
    
       <!-- To configure Spring Front controller , Read the controller configuration file through initialization parameter settings -->
       <servlet>
           <servlet-name>DispatcherServlet</servlet-name>
           <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
           <init-param>
               <param-name>contextConfigLocation</param-name>
               <param-value>classpath:config/spring-mvc-config.xml</param-value>
           </init-param>
           <load-on-startup>1</load-on-startup>
       </servlet>
    
       <!--Spring MVC The dispatcher of is responsible for all client requests -->
       <servlet-mapping>
           <servlet-name>DispatcherServlet</servlet-name>
           <url-pattern>/</url-pattern>
       </servlet-mapping>
    
       <!-- Set character encoding filter -->
       <filter>
           <filter-name>Character Encoding</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>Character Encoding</filter-name>
           <url-pattern>/*</url-pattern>
       </filter-mapping>
    </web-app>
    

( eighteen ) Start the server , See the effect

  • Start the server
     Insert picture description here

  • Because in web.xml Set in file <welcome-file>/WEB-INF/views/frontend/login.jsp</welcome-file> Elements , So the login page will be displayed first
     Insert picture description here

  • Non empty verification
     Insert picture description here
     Insert picture description here

  • Login failed
     Insert picture description here

  • Enter the correct user name and password
     Insert picture description here

  • single click 【 Cancellation 】 link , Return to login page
     Insert picture description here

原网站

版权声明
本文为[Yushijuj]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220011547593.html