Teach you how to integrate SSM to implement a simple CRUD project

Keywords: Java Maven Spring SSM

Project notes

1, Project introduction

This is a simple CRUD(Create Retrieve Update Delete) web page project based on SSM framework. The IDE used is IDEA2021.1.
Due to the time problem, this article will introduce the first two parts. The problems and solutions that are easy to encounter in the project will be given in the following articles. Specific project address: https://gitee.com/qc-sxt/userSystem-SSM

2, Project steps

1. Build database environment

First, create the database required by the project, named db3, which contains two tables: one is the user table, which is used to display user information; One is the administrator table, which is used to record the user name and password of the administrator. Finally, only the administrator can log in to the system to add, delete, modify and query the user's information.

CREATE TABLE IF NOT EXISTS administrator(  -- establish administrator surface
	id INT PRIMARY KEY AUTO_INCREMENT,  -- administrators id,Set as primary key and grow automatically
	username VARCHAR(30),  -- Administrator user name
	PASSWORD VARCHAR(30)  -- Administrator password
);
-- Insert administrator data
INSERT INTO administrator VALUES(NULL,"administrator1","888888");
INSERT INTO administrator VALUES(NULL,"administrator2","888888");

CREATE TABLE IF NOT EXISTS USER(  -- Create user table
	id INT PRIMARY KEY AUTO_INCREMENT,  -- user id,Set as primary key and grow automatically
	NAME VARCHAR(30) NOT NULL,  -- User name, non empty
	gender VARCHAR(10),  -- User gender
	age INT,  -- User age
	address VARCHAR(20),  -- User address
	qq VARCHAR(30),  -- user QQ number
	email VARCHAR(30)  -- User mailbox
);
-- Insert user data
INSERT INTO USER VALUES(NULL,"Zhang San","male",25,"Beijing","123456","123456@qq.com");
INSERT INTO USER VALUES(NULL,"Li Si","female",20,"Shanghai","456789","456789@qq.com");
INSERT INTO USER VALUES(NULL,"Wang Wu","male",28,"Guangzhou","123456","123456@qq.com");
INSERT INTO USER VALUES(NULL,"Zhao Liu","female",23,"Shenzhen","456789","456789@qq.com");

After executing the sql, check whether there is any problem with the table and the data in the table. If there is no problem, the database will be built.

2.dao layer preparation (based on mybatis framework)

(1) In IDEA, create an empty project based on Maven management, named userSystem_SSM. Introduce dependencies in the pom.xml file of the project and set resource filtering (prevent the XML and properties configuration files written later from being found). Remember to refresh Maven after pom.xml is written.

<?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>com.sxt</groupId>
    <artifactId>userSystem_SSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <!--Here is only mybatis Framework, and then integrated spring and springmvc The configuration file will continue to be modified after the framework -->
    
    <dependencies>
        <!--mybatis environment-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--mysql environment-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <!--unit testing  junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--Log output log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <!--Turn on resource filtering-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

(2) Create a new package in the Java Directory: com.sxt.pojo (place ordinary Java object, whose name emphasizes that it is an ordinary Java object), com.sxt.dao(Data Access Object, which is used to access the database), com.sxt.utils (tool package, which contains the tool classes of the whole project).

Create two new Java classes under the pojo package: User (User class) and Administrator (Administrator class). Write their corresponding properties and getter and setter methods against the tables in the database. The constructor is generated according to the requirements of its own sql statement. However, it should be noted that once the constructor with parameters is generated, the default parameterless constructor must be explicitly declared. Code omitted here.

(3) Create three new configuration files under the resources package: database.properties, log4j.properties and mybatis-config.xml, which are used for database configuration, log configuration and mybatis core configuration files respectively.

# Database configuration
driver=com.mysql.jdbc.Driver  # Database driven
url=jdbc:mysql://localhost:3306/db3 # database access url
username=root  # Database user name
password=root  # Database password
# Global log configuration
log4j.rootLogger=DEBUG,console
# MyBatis log configuration
log4j.logger.com.example.dao.UserMapper=TRACE
# Settings related to console output
#log4j.appender.stdout=org.apache.log4j.ConsoleAppender
#log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
#log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

#Settings related to console output
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n

#Settings related to file output
#log4j.appender.file = org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=./log/sxt.log
#log4j.appender.file.MaxFileSize=10mb
#log4j.appender.file.Threshold=DEBUG
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n

#Log output level
#SQL statements will be recorded at the DEBUG log level
#The returned result set is recorded at the TRACE log level
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
<?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>
    <properties resource="database.properties"/>

    <typeAliases>
        <!--Use when entity classes are few-->
        <!--<typeAlias type="pers.sxt.pojo.User" alias="user"/>-->
        <!--Entity classes are used when they are multiple,The default alias is the lowercase initial of the class name-->
        <package name="com.sxt.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <!-- every last mapper.xml All need to be in mybatis Register in the core configuration file! -->
    <mappers>
        <!--Recommended use,The other two configuration methods must ensure mapper Interface and corresponding xml The mapping configuration file is under the same package, and the interface class name and xml File names must be consistent-->
        <mapper resource="com/sxt/dao/UserMapper.xml"/>
        <!--<mapper class="com.example.dao.UserMapper"/>-->
        <!--<package name="com.example.dao"/>-->
    </mappers>
