Build SSM framework

1, Create Maven project (idea version)

  • I'm used to creating empty maven projects and configuring them myself, so I can learn a lot

2, Import dependent coordinates

  • Note: be sure to see the purpose of each package by yourself. Don't put everything in the project according to the mess on the Internet

2.1 pom.xml

2.1.1 jar package coordinates
<dependencies>
    <!-- Junit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- Database driven -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- Database connection pool -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
    <!-- Servlet-JSP -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.13</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.16</version>
    </dependency>
</dependencies>
2.1.2 static resource processing
<!-- Static resource export problem -->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>
  • Look, how clean the project files are. The projects you create automatically with webapp are a little numb

3, Database connection test

3.1 use the built-in tools to test the database connection


  • After successful connection, select the database you want to test:
  • After setting, you can view the contents in the database, and you can also write SQL statements online for CRUD practice, which is fun!

3.2 write properties to store database connection information - for later use

  • Create a database under the project resource path resources Properties file
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ledgetms?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
  • The first behavior is database connection driver
  • The second line specifies the identification URL for the database connection
  • The third line is the database connection user name
  • The fourth line is the database connection password

4, Mybatis framework integrates jdbc to realize data persistence layer

4.1 create the entity class package pojo under the java source file and load the database mapping object

  • com. lms. pojo. Realbaseinfo class - logistics basic data entity class:
package com.lms.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class RearBaseInfo {
    /*
        campus
     */
    private String location;
    /*
        area covered
     */
    private float area;
    /*
        Total building area
     */
    private float struArea;
    /*
        Greening area
     */
    private float greeningArea;
    /*
        Green area
     */
    private float greenArea;
    /*
        Number of classroom seats
     */
    private int seatNum;
    /*
        Number of canteen seats
     */
    private int dineNum;
    /*
        Library area
     */
    private float libArea;
    /*
        Administrative office area
     */
    private float officeArea;
}

  • Note: look at the import part. This is the lombok package imported under the pom file. It can automatically generate the methods of no parameter, with parameter, get, set, toString, euqals and hashCode. It's very lazy, hee hee!!!
  • Is it very convenient? Let's use it!

4.2 create the Mybatis framework configuration file Mybatis config. In the resources directory XML, and inject the entity class into the ioc container as a bean object

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!-- Configure the data source and submit it to Spring Do it -->
    <typeAliases>
        <!-- Nicknamed, SQL You can directly use the class name in without writing the fully qualified class name -->
        <package name="com.lms.pojo"/>
    </typeAliases>
</configuration>

4.3 create dao package under java source file and install it in data access layer interface and xml file to realize interface

4.3.1 Interface file
package com.ssm.dao;

