[hands on tutorial][JavaWeb]SSM framework verification, repair and instance

[hands on tutorial][JavaWeb]SSM framework verification, repair and instance

[maybe this article is a little long, but the content is very detailed. You are waiting for a full knowledge of dry goods. Remember to sign for the benefits at the end of the article]

Java learning and communication qun:925895158, only create a small communication circle for small partners who love learning java

tool

  • IDE is idea15
  • JDK environment is 1.8
  • Maven version is maven3
  • Mysql version is 5.5.27
  • Tomcat version is 7.0.52

Current objectives

  • Project framework introduction and conflict resolution.
  • Instance Service and Dao. Project framework test.
  • Log in, register for business analysis, creation, and presentation.

conflict resolution

Why do I put conflict resolution first?

After the conflict is resolved, we can enter the testing phase. At the same time, when the conflict is resolved, we will gradually understand how the frameworks in the SSM project framework work together, and then we can complete the project introduction.

What is important is that in real life, when we go to work in the company, we usually solve the conflict of project framework first.

  • After opening the project, select a Spring configuration file at will, and the following interface will pop up:

    The first step of ssm framework detection

    Click the part circled in the upper right corner of the figure, and the following interface will pop up:

    Step 2 of ssm framework detection

    Here we don't need to do anything, just click OK.

    The above two steps are to tell Idea where our Spring configuration file is. ApplicationContext similar to a single Spring configuration file Like XML, we just distribute Spring according to modules.

  • Run this project in Tomcat, and the result should be to display the Hello World interface in the browser.

    • Configuring Tomcat

    • Configure Tomcat startup settings for the project.

    • Reference connection: Click to enter

    • Enter: localhost:8080/druid in the web browser to check whether the Druid is successfully configured.

      Step 3 of ssm framework detection

      As shown in the figure above, we can see that our druid does not list JDBC drivers. This indicates that the jdbc driver of our project is either not set or the configuration file of the database driver is not ready.

    • Enter an address under localhost:8080/. So far, we will show the Error 404 page. And replace the Tomcat unfriendly 404 page.

      • Replacement idea: Error 404, a common page, can be set as a static resource to speed up Web page access.

      • Note: we need to put web-in\fweb Change MVC dispatcher under XML to global configuration.

        <servlet-mapping>
            <servlet-name>mvc-dispatcher</servlet-name>
            <!-- Match all requests by default -->
            <!-- We configure this by default so that our Spring Frame nozzle Servelt,achieve Spring Control all site requests -->
            <url-pattern>/</url-pattern>
            <!--<url-pattern>/css/*</url-pattern>-->
            <!--<url-pattern>/images/*</url-pattern>-->
            <!--<url-pattern>/fonts/*</url-pattern>-->
        </servlet-mapping>
        

        Configured web After XML, we restart the application, enter an incorrect address (jump to page 404), and you will find an error message. The main errors are as follows

         Exception encountered during context initialization - cancelling refresh attempt: 
            org.springframework.beans.factory.BeanCreationException: 
                Error creating bean with name 'dataSource' defined in file [Physical address of the project\WEB-INF\classes\spring\spring-dao.xml]: 
                    Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/slf4j/Logger
            
            //The above error mainly prompts us: NoClassDefFoundError: org/slf4j/ this class cannot be found.
        
        Solution: lazy log4j2 from maven Deleted in the configuration file and enabled logback,stay maven of pom.xml Medium:
            
            <!-- 1.journal -->
            <!--<!– achieve slf4j Interface and integration –>-->
            <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.1</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${org.slf4j.version}</version>
            </dependency>
        
            <!--log4j2 support-->
            <!--<dependency>-->
                <!--<groupId>org.apache.logging.log4j</groupId>-->
                <!--<artifactId>log4j-core</artifactId>-->
                <!--<version>${org.apache.logging.log4j.version}</version>-->
            <!--</dependency>-->
            <!--<dependency>-->
                <!--<groupId>org.apache.logging.log4j</groupId>-->
                <!--<artifactId>log4j-api</artifactId>-->
                <!--<version>${org.apache.logging.log4j.version}</version>-->
            <!--</dependency>-->
        

        Then, we restart Tomcat. After the project deployment is completed, we open it again and enter the wrong address again. We find that we are still reporting an error. The information is as follows:

        Exception encountered during context initialization - cancelling refresh attempt: 
            org.springframework.beans.factory.BeanCreationException: 
                Error creating bean with name 'sqlSessionFactory' defined in file [Project physical address\WEB-INF\classes\spring\spring-dao.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: 
                    Failed to convert property value of type [java.lang.String] to required type [org.springframework.core.io.Resource[]] for property 'mapperLocations'; 
                        nested exception is java.lang.IllegalArgumentException: 
                            Could not resolve resource location pattern [classpath:mapper/*.xml]: class path resource [mapper/] cannot be resolved to URL because it does not exist
                            
            According to the above prompt information, we can see that the prompt is mapper There is no file below, so we will make an empty configuration file for him(BaseDao.xml),The contents are as follows:
            
                <?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 Yes specify Mybatis Scanned directories, mapper It's ours Dao Mapping directory for layer -->
                <mapper namespace="cn.acheng1314.dao">
                </mapper>
        

        Similarly, we restart the server again and input the wrong address. Now the page with Error 404 can be displayed normally, but the page is too Low. We have to rewrite the web XML configuration. The 404 page is as follows:

        ssm framework detects 404 template page

        Solution: the page of Error 404 is one of the commonly used pages, so we create a static directory under the project resource directory (webapp) to store static resources, such as js, css, error prompt page, login page, registration page, etc.

        Through online reference, we can see that most people submit 404 page prompt information to Servelt We manage by ourselves, and we also draw ladles in the same way web.xml , as follows:
        <error-page>
            <error-code>404</error-code>
            <Location>/static/view/404.html</Location>
        </error-page>
        

        At the same time, we need to write a web configuration for spring to control which resources are intercepted. Spring web The XML file is configured as follows:

        <?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-3.0.xsd">
            <!-- allocation SpringMVC -->
            <!-- 1.open SpringMVC Annotation mode -->
            <!-- Simplified configuration:
                (1)automatic logon DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter
                (2)Provide some columns: data binding, number and date format @NumberFormat, @DateTimeFormat, xml,json Default read / write support
            -->
            <mvc:annotation-driven/>
            <!-- 2.Static resource default servlet allocation
                (1)Add processing of static resources: js,gif,png
                (2)Allow to use"/"Make overall mapping
             -->
            <mvc:resources mapping="/css/**" location="/static/css/" />
            <mvc:resources mapping="/images/**" location="/static/images/" />
            <mvc:resources mapping="/view/**" location="/static/view/" />
            <mvc:default-servlet-handler/>
        
            <!-- 3.allocation jsp display ViewResolver -->
            <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
                <property name="prefix" value="/WEB-INF/jsp/"/>
                <property name="suffix" value=".jsp"/>
            </bean>
        
            <!-- 4.scanning web Related bean allocation -->
            <context:component-scan base-package="cn.acheng1314.mvc">
                <!-- Develop package scanning rules ,Scan only for use@Controller Annotated JAVA class -->
                <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            </context:component-scan>
        
        </beans>
        

        After the above files are configured, we restart the server and enter the wrong address. Now the 404 page we inserted is displayed normally.

        Through the above information, we can boldly sort out the ideas of web requests:

        The user initiates a request → DNS resolves the discovery server → establishes a link to send a request → the WEB server distributes it to the application server → the MVC layer framework processes the request → returns data to the user

        As the above SpringMvc is the framework layer, we can also make some ideas through online materials and our current configuration:

        Tomact distributes the request → servlet receives the request → Spring takes over the servlet → DispatcherServlet processes the request distribution → find the corresponding Controller to process the business according to the Spring configuration → return the corresponding data.

        A more prominent picture below illustrates all this:

        SpringMVC detailed operation flow chart

        Summary: at present, we have processed the static resources in the project, added some static resources of the web, added the web processing configuration of Spring, and modified the web XML, log4j2 is replaced by LogBack, Junit version is upgraded to 4.12, and a basemapper XML.

        Web The XML file is as follows:

        <!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
        <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_3_1.xsd"
         version="3.1" metadata-complete="true">
          <welcome-file-list>
              <welcome-file>index.html</welcome-file>
              <welcome-file>index.htm</welcome-file>
              <welcome-file>index.jsp</welcome-file>
              <welcome-file>default.html</welcome-file>
              <welcome-file>default.htm</welcome-file>
              <welcome-file>default.jsp</welcome-file>
          </welcome-file-list>
          <!-- If yes mvn Command generated xml,Need modification servlet Version 3.1 -->
          <!-- allocation DispatcherServlet -->
          <servlet>
              <display-name>SSM</display-name>
              <servlet-name>mvc-dispatcher</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <!-- allocation springMVC Configuration file to load
                  spring-dao.xml,spring-service.xml,spring-web.xml
                  Mybatis - > spring -> springmvc
               -->
              <init-param>
                  <param-name>contextConfigLocation</param-name>
                  <param-value>classpath:spring/spring-*.xml</param-value>
              </init-param>
          </servlet>
          <servlet-mapping>
              <servlet-name>mvc-dispatcher</servlet-name>
              <!-- Match all requests by default -->
              <url-pattern>/</url-pattern>
              <!--<url-pattern>/css/*</url-pattern>-->
              <!--<url-pattern>/images/*</url-pattern>-->
              <!--<url-pattern>/fonts/*</url-pattern>-->
          </servlet-mapping>
        
          <!-- spring Character set filter provided by framework -->
          <!-- spring Web MVC Framework provides org.springframework.web.filter.CharacterEncodingFilter For solving POST Chinese garbled code caused by  -->
          <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>
              <!-- force Force -->
              <init-param>
                  <param-name>forceEncoding</param-name>
                  <param-value>true</param-value>
              </init-param>
          </filter>
          <filter-mapping>
              <filter-name>encodingFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>
        
          <!--druid ==> WEB Mode monitoring configuration-->
          <servlet>
              <servlet-name>DruidStatView</servlet-name>
              <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
          </servlet>
          <servlet-mapping>
              <servlet-name>DruidStatView</servlet-name>
              <url-pattern>/druid/*</url-pattern>
          </servlet-mapping>
          <filter>
              <filter-name>druidWebStatFilter</filter-name>
              <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
              <init-param>
                  <param-name>exclusions</param-name>
                  <param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
              </init-param>
              <init-param>
                  <param-name>principalSessionName</param-name>
                  <param-value>sessionInfo</param-value>
              </init-param>
              <init-param>
                  <param-name>profileEnable</param-name>
                  <param-value>true</param-value>
              </init-param>
          </filter>
          <filter-mapping>
              <filter-name>druidWebStatFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>
        
          <error-page>
              <error-code>404</error-code>
              <location>/static/view/404.html</location>
          </error-page>
        </web-app>
        

        Basemapper The XML is as follows:

        <?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 Point to us dao Address of -->
        <mapper namespace="cn.acheng1314.dao">
        </mapper>
        

        Other file modification information can be seen on the above and will not be posted again.

SSM framework instance -- warehouse management system -- functional analysis of login and registration

Analysis:

  • Login and registration are both user behaviors and the business corresponding to a certain behavior that we often say in development.
  • Registering users means adding users. Only after adding users can we continue the login function.
  • User login is also a process of searching and comparing user information. Generally speaking, the user submits the information to the program first, and then the program executes according to the process and submits the data to the server (the program may generate some business logic judgments in this process). The server receives the data and compares the data. When the user information exists and the account and password match, the login can succeed. Otherwise, the login fails if any of the preceding conditions are not met.
  • We can rely on a single user table to achieve the acquisition of user login data and the addition of registration information.

After the function analysis, we can consider how to implement these functions. The approximate diagram is as follows:

Classic three-layer analysis of ssm framework

  • First, user information needs to be stored. We need the support of the database.
  • With the support of the database, we need to test the addition and search of user information. This is what we often call the Dao layer.
  • When our Dao layer gets the desired data, we need the Service layer to provide Dao layer operations as services to the controller, and then the controller provides them to the foreground page.
  • The same user needs to obtain some data. First, the browser obtains the user request → web layer → Service layer → Dao layer, and then repeat the above operations.

The above figure has well explained the relationship between the java web back-end layers with the model, and the following figure is a description of the classic three-layer comparison MVC.

Comparison of classic three-layer analysis of ssm framework Mvc

The above figure is quoted from Internet materials, and the black words below are added by me.

  • In the above figure, we can see that some MVC designs are similar to those marked in the figure, but this is only a chestnut of MVC pattern.

  • For more detailed MVC, we can Baidu Encyclopedia View.

As for the above-mentioned things, we can just stop there. Many things are not the time to study deeply. We need to understand the external performance of a thing before we have further exploration. Therefore, we need to wait for the arrival of fate.

SSM framework instance -- warehouse management system -- function simulation implementation of registration and login

According to our previous analysis, we need to consider the implementation of the Dao layer first. After all, the following operations can only be carried out after the Dao layer encapsulates the data. Therefore, in my chestnut, everything is implemented according to the steps of Dao → Service → Controller → View.

  • Dao layer implementation of user registration function.
    • The basic operations of the database are: add, delete, modify and query.

    • According to the types of regular database operations, we abstract them respectively, so dao Java is the basic model of this interface object. The codes are as follows:

      /**
       * Programming via interface
       * @param <T> Generics are used for decoupling while avoiding writing duplicate code
       */
      public interface Dao<T> {
          /**
           * Add an object
           * @param t Objects to be added
           * @return  Returns the number of rows affected
           */
          int add(T t);
      
          /**
           * To delete an object, in enterprise development, we generally do not delete it physically, but only add a field to control its data availability
           * @param t Object to be deleted
           * @return Return the number of affected items
           */
          int  del(T t);
      
          /**
           * Update an object
           * @param t Object to be updated
           * @return Return the number of affected items
           */
          int update(T t);
      
          /**
           * Find an object by ID
           * @param Id    ID of the object to be queried
           * @return  Return the object corresponding to this ID
           */
          T findOneById(Serializable Id);
      
          /**
           * Find object collection
           * @return  Returns a collection of objects
           */
          List<T> findAll();
      }
      
    • Implementing the user's Dao layer:

      • We need to write the user Dao layer for users. We need to have a user object encapsulation and directly create a user under the domain package Java, the code is as follows:
      /***
      To create a database user table:
       CREATE TABLE `user` (
       `login_id` varchar(20) NOT NULL COMMENT 'Login ID',
       `pwd` varchar(20) NOT NULL COMMENT 'User password ',
       `name` varchar(100) NOT NULL COMMENT 'User name ',
       `age` int(3) NOT NULL COMMENT 'User age ',
       `sex` varchar(3) NOT NULL COMMENT 'Gender ',
       `duty` varchar(15) COMMENT 'Title ',
       `cell_number` varchar(15) COMMENT 'Mobile number ',
       `photo_url` varchar(75) COMMENT 'Avatar address',
       `used` boolean NOT NULL COMMENT 'Whether the account is available ',
       PRIMARY KEY (`login_id`)
       ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8 COMMENT='User table ';
      
       Insert default data:
       INSERT INTO `user` (`login_id`,`pwd`,`name`,`age`,`sex`,`used`)
       VALUES
       ('pc859107393','123456','Cheng ', 20,' male ', true),
       ('pc228568859','123456','chengcheng',20,'Female ', true),
       ('pangpang','123456','The rest of the night ', 25,' male ', true),
       ('111111','123456','Hand in hand tutorial series', 22, 'female', true);
       */
      
      public class User implements Serializable {
          private String name;    //name
          private String sex; //Gender
          private String loginId; //Login ID
          private String pwd;    //password
          private String duty;    //post
          private int age;    //Age
          private String cellNumber;  //Mobile number
          private String photoUrl;    //Avatar address
          private boolean used = true;   //Whether it is available. The default value is true
          
          ···ellipsis get,set and toString
      }    
      
      //It is recommended that you note the database operations corresponding to each bean above.
      //Open Navicat For Mysql, link the database, create the corresponding database, and run the above sql to generate database tables and initial records.
      
      • After the database is created, we need to write an interface to encapsulate the user table. We create the UserDao interface under the dao package. The code is as follows:
      /**
       * In traditional jdbc operations, we need to manually manage the switch of database connection, database resource access, and so on
       * <br/>However, we have adopted the two frameworks of Mybatis and Druid, so we can completely ignore the control of database connection and so on,
       * <br/>We just need to focus more on the development of business implementation.
       */
      public interface UserDao extends Dao<User> {
          int add(User user);
      
          int del(User user);
      
          int update(User user);
      
          User findOneById(Serializable Id);
      
          List<User> findAll();
      }
      
      
      • After the encapsulation of UserDao is completed, the traditional operation step needs to manually implement the Impl of UserDao and operate the database. After we use Mybatis, the Impl of UserDao is specified as xml in the mapper folder of Mybatis. Except for the database operation statements, our Dao files do not need to be paid attention to, so we do not need to care about the rest of the database operations. After all, Mybatis and druid have done other things for us. UserDao The xml is as follows:
      <?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 Specify our to specific bean -->
      <mapper namespace="cn.acheng1314.dao.UserDao">
      
          <!--lookup-->
          <select id="findOneById" resultType="User" parameterType="String">
              SELECT
              *
              FROM
              `user`
              WHERE
              login_id = #{userId}
          <select>
      
          <!--Add statement-->
          <insert id="add" parameterType="User">
          INSERT INTO
              `user`
              (`login_id`,`name`,`age`,`sex`,`duty`,`cell_number`,`photo_url`,`pwd`,`used`)
              VALUES
              (#{loginId},#{name},#{age},#{sex},#{duty},#{cellNumber},#{photoUrl},#{pwd},#{used})
          </insert>
      
          <!-- delete -->
          <update id="del" parameterType="User">
              UPDATE
              `user`
              SET
              `used`=FALSE
              WHERE
              `login_id`=#{loginId};
          </update>
      
          <!-- Update user information -->
          <update id="update" parameterType="User">
              UPDATE
              `user`
              SET
              `name`=#{name}, `age`=#{age}, `sex`=#{sex}, `duty`=#{duty}, `cell_number`=#{cellNumber}, `photo_url`=#{photoUrl}
              WHERE
              `login_id`=#{loginId};
          </update>
      </mapper>
      
      • UserDao XML has been completed, which means that our UserDao is basically completed, so we should have a unit test to see the effect. Userdaotest Java is as follows:
      @RunWith(SpringJUnit4ClassRunner.class) //Unit test of spring
      @ContextConfiguration({"classpath:spring/spring-*.xml"})    //Context configuration
      public class UserDaoTest {
      
          @Autowired
          private UserDao userDao;    //Initialize Dao layer, interface oriented programming
          
          /**
          * Add a user's unit test, and you will be prompted whether the addition is successful or not.
          * Of course, my configuration is generally correct. If there is an error, you need to look at the error prompt code step by step.
          * Adding a user with the same LoginId will fail because LoginId is used as the primary key of the database table.
          */
          @Test
          public void testAdd() {
              User user = new User();
              user.setLoginId("pc147852369");
              user.setName("It rained all night");
              user.setPwd("123456");
              user.setSex("unknown");
              int result = 0; //The number of affected rows defaults to 0
              try {
                  result = userDao.add(user);
              } catch (Exception e) {
                  e.printStackTrace();
                  System.out.println("Failed to add user");
              }
              if (result>0)
                  System.out.println("User added successfully");
          }
          
          /**
          * Find out whether the user test is successful or not, and whether the log will be output
          */
          @Test
          public void testFindOneId() throws Exception {
              User user = new User();
              user.setLoginId("pc147852369");
              User result = null; //The number of affected rows defaults to 0
              try {
                  result = userDao.findOneById(user.getLoginId());
              } catch (Exception e) {
                  e.printStackTrace();
                  System.out.println("Failed to find user");
              }
              if (null!=result)
                  System.out.println("User found successfully\n"+result.toString());
          }
      
          @Test
          public void testDel() {
              User user = new User();
              user.setLoginId("pc147852369");
              int result = 0; //The number of affected rows defaults to 0
              try {
                  result = userDao.del(user);
              } catch (Exception e) {
                  e.printStackTrace();
                  System.out.println("Delete user failed");
              }
              if (result>0)
                  System.out.println("User deleted successfully");
          }
      
          @Test
          public void testUpdate() {
              User user = new User();
              user.setLoginId("pc147852369");
              user.setName("Handlebar tutorial");
              user.setPwd("123456");
              user.setSex("male");
              int result = 0; //The number of affected rows defaults to 0
              try {
                  result = userDao.update(user);
              } catch (Exception e) {
                  e.printStackTrace();
                  System.out.println("Failed to update user information user");
              }
              if (result>0)
                  System.out.println("User information updated successfully");
      
          }
      }
      

      The data operation results can be viewed in mysql. Here are not the screenshots one by one. Of course, we can also see that each unit test needs to annotate the spring unit test and spring context on the class. According to our programming principles, one-time coding runs everywhere. We can put these annotations into basetest In Java, all the following unit tests inherit basetest Java can avoid a lot of repeated coding.

    • UserService implementation (pay attention to the cultivation of programming thinking)

      • According to our thinking of interface oriented programming, the core of our Service is to implement the Dao layer and call the Dao layer.
      • Just now we passed the unit test and our UserDao layer passed the test. Now we should focus on the implementation of business logic rather than continue to pester the Dao layer. After all, data persistence has been implemented.
      • From the point of view of the server program, the main businesses of users include registration, login, logout, logout, etc. here, let's talk about registration first.
      • User registration process analysis (user perspective):
        • Fill in relevant information of account number
        • Submit registration information
        • The server returns whether the registration is successful
      • User registration process analysis (server perspective):
        • User registration request received
        • Unpack data → package to UserBean
          • Unpacking data failed (abnormal request information), and an error message is returned
        • Check whether the standard is met for specific user information
          • If the inspection standard is not met, the corresponding error prompt is returned
        • By checking, call Dao to check whether the same user exists
          • The same user information already exists in the database and cannot be added repeatedly. An error message is returned
        • If the same user does not exist, add a new user and return a successful prompt

      The flow chart is reflected as follows:

      ssm framework user behavior analysis flow chart

      • The code implements the Service registered by the user:
      //Create a BaseService interface and use generic decoupling
      public interface UserService extends BaseService<User> {
          //Add an instance of a user
          void add(User user) throws Exception;
      }
      
      ------------------------------Split line----------------------------------
      
      //Create a UserService to inherit the BaseService and specify the specific entity type
      //Why write another UserService interface? Different objects have different business systems, and BaseService cannot completely replace the specific behavior of different objects
      public interface UserService extends BaseService<User> {
      
          void add(User user) throws Exception;
      }
      
      ------------------------------Split line----------------------------------
      
      //Create UserServiceImpl to implement UserService interface
      @Service("userService")
      public class UserServiceImpl implements UserService {
      
          @Autowired
          private UserDao userDao;
      
          /**
           * To add a user, it is generally necessary to check that the user is empty, the user name is empty, and the password is empty
           */
          public void add(User user) throws UserCanNotBeNullException, UserNameCanNotBeNullException, UserPwdCanNotBeNullException, UserAireadyExistException, OtherThingsException {
              //First check whether the user exists
              if (null == user) {
                  //Throw a user-defined exception with an empty user
                  throw new UserCanNotBeNullException("User can not be Null");
              }
              //User name cannot be empty check
              if (StringUtils.isEmpty(user.getLoginId())) {
                  //Throw a custom exception with empty user name
                  throw new UserNameCanNotBeNullException("User name can not be Null");
              }
              //User password cannot be empty check
              if (StringUtils.isEmpty(user.getPwd())) {
                  //Throw a user-defined exception with an empty user password
                  throw new UserPwdCanNotBeNullException("User name can not be Null");
              }
              //Since this is a warehouse management system, our basic user information cannot be empty according to business requirements
              //Basic information includes: name, age, user name, password, gender and mobile phone number. Age is greater than 18
              if (StringUtils.isEmpty(user.getDuty())
                      || StringUtils.isEmpty(user.getSex())
                      || user.getAge() > 18
                      || StringUtils.isEmpty(user.getCellNumber())) {
                  //Other comprehensive anomalies
                  throw new OtherThingsException("Some use's base info can not be null");
              }
              //The same user already exists
              if (null != userDao.findOneById(user.getLoginId())) {
                  //The same user exception exists
                  throw new UserAireadyExistException("Register User Failed,Because the  user Aiready exist");
              }
              int result = 0; //The number of affected rows defaults to 0
              try {
                  result = userDao.add(user);
              } catch (Exception e) {
                  System.out.println("Failed to add user,User already exists");
                  //Add other users failed exception
                  throw new OtherThingsException(e);
              }
              if (result > 0)
                  System.out.println("User added successfully");
          }
          
          //···Other methods omitted···
          
      }
      
      
      • According to the old rule, after writing each Service, unit tests should be conducted for the behavior of specific objects. Userservicetest The Java code is as follows:
      public class UserServiceTest extends BaseTest {
          @Autowired
          private UserServiceImpl userService;    
          //The implementation class of UserService is directly used here, mainly to facilitate throwing exceptions, and then the exceptions can be handled in a targeted manner
          
          @Test
          public void testAdd() {
              User user = new User();
              try {
                  userService.add(user);
              } catch (UserCanNotBeNullException e) {
                  //The user cannot throw an empty exception
                  e.printStackTrace();
              } catch (UserNameCanNotBeNullException e) {
                  //User name cannot be empty
                  e.printStackTrace();
              } catch (UserPwdCanNotBeNullException e) {
                  //User password cannot be empty
                  e.printStackTrace();
              } catch (UserAireadyExistException e) {
                  //User presence throw
                  e.printStackTrace();
              } catch (OtherThingsException e) {
                  //Other comprehensive exceptions or exceptions that cannot be handled
                  e.printStackTrace();
              }
          }
          
          //···Other test codes omitted···
      }
      
      • Similarly, after the test code of our Service is executed, we can see the specific data changes in mysql and will not map them one by one.

Because of space and time, we will not write the detailed implementation of specific functions for the time being. After all, learning is not overnight. It is important to cultivate more thinking. Since this period, the code has gradually increased. After all, the learning process is such an incremental process. After getting familiar with it, it may be more about cultivating the way of thinking in many places, and the code will be directly posted (there will be no fewer detailed comments).

Summary of this period:

  • Solve the project framework conflict, and briefly introduce the functions of each framework.
  • Simple principle explanation.
  • java web classic mvc and three-tier architecture are briefly introduced.
  • Some simple SQL statements.
  • Unit tests for Dao layer and Service layer.
  • Process analysis of simple business implementation.

The content of this article is very detailed. I believe everyone has different gains

The blogger has prepared a small welfare for you. I hope it can help you

Like to pay a little attention to it. You can get it for free by editing [data] of private letters

 

 

 

Tags: MySQL Java Programming

Posted by toffler on Wed, 01 Jun 2022 05:21:17 +0530