</configuration>

(4) Create a new UserMapper interface and UserMapper.xml mapping file under dao package.

package com.sxt.dao;

import com.sxt.pojo.Administrator;
import com.sxt.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {
    /**
     * Query all user information in the system and return the List collection of user objects
     * @return
     */
    List<User> findUsers();

    /**
     * Query administrator information through user name and password for administrator login
     * @Param It is provided by MyBatis. As the annotation of Dao layer, it is used to pass parameters, so it can correspond to the field name in SQL. Generally, it is best used when 2 = < number of parameters < = 5
     * When there is only one parameter, there is nothing to say. Only one parameter can match a value passed in.
     * When there are multiple parameters, the values passed in cannot be distinguished. In this case, you can consider using Map or @ Param annotation (much more convenient)
     * @param username
     * @param password
     * @return
     */
    Administrator findAdministrator(@Param("username") String username, @Param("password") String password);

    void addUser(User user);  //Add a user

    void deleteUser(int id);  //Delete a user

    void deleteSelectedUsers(@Param("ids")int[] ids);  //Delete selected users in batch

    void updateUser(User user);  //Modify a user information

    User findUserById(int id);  //Query specified user information according to id

}
<?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 Is a required attribute,Used to bind a corresponding Mapper Interface,This name should correspond to the xml Consistent file name-->
<mapper namespace="com.sxt.dao.UserMapper">
    <!--
        id:Is the corresponding namespace Method name in
        resultType:sql The return value of statement execution, and the return result should be written with a fully qualified name
        parameterType:Parameter type
    -->
    <select id="findUsers" resultType="user">
        select * from user
    </select>

    <select id="findAdministrator" resultType="administrator">
        select * from administrator where username = #{username} and password = #{password}
    </select>

    <insert id="addUser" parameterType="user">
        insert into user values (#{id},#{name},#{gender},#{age},#{address},#{qq},#{email})
    </insert>

    <delete id="deleteUser" parameterType="_int">
        delete from user where id = #{id}
    </delete>

    <update id="updateUser" parameterType="user">
        update user set name=#{name},gender=#{gender},age=#{age},address=#{address},qq=#{qq},email=#{email} where id = #{id}
    </update>

    <delete id="deleteSelectedUsers" parameterType="int">
        delete from user where id in
        <!-- dynamic sql Statement value foreach -->
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

    <select id="findUserById" resultType="user">
        select * from user where id = #{id}
    </select>

</mapper>

(5) Write MyBatisUtils tool class under utils Toolkit

package com.sxt.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    //Each MyBatis based application takes an instance of SqlSessionFactory as the core.
    // An instance of SqlSessionFactory can be obtained through SqlSessionFactoryBuilder.
    // SqlSessionFactory builder can build a SqlSessionFactory instance from an XML Configuration file or a pre configured Configuration instance
    static {
        try {
            //In the first step of using mybatis, get the sqlSessionFactory object
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Now that we have SqlSessionFactory, as the name suggests, we can get an instance of SqlSession from it.
    // SqlSession provides all the methods required to execute SQL commands in the database
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

(6) Write a test class to test whether the dao layer code can execute normally and output the correct results

package com.sxt.dao;

import com.sxt.pojo.Administrator;
import com.sxt.pojo.User;
import com.sxt.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class DaoTest {
    private static SqlSession sqlSession;
    private static UserMapper userMapper;

    static {
        sqlSession = MyBatisUtils.getSqlSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void test1(){
        List<User> users = userMapper.findUsers();
        for (User user : users) {
            System.out.println(user);
        }
        sqlSession.close();
    }

    @Test
    public void test2(){
        Administrator administrator = userMapper.findAdministrator("administrator1","888888");
        System.out.println(administrator);
        sqlSession.close();
    }

    @Test
    public void test3(){
        User user = new User(5,"Li Si","male",50,"Xi'an","123456","123456@qq.com");
        userMapper.addUser(user);
        sqlSession.commit();
        test1();
        sqlSession.close();
    }

    @Test
    public void test4(){
        userMapper.deleteUser(6);
        sqlSession.commit();
        test1();
        sqlSession.close();
    }

    @Test
    public void test5(){
        int[] ids = {5,6};
        userMapper.deleteSelectedUsers(ids);
        sqlSession.commit();
        test1();
        sqlSession.close();
    }

    @Test
    public void test6(){
        User user = new User(6,"Zhang San","female",20,"Chengdu","123456","123456@qq.com");
        userMapper.updateUser(user);
        sqlSession.commit();
        test1();
        sqlSession.close();
    }
}

So far, the code of dao layer has been written, and the basic functions of data addition, deletion, modification and query can be realized.

3.service layer preparation (based on spring Framework)

(1) Create a new UserService interface under the service package to implement business operations (call the dao layer to operate the database).

package com.sxt.service;

import com.sxt.pojo.Administrator;
import com.sxt.pojo.User;

import java.util.List;

//You need to implement it and call the dao layer. Method is exactly the same as that in UserMapper
public interface UserService {
    List<User> findUsers();

    Administrator findAdministrator(String username, String password);

    void addUser(User user);

    void deleteUser(int id);

    void deleteSelectedUsers(int[] ids);

    void updateUser(User user);

    User findUserById(int id);
}

(2) Create a new impl package under the service package to store the implementation class of UserService interface. Then, create a new UserServiceImpl class under the UserServiceImpl package and write specific business operations (all call the dao layer interface and call its methods to execute sql statements)

package com.sxt.service.impl;

import com.sxt.dao.UserMapper;
import com.sxt.pojo.Administrator;
import com.sxt.pojo.User;
import com.sxt.service.UserService;
import java.util.List;

public class UserServiceImpl implements UserService {

    //Call the operation of dao layer and set a set interface to facilitate Spring management
    private UserMapper userMapper;
	//The spring container can then inject the userMapper object through attributes
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    public List<User> findUsers() {
        return userMapper.findUsers();
    }

    public Administrator findAdministrator(String username, String password) {
        return userMapper.findAdministrator(username,password);
    }

    public void addUser(User user) {
        userMapper.addUser(user);
    }

    public void deleteUser(int id) {
        userMapper.deleteUser(id);
    }

    public void deleteSelectedUsers(int[] ids) {
        userMapper.deleteSelectedUsers(ids);
    }

    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    public User findUserById(int id) {
        return userMapper.findUserById(id);
    }
}

(3) To integrate MyBatis and Spring, you need to use MyBatis Spring dependency (you can seamlessly integrate MyBatis code into Spring), Spring webmvc dependency (including multiple packages such as Spring beans, Spring context and Spring core, which is very convenient to guide), and Spring JDBC dependency (Spring transaction management). Therefore, modify the pom.xml file, add the following configuration in the dependency, and then refresh Maven:

<!--spring environment-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.0.RELEASE</version>
</dependency>
<!--mybatis and spring Integration package-->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
</dependency>

(4) Write the configuration file of spring integrating mybatis, that is, the Dao layer is managed by spring. Create a new spring-dao.xml file in the resources folder and write the configuration:

Note: here, you must add jdbc. Before each attribute in the database.properties database configuration file

That's it: otherwise, there may be some strange problems. As for the reasons, there are many online, so I won't repeat them here

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db3
jdbc.username=root
jdbc.password=root

spring-dao.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"
       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">

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

    <!--Configure data sources: there are many data sources. You can use third-party or Spring of-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--to configure SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--relation Mybatis-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--If Mapper.xml And Mapper.class Under the same package and with the same name,-->
        <!--spring scanning Mapper.class At the same time, it will automatically scan the with the same name Mapper.xml And assembled to Mapper.class. -->
        <!--If Mapper.xml And Mapper.class If it is not under the same package or has a different name, you must use configuration mapperLocations appoint mapper.xml The location of the.-->
        <!--here spring By identifying mapper.xml Medium <mapper namespace="com.sxt.dao.UserMapper"> namespace To determine the corresponding Mapper.class of-->
        <!--<property name="mapperLocations" value="classpath:com/sxt/dao/*.xml"/>-->
    </bean>

        <!--register sqlSessionTemplate , relation sqlSessionFactory-->
        <!--<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
            <!--Using constructor injection-->
            <!--<constructor-arg index="0" ref="sqlSessionFactory"/>-->
        <!--</bean>-->

    <!-- Configure scan Dao Interface package, dynamic implementation Dao Interface injection into spring In container -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- injection sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- Give the information that needs to be scanned Dao Interface package -->
        <property name="basePackage" value="com.sxt.dao"/>
    </bean>

</beans>

After writing, you need to modify the mybatis-config.xml file to keep only its basic configuration (usually, the basic configuration refers to < Settings > or < typealiases > elements)

mybatis-config.xml after modification:

<?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="LOG4J"/>
    </settings>
    <typeAliases>
        <!--Use when entity classes are few-->
        <!--<typeAlias type="pers.sxt.pojo.User" alias="user"/>-->
        <!--Entity classes are used when they are multiple-->
        <package name="com.sxt.pojo"/>
    </typeAliases>
</configuration>

If MyBatis cannot find the corresponding mapper XML file under the path corresponding to the mapper class, a configuration file is also required. There are two solutions: the first is to manually specify the class path of the XML file in the < mappers > section of the XML configuration file of MyBatis (there is no method before integration); The second is to set the maperlocations property of the factory bean.

(5) Write the spring integration service layer file: spring-service.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
       http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <!--UserServiceImpl Inject into IOC In container-->
    <bean id="userServiceImpl" class="com.sxt.service.impl.UserServiceImpl">
        <property name="userMapper" ref="userMapper"/>
    </bean>

    <!-- Configure transaction manager -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Inject database connection pool -->
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

(6) Write the applicationContext.xml file to import all spring configuration files into this file for easy management.

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

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>

</beans>

(7) Write test code to verify that there is no problem with integration

package com.sxt.service;

import com.sxt.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class ServiceTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        UserService userService = context.getBean("userServiceImpl", UserService.class);

        List<User> users = userService.findUsers();
        for (User user : users) {
            System.out.println(user);
        }

    }
}

So far, the code of the service layer has been written, and the integration of spring and mybat has been successful.

4.controller layer preparation (based on spring MVC framework)

(1) The dependency of servlet and jsp package, JSTL and paging plug-in (used for paging display of queried data) is introduced into pom.xml file.

<?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>com.sxt</groupId>
    <artifactId>userSystem_SSM</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!--mybatis environment-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--mysql environment-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>
        <!--spring environment-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--mybatis and spring Integration package-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <!--servlet and jsp package-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- JSTL -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- JSTL Implementation package -->
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>
        <!--unit testing  junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--Log output log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.7.0</version>
        </dependency>
        <!--Paging plug-in-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.1</version>
        </dependency>
    </dependencies>

    <!--Turn on resource filtering-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

</project>

(2) Write the spring MVC configuration file: spring-controller.xml.

Note: static resource filtering must be configured, otherwise the css, js and other files of the page written later cannot be loaded. The function of interceptor is the same as that of the filter in java web before. It is used to implement the login verification function in the project.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- open SpringMVC Annotation driven -->
    <mvc:annotation-driven/>
    <!-- Static resource filtering-->
    <mvc:default-servlet-handler/>
    <!--Automatic scanning web dependent bean-->
    <context:component-scan base-package="com.sxt.controller"/>

    <!--
    For security reasons, our JSP The files will be placed in WEB-INF Next,
    But we can't access it directly from the outside/WEB-INF/Resources in the directory, right,
    It can only be accessed in the form of forwarding through the internal server, InternalResourceViewResolver The bottom layer helps us solve this problem through forwarding!
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--About interceptor configuration-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--/** Include paths and their sub paths-->
            <mvc:mapping path="/**"/>
            <!--bean The interceptor is configured-->
            <bean class="com.sxt.interceptor.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

(3) Modify the general spring configuration file: applicationContext.xml, and import spring-controller.xml to facilitate the three-tier configuration file management.

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

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="classpath:spring-controller.xml"/>

</beans>

(4) Modifying the web.xml file is mainly to configure the dispatcher servlet.

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

    <!--The static resource filtering configuration of the interceptor. Although it is said on the Internet that the interceptor does not intercept static resources, if it is not configured, the static resources cannot be loaded-->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/img/*</url-pattern>
        <url-pattern>/js/*</url-pattern>
        <url-pattern>/css/*</url-pattern>
    </servlet-mapping>

    <!--register DispatcherServlet-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--Associate a springmvc Configuration file for:[servlet-name]-servlet.xml-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!--Startup level-1-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--/ Match all requests( barring.jsp)-->
    <!--/* Match all requests( include.jsp)-->
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--encodingFilter-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>

    <!--Session Expiration time 30 minutes-->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

(5) Create a new package: con.sxt.controller, which stores the code of all view layers. Create several Java classes under the package:

  • Add.java (used to jump to the add user interface)
package com.sxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("userSystem")
public class Add {

    @RequestMapping("/add")
    public String add(){
        return "add";
    }
}
  • AddUser.java (used to add users)
package com.sxt.controller;

import com.sxt.pojo.User;
import com.sxt.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Controller
@RequestMapping("userSystem")
public class AddUser {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("addUser")
    public String addUser(HttpServletRequest request) throws UnsupportedEncodingException {
        //Set encoding
        request.setCharacterEncoding("utf-8");
        //Get parameters
        Map<String, String[]> map = request.getParameterMap();
        //Encapsulated object
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        userService.addUser(user);

        return "redirect:list";
    }
}
  • CheckCode.java (used to generate verification code)
package com.sxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
@RequestMapping("userSystem")
public class CheckCode {
    /**
     * Generate 4-bit random string as verification code
     * @return
     */
    private String generateCheckCode(){
        String baseCode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        int size = baseCode.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //Generate random values from 0 to size-1
            int index = r.nextInt(size);
            //Gets the character with index index in the baseCode string
            char c = baseCode.charAt(index);
            //Put c into StringBuffer
            sb.append(c);
        }
        return sb.toString();
    }
    @RequestMapping("/code")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //Create a picture with a length of 80 and a width of 30 in memory, with a default black background; Parameter 1: length; Parameter 2: width; Parameter 3: color
        int width = 80;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);

        //Get the brush, set the brush color to gray, and fill the picture
        Graphics gp = image.getGraphics();
        gp.setColor(Color.gray);
        gp.fillRect(0,0,width,height);


        //Generate 4 random verification codes and put them into HttpSession
        String checkCode_server = generateCheckCode();
        //Put the verification code into HttpSession
        request.getSession().setAttribute("checkCode_server",checkCode_server);

        //Set the brush color to yellow, set the font size to 24, and write the verification code to the picture
        gp.setColor(Color.YELLOW);
        gp.setFont(new Font("Blackbody",Font.BOLD,24));
        gp.drawString(checkCode_server,15,25);

        //Output the picture in memory to the browser parameter 1: picture object; Parameter 2: image format, such as PNG,JPG,GIF; Parameter 3: where is the picture output
        ImageIO.write(image,"PNG",response.getOutputStream());
    }
}
  • DeleteSeletedUsers.java (used to delete selected users in batch)