import com.ssm.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper {

    //Add a Book
    int addBook(Books books);
    //Delete a Book
    int deleteBook(@Param("bookId") int id);
    //Update a Book
    int updateBook(Books books);
    //Inquire about a Book
    Books queryBookById(@Param("bookId") int id);
    //All book inquiries
    List<Books> queryAllBook();

    //Query books
    Books queryBookByName(@Param("bookName") String bookName);
}
4.3.2 xml interface implementation file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ssm.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail) values (#{bookName}, #{bookCounts}, #{detail});
    </insert>

    <delete id="deleteBook" parameterType="int">
        delete from ssmbuild.books where bookID = #{bookId};
    </delete>

    <update id="updateBook" parameterType="Books">
        update ssmbuild.books set bookName=#{bookName}, bookCounts=#{bookCounts}, detail=#{detail} where bookID=#{bookID};
    </update>

    <select id="queryBookById" resultType="Books">
        select * from ssmbuild.books where bookID=#{bookId};
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books;
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from ssmbuild.books where bookName = #{bookName};
    </select>
</mapper>
4.3.3 writing dao layer configuration file

springmvc-dao.xml file, namely Dao layer configuration file, is responsible for injecting database resources, connection pool and factory class, and scanning all resource files under Dao layer

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

    <!-- Associated database profile -->
    <context:property-placeholder location="classpath:database.properties"/>

    <!-- 2.Connection pool
            dbcp:Semi automatic operation, unable to connect automatically
            c3p0:Automatic operation (automatic loading of configuration files and automatic setting into objects)
            druid: hikari
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!-- c3p0 Private properties of connection pool -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- Not automatically after closing the connection commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- Get connection timeout -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- Number of retries when getting connection failed -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>

    <!-- 3.SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- binding Mybatis configuration file -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- to configure dao Interface scanning package, dynamic implementation Dao Interface can be injected into Spring In container -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- injection SqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- Packages to scan -->
        <property name="basePackage" value="com.lms.dao"/>
    </bean>
</beans>
4.3.4 inject dao layer into ioc container in Mybatis configuration file and submit it to Spring for management
<mappers>
    <mapper class="com.lms.dao.RearBaseInfoMapper"/>
</mappers>

5, Implementation of view+controller+service integration in spring MVC framework

5.1 service layer - call to dao layer

Create business layer interface files and implementation classes under java resource files

5.1.1 *Service interface file
package com.lms.service;

import com.lms.pojo.RearBaseInfo;
import java.util.List;

public interface RearBaseInfoService {

    //Add a piece of data
    int addRearBaseInfo(RearBaseInfo rearBaseInfo);
    //Delete a piece of data
    int deleteRearBaseInfo(String location);
    //Modify a piece of data
    int updateRearBaseInfo(RearBaseInfo rearBaseInfo);
    //Query a piece of data
    RearBaseInfo queryRearBaseInfo(String location);
    //Query all data
    List<RearBaseInfo> queryAllRearBaseInfo();
}
  • If you find it familiar, it's right. This interface is the same as the Mapper interface file under the dao layer, that is, you can't call some of Mybatis's own annotations, and copy the rest completely
5.1.2 *ServiceImpl business layer interface implementation class
package com.lms.service.impl;

import com.lms.dao.RearBaseInfoMapper;
import com.lms.pojo.RearBaseInfo;
import com.lms.service.RearBaseInfoService;

import java.util.List;

public class RearBaseInfoServiceImpl implements RearBaseInfoService {

    //service layer calls dao layer method
    private RearBaseInfoMapper rearBaseInfoMapper;

    public int addRearBaseInfo(RearBaseInfo rearBaseInfo) {
        return rearBaseInfoMapper.addRearBaseInfo(rearBaseInfo);
    }

    public int deleteRearBaseInfo(String location) {
        return rearBaseInfoMapper.deleteRearBaseInfo(location);
    }

    public int updateRearBaseInfo(RearBaseInfo rearBaseInfo) {
        return rearBaseInfoMapper.updateRearBaseInfo(rearBaseInfo);
    }

    public RearBaseInfo queryRearBaseInfo(String location) {
        return rearBaseInfoMapper.queryRearBaseInfo(location);
    }

    public List<RearBaseInfo> queryAllRearBaseInfo() {
        return rearBaseInfoMapper.queryAllRearBaseInfo();
    }
}

5.2 write Service layer configuration file

  • Because all Spring layer bean objects need to be managed by the Ioc container of the Spring framework, first create the top-level configuration file of Spring under the resources resource path
5.2.1 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

</beans>

It is only responsible for managing the configuration files of other parts of Spring and generating the corresponding bean objects through the reflection mechanism.

  • The file resources under the above Service package are configured and managed by the Ioc container of Spring
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           https://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context
                           https://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 1.scanning service Package under -->
    <context:component-scan base-package="com.lms.service"/>

    <!-- 2.Inject all business classes into Spring It can be implemented through configuration or annotation -->
    <bean id="rearBaseInfoServiceImpl" class="com.lms.service.impl.RearBaseInfoServiceImpl">
        <property name="rearBaseInfoMapper" ref="rearBaseInfoMapper"/>
    </bean>

    <!-- 3.Declarative transaction configuration -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Injection data source -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 4.aop Transaction support -->
    <!-- combination AOP Implement transaction weaving -->
    <!-- Configure the propagation characteristics of transactions: new propagation -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- Configure transactions for methods -->
        <!-- Configure propagation properties of transactions -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- Configure transaction entry -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.lms.dao.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

5.3 testing

  • After writing so much, I don't know whether the database transaction is effective. Use unit test to test the data access layer interface
5.3.1 C-increase operation
@Test
public void addRearBaseInfo() {
    //Read the Spring top-level configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //The configuration file obtains the service layer bean object through the reflection mechanism to process the business
    RearBaseInfoService rearBaseInfoService = (RearBaseInfoService) context.getBean("rearBaseInfoServiceImpl");
    //Processing business
    int i = rearBaseInfoService.addRearBaseInfo(new RearBaseInfo("love", 1, 2, 3, 4, 5, 6, 7, 8));
    if (i > 0)
        System.out.println("Record added successfully");
    else
        System.out.println("Failed to add record");
}

  • Add the log function of Mybatis, and then the log printed on the console is a mess. You can see the whole life cycle activities of SqlSession, which is very convenient.

  • Data results in this specific database

5.3.2 D-delete operation
@Test
public void deleteRearBaseInfo() {
    //Read the Spring top-level configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //The configuration file obtains the service layer bean object through the reflection mechanism to process the business
    RearBaseInfoService rearBaseInfoService = (RearBaseInfoService) context.getBean("rearBaseInfoServiceImpl");
    int i = rearBaseInfoService.deleteRearBaseInfo("love");
    if (i > 0)
        System.out.println("Record deleted successfully");
    else
        System.out.println("Failed to delete record");
}


5.3.3 U-change operation
@Test
public void updateRearBaseInfo() {
    //Read the Spring top-level configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //The configuration file obtains the service layer bean object through the reflection mechanism to process the business
    RearBaseInfoService rearBaseInfoService = (RearBaseInfoService) context.getBean("rearBaseInfoServiceImpl");
    int i = rearBaseInfoService.updateRearBaseInfo(new RearBaseInfo("love", 10, 20, 30, 40, 50, 60, 70, 80));
    if (i > 0)
        System.out.println("Record modified successfully");
    else
        System.out.println("Failed to modify record");
}


  • Pay attention to whether there is any discovery. Once modified, it is found that all records are modified data. I'm a little afraid. Find the reason!!!
<update id="updateRearBaseInfo" parameterType="RearBaseInfo">
    update ledgetms.rearbaseinfo set area = #{area}, struArea = #{struArea}, greeningArea = #{greeningArea}, seatNum = #{seatNum},
    dineNum = #{dineNum}, libArea = #{libArea}, officeArea = #{officeArea};
</update>
<update id="updateRearBaseInfo" parameterType="RearBaseInfo">
    update ledgetms.rearbaseinfo set area = #{area}, struArea = #{struArea}, greeningArea = #{greeningArea}, seatNum = #{seatNum},
    dineNum = #{dineNum}, libArea = #{libArea}, officeArea = #{officeArea} where location = #{location};
</update>
  • Insert the corresponding primary key condition after the SQL statement and try again:
rearBaseInfoService.updateRearBaseInfo(new RearBaseInfo("love", 100, 200, 300, 400, 500, 600, 700, 800));

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-onowjg0d-1606874604485) (C: \ users \ lbs59 \ appdata \ roaming \ typora user images \ image-2020113016335274. PNG)]

  • yeah! Successful, only the corresponding one has been changed!