package com.sxt.controller;

import com.sxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("userSystem")
public class DeleteSelectedUsers {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/deleteSelectedUsers")
    public String deleteUsers(int[] userBox){

        userService.deleteSelectedUsers(userBox);

        return "redirect:list";
    }
}
  • DeleteUser.java (used to delete a user)
package com.sxt.controller;

import com.sxt.pojo.User;
import com.sxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("userSystem")
public class DeleteUser {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/deleteUser")
    public String list(int id){
        userService.deleteUser(id);

        return "redirect:list";
    }
}
  • FindUserById.java (used to find a user by specific user id)
package com.sxt.controller;

import com.sxt.pojo.User;
import com.sxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("userSystem")
public class FindUserById {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/findUserById")
    public String list(Model model,int id){
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "update";
    }
}
  • FindUsers.java (used to query the information of all users)
package com.sxt.controller;

import com.github.pagehelper.PageHelper;
import com.sxt.pojo.User;
import com.sxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/userSystem")
public class FindUsers {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/list")
    public String list(Model model){
        PageHelper.startPage(1, 5);
        List<User> users = userService.findUsers();
        model.addAttribute("list",users);
        return "list";
    }

}
  • Login.java (used to realize login function)
package com.sxt.controller;

import com.sxt.pojo.Administrator;
import com.sxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/userSystem")
public class Login {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/login")
    public String verify(String username,String password,Model model,HttpServletRequest request) throws UnsupportedEncodingException {
        //Set encoding
        request.setCharacterEncoding("utf-8");
        //Obtain the verification code filled in by the user
        String checkCode = request.getParameter("checkCode");
        //Verification code verification
        HttpSession session = request.getSession();
        String checkCode_server = (String) session.getAttribute("checkCode_server");
        if(checkCode!=null){
            if(!checkCode_server.equalsIgnoreCase(checkCode)){ //The verification code generated by the server is not equal to the verification code filled in by the user
                //Incorrect verification code, prompt message
                model.addAttribute("msg","Verification code error");
                session.removeAttribute("checkCode_server");//Ensure that the verification code is one-time
                return "login";
            }
        }
        Administrator administrator = userService.findAdministrator(username, password);
        if(administrator!=null){
            String username1 = administrator.getUsername();
            session.setAttribute("administrator",administrator);
            model.addAttribute("msg","Login succeeded, welcome"+username1);
            return "index";
        }else{
            model.addAttribute("msg","Wrong user name or password");
            return "login";
        }

    }

}
  • SignOut.java (used for exit function)