5.3.4 R-check operation
@Test
public void queryRearBaseInfo() {
    //Read the Spring top-level configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //The configuration file obtains the service layer bean object through the reflection mechanism to process the business
    RearBaseInfoService rearBaseInfoService = (RearBaseInfoService) context.getBean("rearBaseInfoServiceImpl");
    RearBaseInfo info = rearBaseInfoService.queryRearBaseInfo("love");
    System.out.println(info);
}
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'com.lms.dao.RearBaseInfoMapper.queryRearBaseInfo'.  It's likely that neither a Result Type nor a Result Map was specified.
  • Note that this is the log of running failure. Yes, it failed again. However, it is easy to understand that there is log printing. It is that the corresponding result return type is not given. However, the return type of the query operation written by my dao layer interface is realbaseinfo, which does not belong to the basic data type or String type. Therefore, it is necessary to explicitly define resultType = "realbaseinfo".
<select id="queryRearBaseInfo" resultType="RearBaseInfo">
    select * from ledgetms.rearbaseinfo where location = #{loc};
</select>

  • It worked, wow! This log print is impeccable, love, love! The arrangement is clear.

Finally, there is a record of general investigation, so there is no title. Go directly to the above figure:

@Test
public void queryAllRearBaseInfo() {
    //Read the Spring top-level configuration file
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //The configuration file obtains the service layer bean object through the reflection mechanism to process the business
    RearBaseInfoService rearBaseInfoService = (RearBaseInfoService) context.getBean("rearBaseInfoServiceImpl");
    List<RearBaseInfo> list = rearBaseInfoService.queryAllRearBaseInfo();
    for (RearBaseInfo rearBaseInfo : list)
        System.out.println(rearBaseInfo);
}

  • If it is not clear, use it quickly!!!