package com.sxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("userSystem")
public class SignOut {

    @RequestMapping("/signOut")
    public void signOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("administrator");
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }
}
  • UpdateUser (used to modify user information)
package com.sxt.controller;

import com.sxt.pojo.User;
import com.sxt.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@Controller
@RequestMapping("userSystem")
public class UpdateUser {
    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/updateUser")
    public String updateUser(HttpServletRequest request) throws UnsupportedEncodingException {
        //Set encoding
        request.setCharacterEncoding("utf-8");
        //Get parameters
        Map<String, String[]> map = request.getParameterMap();
        //Encapsulated object
        User user = new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        userService.updateUser(user);

        return "redirect:list";
    }
}

(6) con.sxt.controller, which stores the interceptor code. Create a new LoginInterceptor.java class under the package to realize login verification:

package com.sxt.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    //Execute before the method of request processing
    //If true is returned, execute the next interceptor
    //If false is returned, the next interceptor is not executed
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        //Get resource request path
        String uri = request.getRequestURI();
        //Determine whether the login related resource path is included
        if (uri.contains("/login")||uri.contains("/code")) {
            //Yes, the user just wants to log in. Release
            return true;
        } else {
            //Not included. You need to verify whether the user logs in
            //Get user from session
            Object administrator = session.getAttribute("administrator");
            if (administrator != null) {
                //Logged in and released
                return true;
            } else {
                //Not logged in. Jump to login page
                request.setAttribute("msg", "You have not logged in, please log in first");
                request.getRequestDispatcher("/login.jsp").forward(request,response);
                return false;
            }
        }
    }
}