5.4 View layer + Controller layer

Create a controller package in the java source file directory to store the control layer resource files. In the final analysis, the underlying implementation is still Servlet. The simplified Servlet is good.

It's important to forget that our project is not a web project yet. Add a web support to it. What we need to do is a Java Web project

  • After adding web support successfully, the project will be added to the same web directory. Here, we only need to store some view layers and the configuration of the whole web project. We need to create a jsp directory under the WEB-INF directory to store our views. Why? The permissions of this WEB-INF directory are relatively high. Generally, the view of this directory cannot be accessed by directly jumping to the front-end page. How should we operate the resources under this directory? We have a Controller. The control permissions are on our back-end. Is it safe?!
5.4.1 spring MVC configuration file
  • To tell the truth, in the previous online tutorials, there are only three configuration files for an ssm framework, which is equivalent to one configuration file for a framework, but there are 1000 Harry Potter for 1000 readers. There are all kinds of things. I have vomited. I simply configure them separately, which is not much. On the contrary, it makes our thinking clearer.
<?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
                           https://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/mvc
                           http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/context
                           https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 1.Annotation driven -->
    <mvc:annotation-driven/>
    <!-- 2.Static resource filtering -->
    <mvc:default-servlet-handler/>
    <!-- 3.Scan package: controller -->
    <context:component-scan base-package="com.ssm.controller"/>
    <!-- 4.view resolver  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
  • See the view parser above? This configuration is very important. It can help us access the view resources under WEB-INF, and can splice url addresses well. Is it very considerate?!

By the way, put the web XML configuration. There's nothing to say about this

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

    <!-- DispatcherServlet -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Solve the problem of Chinese garbled code -->
    <filter>
        <filter-name>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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Session -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>
</web-app>
5.4.1 view + control
  1. The first is the home page: index jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>System home page</title>
        <style>
            a {
                text-decoration: none;
                color: black;
                font-size: 18px;
            }
            h3 {
                width: 180px;
                height: 38px;
                margin: 100px auto;
                text-align: center;
                line-height: 38px;
                background: deepskyblue;
                border-radius: 5px;
            }
            h1 {
                text-align: center;
            }
        </style>
    </head>
    <body>
        <h1>This is the system home page</h1>
        <h3>
            <a href="${pageContext.request.contextPath}/util/toLoginPage">Enter the login page</a>
        </h3>
    </body>
</html>

  • There must be some leading artists coming here to roast. Well, I admit, I'm good at the back end. Let the front end go with the wind. What we need is business processing, business processing, and give the things on the facade to those who do art work.

  • The corresponding controller controls the jump

@Controller
@RequestMapping("/util")
public class AdminUtilController {
    @RequestMapping("/toLoginPage")
    public String toLoginPage() {
        return "/login";
    }
}
  • Note: be sure to add the Controller annotation to the class name in the Controller file, so that the Ioc container of Spring can recognize that you are a Controller class, not an ordinary class. In this way, when parsing the return value of each Controller, the Spring container will not treat it as a string, but splice your return value with the prefix and suffix of the view parser to find the corresponding view layer page, which is very convenient!!!
  1. Click "enter login page" to jump to login page: login jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Login page</title>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>
        <script>
            function a1() {
                if ($("#name").val().toString() !== 'admin') {
                    alert("The user name is incorrect, please re-enter!!!");
                }
            }
            function a2() {
                if ($("#pwd").val().toString() !== '123456') {
                    alert("The password is incorrect. Please re-enter it");
                }
            }
        </script>
    </head>
    <body>
        <div class="container">
            <div class="row" style="margin-top: 30px">
                <div class="col-md-4 col-md-offset-4">
                    <div class="panel panel-primary">
                        <div class="panel-heading">
                            <span class="glyphicon glyphicon-user"></span>Sign in
                        </div>
                        <div class="panel-body">
                            <form action="${pageContext.request.contextPath}/util/toAdminIndexPage" method="post">
                                <div class="form-group">
                                    <label>user name</label> <input type="text" class="form-control" id="name" name="username" placeholder="enter one user name" required οnblur="a1()">
                                </div>
                                <div class="form-group">
                                    <label>password</label> <input type="password" class="form-control" id="pwd" name="password" placeholder="Please input a password" required οnblur="a2()">
                                </div>
                                <button type="submit" class="btn btn-primary">Sign in</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

  • Well, it's still ugly. div+div+div is nested layer by layer. I'm stupid. It's good to make a frame like it. Don't spray it if you don't like it. Here, the user name I set is "admin" and the password is "123456", which is a dead string. If you don't enter it like this, OK, pop up and serve:

  • In fact, I still need to input the correct string. I have some problems when dealing with the front-end js myself. It's clear at a glance by looking at the js processing function written in the jsp file. If I don't press this input, sometimes the pop-up window can't be closed, and you doubt your life.

  • The corresponding controller controls the jump

@Controller
@RequestMapping("/util")
public class AdminUtilController {
    @Autowired
    @Qualifier("rearBaseInfoServiceImpl")
    private RearBaseInfoService rearBaseInfoService;
    @RequestMapping("/toAdminIndexPage")
    public String toAdminIndexPage(String username, String password) {
        if ("admin".equals(username) && "123456".equals(password))
            return "adminIndex";
        return null;
    }
}
  1. Click "login interface", and after successful login, enter the administrator operation home page: adminindex jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Administrator action</title>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
        <style>
            a {
                text-decoration: none;
                color: black;
                font-size: 18px;
            }
            h3 {
                width: 180px;
                height: 38px;
                margin: 100px auto;
                text-align: center;
                line-height: 38px;
                background: deepskyblue;
                border-radius: 5px;
            }
            h1 {
                text-align: center;
            }
        </style>
    </head>
    <body>
        <h1>Here is the administrator operation interface - please select the required operation</h1>
        <div>
            <h3>
                <a href="${pageContext.request.contextPath}/util/adminInfo">Administrator information</a>
            </h3>
        </div>
        <div>
            <h3>
                <a href="${pageContext.request.contextPath}/util/allRearBaseInfo">Basic logistics information</a>
            </h3>
        </div>
        <div>
            <h3>
                <a href="${pageContext.request.contextPath}/util/toLoginPage">Log out</a>
            </h3>
        </div>
    </body>
</html>

  • I used several buttons instead of specific business logic. What I want to complete is specific business logic operations, not specific UI beautification. Don't tangle with details.

  • First verify the "exit login operation", that is, return to the login page, and the corresponding controller controls the jump

@Controller
@RequestMapping("/util")
public class AdminUtilController {
    @RequestMapping("/toLoginPage")
    public String toLoginPage() {
        return "/login";
    }
}
  • To tell you the truth, the trend of the page depends entirely on the operation of the controller here. I have to say that the controller is really powerful, because it has been shown in front of the login interface, so it will not be shown here again.
  1. Click the "administrator information" button to jump to the administrator information page. Because the administrator table is not created in the database, I directly display AdminInfo in the interface with ordinary string jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Administrator information</title>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">

            <div class="row clearfix">
                <div class="col-md-12 column">
                    <div class="page-header">
                        <h1>
                            <small>Data presentation - administrator information</small>
                        </h1>
                    </div>
                </div>

                <div class="row">
                    <div class="clo-md-4 column">
                        <a class="btn btn-primary" href="${pageContext.request.contextPath}/util/returnAdminIndex">return</a>
                    </div>
                </div>

            </div>

            <div class="row clearfix">
                <div class="col-md-6 column">
                    <table class="table table-hover table-striped">
                        <thead>
                            <tr>
                                <th>user name</th>
                                <th>password</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>admin</td>
                                <td>123456</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </body>