(7) Create new folders in the webapp Directory: css (storing css library code), js (storing js library code), img (storing the background picture of your web page).

Download the bootstrap code: bootstrap.css and bootstrap-theme.css on the Internet and put them into the CSS folder and bootstrap.js into the JS folder.

Download the jQuery Code: jquery-2.1.0.min.js on the Internet and put it in the JS folder.

(8) Write the page.

Create new index.jsp and login.jsp files in webapp directory and write corresponding codes respectively

  • index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>User information management system</title>
    <style>
        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
      div{
        margin-top: 20%;
      }

      a{
        text-decoration: none;
        font-size: 35px;
          color: purple;
      }
    </style>
</head>
<%--stay WEB-INF All pages or resources under can only be accessed through controller perhaps servlet Visit--%>
<body>
<div align="center">
    <h1 style="text-align: center; color: #5bc0de "> welcome to the user information management system</h1>
    <hr color="orange"/>
    First, please<a href="${pageContext.request.contextPath}/login.jsp" >
            Sign in
        </a>
</div>
</body>



</html>
  • login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>User information management system</title>

    <!-- 1. Import CSS Global style for -->
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
    </style>

    <script>
        function refreshCode(){
            //Get verification code picture object
            var codeImg = document.getElementById("codeImg");
            //Set its src attribute and add time stamp
            codeImg.src = "${pageContext.request.contextPath}/userSystem/code?time="+new Date().getTime();
        }
    </script>