</html>

  • Well, this is the user name and password that made me haggard on the login interface just now. I can't close the window without popping up. I write it down silently in my heart.

  • The corresponding controller controls the jump

@Controller
@RequestMapping("/util")
public class AdminUtilController {
    @RequestMapping("/adminInfo")
    public String toAdminInfoPage() {
        return "/adminInfo/adminInfo";
    }
}
  • Click the "return" button to return to the administrator operation home page, and the corresponding controller controls the jump
@Controller
@RequestMapping("/util")
public class AdminUtilController {
    @RequestMapping("/returnAdminIndex")
    public String returnAdminIndex() {
        return "/adminIndex";
    }
}
  • As above, the administrator operation home page has been displayed, and will not be displayed here.

  • Click "basic logistics information" to enter the main page of campus basic logistics information, and the corresponding controller controls the jump

@Controller
@RequestMapping("/util")
public class AdminUtilController {
    
    @Autowired
    @Qualifier("rearBaseInfoServiceImpl")
    private RearBaseInfoService rearBaseInfoService;
    
    public String toRearBaseInfoPage(Model model) {
        List<RearBaseInfo> list = rearBaseInfoService.queryAllRearBaseInfo();
        model.addAttribute("rearBaseInfo", list);
        return "/rearBaseInfo/allRearBaseInfo";
    }
}
  • I don't know if you have noticed any details. When we jump to this page, we have a reference of Model type in the parameter list. This object is equivalent to a carrier, which can help us load the data transmitted from the server to the web page. It's a bit like when we only use the spring MVC framework, the return type of most of our controllers is ModelAndView. The function of this object is similar to that of Model, However, it can not only load data, but also reprint the page path that the user wants to request forwarding, and finally return the ModelAndView reference.
  1. Enter the logistics data display page allrealbaseinfo jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Display of basic logistics data</title>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <div class="row clearfix">
                <div class="col-md-12 column">
                    <div class="page-header">
                        <h1>
                            <small>Data list - displays all basic logistics data</small>
                        </h1>
                    </div>
                </div>

                <div class="row">
                    <div class="clo-md-4 column">
                        <a class="btn btn-primary" href="${pageContext.request.contextPath}/rearBaseInfo/toAddPage">Add logistics data</a>
                        <a class="btn btn-primary" href="${pageContext.request.contextPath}/util/allRearBaseInfo">Display all logistics data</a>
                    </div>
                    <div class="clo-md-4 column">
                        <div class="clo-md-4 column">
                            <%-- Query basic logistics data --%>
                            <form action="${pageContext.request.contextPath}/rearBaseInfo/queryRearBaseInfo" method="post" style="float: right">
                                <input type="text" name="queryLocation" class="form-control" placeholder="Please enter the campus name to query">
                                <input type="submit" value="query" class="btn btn-primary">
                            </form>
                        </div>
                    </div>
                </div>

                <div class="row clearfix">
                    <div class="col-md-12 column">
                        <table class="table table-hover table-striped">
                            <thead>
                                <tr>
                                    <th>campus</th>
                                    <th>area covered(Mu)</th>
                                    <th>Total building area(Mu)</th>
                                    <th>Greening area(㎡)</th>
                                    <th>afforested area(㎡)</th>
                                    <th>Number of classroom seats(individual)</th>
                                    <th>Number of canteen seats(individual)</th>
                                    <th>Library area(㎡)</th>
                                    <th>Administrative office area(㎡)</th>
                                    <th>operation</th>
                                </tr>
                            </thead>
                            <tbody>
                                <%-- Books are queried from the database list Traversal from: foreach --%>
                                <c:forEach var="rearBaseInfo" items="${rearBaseInfo}">
                                    <tr>
                                        <td>${rearBaseInfo.location}</td>
                                        <td>${rearBaseInfo.area}</td>
                                        <td>${rearBaseInfo.struArea}</td>
                                        <td>${rearBaseInfo.greeningArea}</td>
                                        <td>${rearBaseInfo.greenArea}</td>
                                        <td>${rearBaseInfo.seatNum}</td>
                                        <td>${rearBaseInfo.dineNum}</td>
                                        <td>${rearBaseInfo.libArea}</td>
                                        <td>${rearBaseInfo.officeArea}</td>
                                        <td>
                                            <a href="${pageContext.request.contextPath}/rearBaseInfo/toUpdatePage?location=${rearBaseInfo.location}">modify</a>
                                            &nbsp; | &nbsp;
                                            <a href="${pageContext.request.contextPath}/rearBaseInfo/deleteRearBaseInfo?location=${rearBaseInfo.location}">delete</a>
                                        </td>
                                    </tr>
                                </c:forEach>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

  • Whether this page is much richer, good or ugly, the place circled above is all the business operations completed - CRUD. Each will be shown one by one below.

  • Click "add logistics data" to jump to the operation page of adding data, and the corresponding controller controls the jump