</head>
<body>

<div class="container" style="width: 400px;margin-top: 200px">
    <h2 style="color: red;text-align: center;">Administrator login</h2>
    <form action="${pageContext.request.contextPath}/userSystem/login" method="post">
        <!-- Put labels and controls in a class .form-group of <div> Yes. This is necessary to obtain the best spacing.-->
        <!-- To all text elements <input>,<textarea> and <select> add to class ="form-control" -->
        <div class="form-group">
            <!-- for id	regulations label Which form element to bind to.-->
            <label for="username">user name:</label>
            <input type="text" name="username" class="form-control" id="username" placeholder="enter one user name" required/>
        </div>

        <div class="form-group">
            <label for="password">password:</label>
            <input type="password" name="password" class="form-control" id="password" placeholder="Please input a password" required/>
        </div>

        <div class="form-inline">
            <label for="checkCode">Verification Code:</label>
            <input type="text" name="checkCode" class="form-control" id="checkCode" placeholder="Please enter the verification code" required/>
            <a href="javascript:refreshCode();" >
                <img alt="Verification Code" src="${pageContext.request.contextPath}/userSystem/code" id="codeImg" title="Can't see clearly. Change one"/>
            </a>
        </div>
        <hr/>
        <div class="form-group" style="text-align: center">
            <input class="btn-primary" type="submit" value="Sign in">
        </div>

    </form>

    <!-- Error message box -->
    <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" >
            <span>&times;</span>
        </button>
        <strong>${msg}</strong>
    </div>
</div>
</body>
</html>

Create a new JSP folder in the WEB-INF directory of webapp and write page code that you don't want to be accessed directly. They are add.jsp, index.jsp, list.jsp, login.jsp and update.jsp respectively

  • add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <!-- Specify character set -->
    <meta charset="utf-8">
    <!-- use Edge The latest browser rendering -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: the web page can be automatically adapted according to the set width. A container is virtual inside the browser, and the width of the container is the same as that of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Above 3 meta label*must*Put it first, anything else*must*Follow! -->
    <title>User information management system</title>

    <!-- 1. Import CSS Global style for -->
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery Import, 1 is recommended.9 Version above -->
    <script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
    <!-- 3. Import bootstrap of js file -->
    <script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>

    <style>
        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-size: 100% 100%;
            background-repeat: no-repeat;
        }
        .container{
            width: 40%;
        }
    </style>
</head>

<body>
<div class="container">
    <h3 style="text-align: center;color: orangered">Add contact page</h3>
    <form action="${pageContext.request.contextPath}/userSystem/addUser" method="post">
        <div class="form-group">
            <label for="name">full name:</label>
            <input type="text" class="form-control" id="name" name="name" placeholder="Please enter your name" required/>
        </div>

        <div class="form-group">
            <label>Gender:</label>
            <label>
                <input type="radio" name="gender" value="male" checked="checked"/>
            </label>male
            <label>
                <input type="radio" name="gender" value="female"/>
            </label>female
        </div>

        <div class="form-group">
            <label for="age">Age:</label>
            <input type="text" class="form-control" id="age" name="age" placeholder="Please enter age" required/>
        </div>

        <div class="form-group">
            <label for="address">Native place:</label>
            <select name="address" class="form-control" id="address">
                <option value="Shanghai">Shanghai</option>
                <option value="Beijing">Beijing</option>
                <option value="Shenzhen">Shenzhen</option>
                <option value="Guangzhou">Guangzhou</option>
            </select>
        </div>

        <div class="form-group">
            <label for="qq">QQ: </label>
            <input type="text" class="form-control" id="qq" name="qq" placeholder="Please enter QQ number" required/>
        </div>

        <div class="form-group">
            <label for="email">Email: </label>
            <input type="text" class="form-control" id="email" name="email" placeholder="Please enter email address" required/>
        </div>

        <div class="form-group" style="text-align: center">
            <input class="btn btn-primary" type="submit" value="Submit" />
            <input class="btn btn-danger" type="reset" value="Reset" />
            <input class="btn btn-default" type="button" value="return"
           οnclick="window.location.href='${pageContext.request.contextPath}/userSystem/list'"/>
        </div>
    </form>
</div>
</body>


</html>
  • index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>User information management system</title>
    <style>
        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
      div{
        margin-top: 20%;
      }

      a{
        text-decoration: none;
        font-size: 35px;
          color: purple;
      }
    </style>
</head>


<body>
<a href="${pageContext.request.contextPath}/userSystem/signOut" style="color: black">sign out
</a>
<div align="center">
    <span>${msg}</span>
    <h1 style="text-align: center; color: #5bc0de "> welcome to the user information management system</h1>
    <hr color="orange"/>
    <a href="${pageContext.request.contextPath}/userSystem/list" >
            Query all user information
    </a>
</div>
</body>



</html>
  • list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <!-- Specify character set -->
    <meta charset="utf-8">
    <!-- use Edge The latest browser rendering -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- viewport Viewport: the web page can be automatically adapted according to the set width. A container is virtual inside the browser, and the width of the container is the same as that of the device.
    width: The default width is the same as the width of the device
    initial-scale: The initial zoom ratio is 1:1 -->
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Above 3 meta label*must*Put it first, anything else*must*Follow! -->
    <title>User information management system</title>

    <!-- 1. Import CSS Global style for -->
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <!-- 2. jQuery Import, 1 is recommended.9 Version above -->
    <script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
    <!-- 3. Import bootstrap of js file -->
    <script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>

    <style type="text/css">
        td, th {
            text-align: center;
        }

        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
    </style>

    <script>
        function deleteUser(id){
            //User safety tips
            if(confirm("Are you sure you want to delete?")){
                //Access path
                location.href="${pageContext.request.contextPath}/userSystem/deleteUser?id="+id;
            }
        }
        window.onload = function (){
            //Add a click event to the delete selected button
            document.getElementById("delSelected").onclick = function(){
                var flag = false;
                //Determine whether there is a selected item
                var cbs = document.getElementsByName("userBox");
                for (var i = 0; i < cbs.length; i++) {
                    if(cbs[i].checked){
                        //One entry is selected
                        flag = true;
                        break;
                    }
                }
                if(flag){//There are entries selected
                    if(confirm("Are you sure you want to delete the selected entry?")){
                        //Form submission
                        document.getElementById("form").submit();
                    }
                }
            }
            //Get the first general selection box (implementation of select all and deselect all function)
            document.getElementById("generalBox").onclick = function(){
                //Gets all the selection boxes in the lower list
                var boxes = document.getElementsByName("userBox");
                //ergodic
                for (var i = 0; i < boxes.length; i++) {
                    //4. Set the checked status of these cbs[i] = firstCb.checked
                    boxes[i].checked = this.checked;
                }
            }
        }
    </script>
</head>
<body>
<div class="container">
    <h3 style="text-align: center;font-size: 30px;color: orange">User information list</h3>
    <div style="float: left;">
        <form class="form-inline" action="${pageContext.request.contextPath}" method="post">
            <div class="form-group">
                <label for="queryName">full name</label>
                <input type="text" name="name" class="form-control" id="queryName">
            </div>
            <div class="form-group">
                <label for="queryAddress">Native place</label>
                <input type="text" name="address" class="form-control" id="queryAddress">
            </div>
            <div class="form-group">
                <label for="queryEmail">mailbox</label>
                <input type="text" name="email" class="form-control" id="queryEmail">
            </div>
            <button type="submit" class="btn btn-default">query</button>
        </form>
    </div>

    <div style="float: right;">
        <a class="btn btn-primary" href="${pageContext.request.contextPath}/userSystem/add">Add a Contact </a>
        <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">Delete selected</a>
    </div>

    <form id="form" action="${pageContext.request.contextPath}/userSystem/deleteSelectedUsers" method="post">
        <table border="1" class="table table-bordered table-hover">
            <tr class="success">
                <th><input type="checkbox" id="generalBox"></th>
                <th>number</th>
                <th>full name</th>
                <th>Gender</th>
                <th>Age</th>
                <th>Native place</th>
                <th>QQ</th>
                <th>mailbox</th>
                <th>operation</th>
            </tr>

            <%--items:Container object,varStatus:Loop state object,attribute count Indicates the number of cycles--%>
            <c:forEach items="${list}" var="user" varStatus="s">
                <tr>
                    <td><input type="checkbox" name="userBox" value="${user.id}"></td>
                        <%--<td>${s.count+(pb.rows)*(pb.currentPage-1)}</td>--%>
                    <td>${user.id}</td>
                    <td>${user.name}</td>
                    <td>${user.gender}</td>
                    <td>${user.age}</td>
                    <td>${user.address}</td>
                    <td>${user.qq}</td>
                    <td>${user.email}</td>
                    <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/userSystem/findUserById?id=${user.id}">modify</a>&nbsp;
                        <a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id})" id="delete">delete</a></td>
                </tr>

            </c:forEach>
        </table>
    </form>

    
</div>

</body>
</html>

  • login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>User information management system</title>

    <!-- 1. Import CSS Global style for -->
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">

    <style>
        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
    </style>

    <script>
        function refreshCode(){
            //Get verification code picture object
            var codeImg = document.getElementById("codeImg");
            //Set its src attribute and add time stamp
            codeImg.src = "${pageContext.request.contextPath}/userSystem/code?time="+new Date().getTime();
        }
    </script>