@Controller
@RequestMapping("/rearBaseInfo")
public class RearBaseInfoController {
    //Jump to add data page
    @RequestMapping("/toAddPage")
    public String toAddPaper() {
        return "/rearBaseInfo/addRearBaseInfo";
    }
}
  1. Enter the new data page addrealbaseinfo jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Add logistics basic data</title>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container">

            <div class="row clearfix">
                <div class="col-md-12 column">
                    <div class="page-header">
                        <h1>
                            <small>Add basic logistics data</small>
                        </h1>
                    </div>
                </div>

                <form action="${pageContext.request.contextPath}/rearBaseInfo/addRearBaseInfo">
                    <div class="form-group">
                        <label>Campus:</label>
                        <input type="text" name="location" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>area covered(Mu): </label>
                        <input type="text" name="area" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Total building area(Mu): </label>
                        <input type="text" name="struArea" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Greening area(㎡): </label>
                        <input type="text" name="greeningArea" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>afforested area(㎡): </label>
                        <input type="text" name="greenArea" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Number of classroom seats(individual): </label>
                        <input type="text" name="seatNum" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Number of canteen seats(individual): </label>
                        <input type="text" name="dineNum" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Library area(㎡): </label>
                        <input type="text" name="libArea" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Administrative office area(㎡): </label>
                        <input type="text" name="officeArea" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <input type="submit" class="form-control" value="add to">
                    </div>
                </form>
            </div>
        </div>
    </body>
</html>

  • Adding basic data can be seen from the jsp page that it is a form submission. After filling in the corresponding data, click the "modify" button to forward the request to the back-end server, and the corresponding controller controls the jump
@Controller
@RequestMapping("/rearBaseInfo")
public class RearBaseInfoController {
    //Add data request
    @RequestMapping("/addRearBaseInfo")
    public String addRearBaseInfo(RearBaseInfo rearBaseInfo) {
        rearBaseInfoService.addRearBaseInfo(rearBaseInfo);
        return "redirect:/util/allRearBaseInfo";
    }
}
  • This controller layer method is a little different: first, the parameter list is a reference of the type of realbaseinfo. Because adding data operations will pass back all the attributes of a complete object to the back-end controller. This parameter list automatically encapsulates the added realbaseinfo object; The second is the return value. Most of the previous controllers use the method of request forwarding. The return value directly refers to the assembly path of a view page, and the operation used here is redirection, which is to put the operation result back into a view interface on the premise that the operation has been completed. However, if you directly request forwarding this view page, even if the data is added successfully, there will be no corresponding refresh in the corresponding view, Because the current controller only adds business and does not transfer the corresponding data value to the front-end view, a small partner may refute me: in this controller, use the Model object to return the data to the view and forward the return value using the request; Here, I would like to emphasize that the data in the realbaseinfo object is loaded into the Model object and passed to the view page. The return value uses the request forwarding to jump to the page. Does the controller seem to have written it? Yes, yes, it is:
@Controller
@RequestMapping("/util")
public class AdminUtilController {

    @Autowired
    @Qualifier("rearBaseInfoServiceImpl")
    private RearBaseInfoService rearBaseInfoService;

    @RequestMapping("/allRearBaseInfo")
    public String toRearBaseInfoPage(Model model) {
        List<RearBaseInfo> list = rearBaseInfoService.queryAllRearBaseInfo();
        model.addAttribute("rearBaseInfo", list);
        return "/rearBaseInfo/allRearBaseInfo";
    }
}
  • This controller is the page that will jump when you click the "basic logistics information" button in front. It has been written. Therefore, we can stand on the shoulders of giants. Why do we have to do it again? (common saying: can't mix, never C, hee hee); Look at the above control class. The redirection method used for its return value is to let other controllers work for it. The above controller redirects to the lower controller mapping path, and actually executes the program of the next controller.
  • After calling the redirected controller, return to the logistics basic data display page again. At the same time, the record in the frame is the data we just entered the data addition page. It can also be displayed. It's amazing!
  • The subsequent operations are some operations of adding, deleting, modifying and querying. However, in the later stage, there will be some data analysis, file upload and graphical interface to show the new functions of data. Hey! Let's talk about it later.

6, Summary

`

  • This controller layer method is a little different: first, the parameter list is a reference of the type of realbaseinfo. Because adding data operations will pass back all the attributes of a complete object to the back-end controller. This parameter list automatically encapsulates the added realbaseinfo object; The second is the return value. Most of the previous controllers use the method of request forwarding. The return value directly refers to the assembly path of a view page, and the operation used here is redirection, which is to put the operation result back into a view interface on the premise that the operation has been completed. However, if you directly request forwarding this view page, even if the data is added successfully, there will be no corresponding refresh in the corresponding view, Because the current controller only adds business and does not transfer the corresponding data value to the front-end view, a small partner may refute me: in this controller, use the Model object to return the data to the view and forward the return value using the request; Here, I would like to emphasize that the data in the realbaseinfo object is loaded into the Model object and passed to the view page. The return value uses the request forwarding to jump to the page. Does the controller seem to have written it? Yes, yes, it is:
@Controller
@RequestMapping("/util")
public class AdminUtilController {

    @Autowired
    @Qualifier("rearBaseInfoServiceImpl")
    private RearBaseInfoService rearBaseInfoService;

    @RequestMapping("/allRearBaseInfo")
    public String toRearBaseInfoPage(Model model) {
        List<RearBaseInfo> list = rearBaseInfoService.queryAllRearBaseInfo();
        model.addAttribute("rearBaseInfo", list);
        return "/rearBaseInfo/allRearBaseInfo";
    }
}
  • This controller is the page that will jump when you click the "basic logistics information" button in front. It has been written. Therefore, we can stand on the shoulders of giants. Why do we have to do it again? (common saying: can't mix, never C, hee hee); Look at the above control class. The redirection method used for its return value is to let other controllers work for it. The above controller redirects to the lower controller mapping path, and actually executes the program of the next controller.

  • After calling the redirected controller, return to the logistics basic data display page again. At the same time, the record in the frame is the data we just entered the data addition page. It can also be displayed. It's amazing!

  • The subsequent operations are some operations of adding, deleting, modifying and querying. However, in the later stage, there will be some data analysis, file upload and graphical interface to show the new functions of data. Hey! Let's talk about it later.

6, Summary

  • How to put it? It's easy to build a simple and stupid ssm framework. If you can have a simple one and realize the required functions, why add some content that doesn't belong to our grasp? Finally, I wish you a happy life, smooth work and earn more RMB. I'm a java Xiaobai programming silently!

Tags: Java Spring

Posted by designergav on Thu, 05 May 2022 00:19:07 +0300