</head>
<body>
<div class="container" style="width: 400px;margin-top: 200px">
    <h2 style="color: red;text-align: center;">Administrator login</h2>
    <form action="${pageContext.request.contextPath}/userSystem/login" method="post">
        <!-- Put labels and controls in a class .form-group of <div> Yes. This is necessary to obtain the best spacing.-->
        <!-- To all text elements <input>,<textarea> and <select> add to class ="form-control" -->
        <div class="form-group">
            <!-- for id	regulations label Which form element to bind to.-->
            <label for="username">user name:</label>
            <input type="text" name="username" class="form-control" id="username" placeholder="enter one user name" required/>
        </div>

        <div class="form-group">
            <label for="password">password:</label>
            <input type="password" name="password" class="form-control" id="password" placeholder="Please input a password" required/>
        </div>

        <div class="form-inline">
            <label for="checkCode">Verification Code:</label>
            <input type="text" name="checkCode" class="form-control" id="checkCode" placeholder="Please enter the verification code" required/>
            <a href="javascript:refreshCode();" >
                <img alt="Verification Code" src="${pageContext.request.contextPath}/userSystem/code" id="codeImg" title="Can't see clearly. Change one"/>
            </a>
        </div>
        <hr/>
        <div class="form-group" style="text-align: center">
            <input class="btn-primary" type="submit" value="Sign in">
        </div>

    </form>

    <!-- Error message box -->
    <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" >
            <span>&times;</span>
        </button>
        <strong>${msg}</strong>
    </div>
</div>
</body>
</html>
  • update.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html lang="zh-CN">
<head>
    <!-- Specify character set -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>User information management system</title>

    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/js/jquery-2.1.0.min.js"></script>
    <script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
    <style>
        body{
            background-image: url("${pageContext.request.contextPath}/img/bk.jpg");
            background-repeat: no-repeat;
            background-size: 100% 100%;
        }
        .container{
            width: 40%;
        }
    </style>
</head>

<body>
    <div class="container">
    <h3 style="text-align: center;color: red">Modify user information</h3>
        <form action="${pageContext.request.contextPath}/userSystem/updateUser" method="post">
            <!--  Hidden domain submission id-->
            <input type="hidden" name="id" value="${user.id}">

          <div class="form-group">
            <label for="name">full name:</label>
            <input type="text" class="form-control" id="name" name="name"  value="${user.name}" readonly="readonly" placeholder="The name cannot be changed" />
          </div>

          <div class="form-group">
            <label>Gender:</label>
              <c:if test="${user.gender == 'male'}">
                  <label>
                      <input type="radio" name="gender" value="male" checked />
                  </label>male
                  <label>
                      <input type="radio" name="gender" value="female"  />
                  </label>female
              </c:if>

              <c:if test="${user.gender == 'female'}">
                  <label>
                      <input type="radio" name="gender" value="male"  />
                  </label>male
                  <label>
                      <input type="radio" name="gender" value="female" checked  />
                  </label>female
              </c:if>
          </div>

          <div class="form-group">
            <label for="age">Age:</label>
            <input type="text" class="form-control" value="${user.age}" id="age"  name="age" placeholder="Please enter age" />
          </div>

          <div class="form-group">
            <label for="address">Native place:</label>
             <select name="address" id="address" class="form-control" >
                 <c:if test="${user.address == 'Shanghai'}">
                    <option value="Shanghai" selected>Shanghai</option>
                    <option value="Beijing">Beijing</option>
                    <option value="Shenzhen">Shenzhen</option>
                    <option value="Guangzhou">Guangzhou</option>
                 </c:if>

                 <c:if test="${user.address == 'Beijing'}">
                     <option value="Shanghai">Shanghai</option>
                     <option value="Beijing" selected>Beijing</option>
                     <option value="Shenzhen">Shenzhen</option>
                     <option value="Guangzhou">Guangzhou</option>
                 </c:if>

                 <c:if test="${user.address == 'Shenzhen'}">
                     <option value="Shanghai">Shanghai</option>
                     <option value="Beijing">Beijing</option>
                     <option value="Shenzhen" selected>Shenzhen</option>
                     <option value="Guangzhou">Guangzhou</option>
                 </c:if>

                 <c:if test="${user.address == 'Guangzhou'}">
                     <option value="Shanghai">Shanghai</option>
                     <option value="Beijing">Beijing</option>
                     <option value="Shenzhen">Shenzhen</option>
                     <option value="Guangzhou"  selected>Guangzhou</option>
                 </c:if>
            </select>
          </div>

          <div class="form-group">
            <label for="qq">QQ: </label>
            <input type="text" id="qq" class="form-control" value="${user.qq}" name="qq" placeholder="Please enter QQ number"/>
          </div>

          <div class="form-group">
            <label for="email">Email: </label>
            <input type="text" id="email" class="form-control" value="${user.email}" name="email" placeholder="Please enter email address"/>
          </div>

          <div class="form-group" style="text-align: center">
            <input class="btn btn-primary" type="submit" value="Submit" />
            <input class="btn btn-danger" type="reset" value="Reset" />
            <input class="btn btn-default" type="button" value="return"
            οnclick="window.location.href='${pageContext.request.contextPath}/userSystem/list'"/>
          </div>
        </form>
    </div>
</body>
</html>

So far, the SSM integration has been completed, and the specific business logic code and front-end display code have been written. The rest is tested in the browser.

5. Start the server, deploy the project and test

The steps here are the same as those of all previous web projects. I won't repeat them here. Just test them according to your habits.

Posted by bradcis on Sun, 05 Sep 2021 13:41:59 -0700