[Ji Li 01 group No. 08] SSM framework integration

Posted by desmi on Sun, 27 Feb 2022 04:50:24 +0100

Python wechat ordering applet course video

https://edu.csdn.net/course/detail/36074

Python actual combat quantitative transaction financial management system

https://edu.csdn.net/course/detail/35475

[Ji Li 01 group No. 08] SSM framework integration

Database preparation

This course uses MySQL database. Start MySQL first:

sudo service mysql start

Then enter the following command under the terminal to enter the MySQL database (- u represents the user name, for example, root here, - p represents the password, which is omitted if there is no password):

mysql -u root

For the convenience of the experiment, we create a new database here and name it ssm for the experiment.

create database ssm;

Create the table user under the database ssm. The code is as follows:

use ssm;
create table user(
    id int primary key auto\_increment,
    username varchar(20),
    password varchar(20),
    sex varchar(10),
    age int
);

Let's first insert a test data into the user table:

insert into user(username,password,sex,age) value('shiyanlou','123456','male',22);

New project

First open the WEB IDE, select File - > open new terminal, and enter in the terminal:

mvn archetype:generate -DgroupId=com.shiyanlou -DartifactId=SSMTest -DarchetypeArtifactId=maven-archetype-webapp

Parameter Description:

  • Group Id: the organization of the project, which is also the directory structure of the package. Generally, it is the reverse order of domain names, such as com shiyanlou;

  • Atifact Id: the actual name of the project, such as SSMTest;

  • archetype Artifact Id: name of maven skeleton used

After entering the command, maven will prompt us to enter the version number. Here you can directly define the version number or press enter. Then maven will prompt the basic information of the current project to be created, enter y, press enter to confirm, and then create the java directory in the src/main / directory.

Create a new package for each layer under src/main/java, as shown in the figure:

  • Under model is a series of POJO s, namely various entity classes

  • Mapper is equivalent to DAO layer. Since MyBatis is used here, it is called mapper, which includes mapper interface and mapper configuration file. CRUD operation is completed through the mapping of SQL statements

  • Service is composed of a series of business logic objects, which place various service interfaces

  • service.impl is the concrete implementation of service

  • The controller consists of a series of controllers that process user requests and respond

Next, add dependent packages, such as spring and mybatis. Open POM XML, add the following

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.0modelVersion>

 <groupId>com.shiyanlougroupId>
 <artifactId>SSMTestartifactId>
 <version>1.0-SNAPSHOTversion>
 <packaging>warpackaging>

 <properties>
 <jdbc.driver.version>5.1.47jdbc.driver.version>
 <mybatis.version>3.3.0mybatis.version>
 <mybatis-spring.version>1.2.2mybatis-spring.version>
 <spring.version>5.1.1.RELEASEspring.version>
 <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
 properties>

 <dependencies>
 <dependency>
 <groupId>junitgroupId>
 <artifactId>junitartifactId>
 <version>4.12version>
 <scope>testscope>
 dependency>
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-testartifactId>
 <version>${spring.version}version>
 <scope>testscope>
 dependency>

 
 <dependency>
 <groupId>commons-logginggroupId>
 <artifactId>commons-loggingartifactId>
 <version>1.1.3version>
 dependency>
 <dependency>
 <groupId>commons-collectionsgroupId>
 <artifactId>commons-collectionsartifactId>
 <version>3.2.1version>
 dependency>
 <dependency>
 <groupId>commons-iogroupId>
 <artifactId>commons-ioartifactId>
 <version>2.4version>
 dependency>
 <dependency>
 <groupId>commons-langgroupId>
 <artifactId>commons-langartifactId>
 <version>2.6version>
 dependency>
 
 <dependency>
 <groupId>org.mybatisgroupId>
 <artifactId>mybatisartifactId>
 <version>${mybatis.version}version>
 dependency>
 <dependency>
 <groupId>org.mybatisgroupId>
 <artifactId>mybatis-springartifactId>
 <version>${mybatis-spring.version}version>
 dependency>
 <dependency>
 <groupId>mysqlgroupId>
 <artifactId>mysql-connector-javaartifactId>
 <version>${jdbc.driver.version}version>
 <scope>runtimescope>
 dependency>
 
 <dependency>
 <groupId>org.slf4jgroupId>
 <artifactId>slf4j-apiartifactId>
 <version>1.7.7version>
 dependency>
 <dependency>
 <groupId>org.slf4jgroupId>
 <artifactId>slf4j-log4j12artifactId>
 <version>1.7.7version>
 <exclusions>
 <exclusion>
 <artifactId>log4jartifactId>
 <groupId>log4jgroupId>
 exclusion>
 exclusions>
 dependency>
 <dependency>
 <groupId>log4jgroupId>
 <artifactId>log4jartifactId>
 <version>1.2.16version>
 dependency>

 
 <dependency>
 <groupId>org.aspectjgroupId>
 <artifactId>aspectjrtartifactId>
 <version>1.7.4version>
 dependency>
 <dependency>
 <groupId>org.aspectjgroupId>
 <artifactId>aspectjweaverartifactId>
 <version>1.7.4version>
 dependency>

 
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-coreartifactId>
 <version>${spring.version}version>
 dependency>
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-beansartifactId>
 <version>${spring.version}version>
 dependency>
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-context-supportartifactId>
 <version>${spring.version}version>
 dependency>
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-jdbcartifactId>
 <version>${spring.version}version>
 dependency>
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-txartifactId>
 <version>${spring.version}version>
 dependency>
 <dependency>
 <groupId>org.springframeworkgroupId>
 <artifactId>spring-webmvcartifactId>
 <version>${spring.version}version>
 dependency>

 <dependency>
 <groupId>javax.servletgroupId>
 <artifactId>javax.servlet-apiartifactId>
 <version>3.1.0version>
 <scope>providedscope>
 dependency>
 <dependency>
 <groupId>javax.servlet.jspgroupId>
 <artifactId>jsp-apiartifactId>
 <version>2.2version>
 dependency>
 <dependency>
 <groupId>javax.servletgroupId>
 <artifactId>jstlartifactId>
 <version>1.2version>
 dependency>
 dependencies>
 <build>
 <plugins>
 <plugin>
 
 <groupId>org.eclipse.jettygroupId>
 <artifactId>jetty-maven-pluginartifactId>
 <version>9.4.12.v20180830version>
 <configuration>
 <scanIntervalSeconds>10scanIntervalSeconds>
 <webApp>
 <contextPath>/contextPath>
 webApp>
 configuration>
 plugin>
 plugins>
 build>
project>

model layer entity class User

At package com shiyanlou. Create a new user class under model Java, a user has five attributes: id, username, password, sex and age. The code is as follows:

package com.shiyanlou.model;

public class User {
    private Integer id;       // User id
    private String username;  // user name
    private String password;  // password
    private String sex;       // Gender
    private Integer age;      // Age

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    // The toString method is rewritten to facilitate later testing
    public String toString() {
        return "id:" + id + ",username:" + username + ",password:" + password
                + ",sex:" + sex + ",age:" + age;

    }
}

mapper(dao) layer implementation

At package com shiyanlou. Create a usermapper under mapper java

The code of UserMapper interface is as follows:

package com.shiyanlou.mapper;

import com.shiyanlou.model.User;

import java.util.List;

public interface UserMapper {

    /**
 * User login query
 *
 * @param user
 * @return User
 **/
    User selectLogin(User user);

    /**
 * Query all users
 *
 * @return List
 **/
    List<User> selectAllUser();

    /**
 * New user
 *
 * @param user
 **/
    void addUser(User user);

    /**
 * Update user
 *
 * @param user
 **/
    void updateUser(User user);

    /**
 * delete user
 *
 * @param id
 **/
    void deleteUser(Integer id);
}

Next, create a mappers folder under src/main/resources, and create usermapper xml,UserMapper.xml is configured as follows:

xml version="1.0" encoding="UTF-8"?
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.shiyanlou.mapper.UserMapper">
 
 <resultMap type="User" id="userResultMap">
 <id property="id" column="id"/>
 <result property="username" column="username"/>
 <result property="password" column="password"/>
 <result property="sex" column="sex"/>
 <result property="age" column="age"/>
 resultMap>
 
 <select id="selectLogin" parameterType="User" resultMap="userResultMap">
 select *
 from user
 where username = #{username}
 and password = #{password}
 select>
 
 <select id="selectAllUser" resultMap="userResultMap">
 select *
 from user
 select>
 
 <insert id="addUser" useGeneratedKeys="true" keyProperty="id">
 insert into user (username, password, sex, age)
 values (#{username}, #{password}, #{sex}, #{age})
 insert>
 
 <update id="updateUser" parameterType="User">
 update user
 set username = #{username},
 password = #{password},
 sex = #{sex},
 age = #{age}
 where id = #{id}
 update>
 
 <delete id="deleteUser" parameterType="int">
 delete
 from user
 where id = #{id}
 delete>

mapper>

Here, the code of DAO layer is finished. Next, let's implement the code of Service layer.

Note: MyBatis configuration files are processed during integration.

service layer implementation

Service layer interface

At package com shiyanlou. Create a userservice under service Java interface file, add the following code:

package com.shiyanlou.service;

import com.shiyanlou.model.User;

import java.util.List;

public interface UserService {

    /**
 * User login
 *
 * @param user
 * @return The User object is returned when login succeeds, and null is returned when login fails
 **/
    User login(User user);

    /**
 * Query all users
 *
 * @return list of all User objects queried
 **/
    List<User> selectAllUser();

    /**
 * New user
 *
 * @param user
 **/
    void addUser(User user);

    /**
 * Update user
 *
 * @param user
 **/
    void updateUser(User user);

    /**
 * delete user
 *
 * @param id(User id)
 **/
    void deleteUser(Integer id);
}

Service layer interface implementation class

At package com shiyanlou. service. Under impl, create a class userserviceimpl Java, which is used to implement the methods in the UserService interface. Add the following code:

package com.shiyanlou.service.impl;

import com.shiyanlou.mapper.UserMapper;
import com.shiyanlou.model.User;
import com.shiyanlou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Annotate the current class as a Spring bean
 *
 * @author shiyanlou
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    /**
 * Auto inject UserMapper
 **/
    @Autowired
    public UserMapper userMapper;

    // The following is the specific implementation of all methods of UserService interface
    public User login(User user) {
        return userMapper.selectLogin(user);
    }

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

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

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

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

Here, the code of the Service layer is finished. Next, we will integrate Spring and MyBatis.

Spring and MyBatis integration

MyBatis profile

Create a new MyBatis configuration file MyBatis config. In the directory src/main/resources XML, the code is as follows:

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>
 
 <typeAliases>
 <package name="com.shiyanlou.model" />
 typeAliases>
 
 <mappers>
 <package name="com.shiyanlou.mapper" />
 mappers>
configuration>

Note: here, we do not configure the running environment and data source of MyBatis, because we want to give these to Spring for configuration management.

applicationContext.xml

Create a new file ApplicationContext. In the directory src/main/resources XML, which is used to complete the integration of Spring and MyBatis, mainly including automatic scanning, automatic injection, configuration database, etc. the contents are as follows:

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

    
    <context:component-scan base-package="com.shiyanlou" />
    
    <bean id="dataSource"
 class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/ssm" />
        <property name="username" value="root" />
        <property name="password" value="" />
    bean>
 
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <property name="dataSource" ref="dataSource"/>
 <property name="configLocation" value="classpath:mybatis-config.xml" />
 <property name="mapperLocations" value="classpath*:mappers/**"/>
 bean>

 
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
 <property name="basePackage" value="com.shiyanlou.mapper"/>
 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
 bean>
 
 <bean id="txManager"
 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <property name="dataSource" ref="dataSource"/>
 bean>
 
 <tx:annotation-driven transaction-manager="txManager" />

beans>

Here, we write the data source configuration information in ApplicationContext In XML, you can also create a new JDBC Properties file, and then import it.

log4j.properties configuration log

Create a new log file log4j. In the directory src/main/resources Properties, add the following contents:

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# 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

Here, the integration of Spring and MyBatis is completed. Let's test whether the integration is successful through a test class.

Spring and MyBatis integration test

Create a new test class SpringMybatisTest under the directory src/test/java, and add the following code:

import com.shiyanlou.model.User;
import com.shiyanlou.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Configure the integration of spring and junit. When junit starts, load the spring IOC container spring test, junit
 **/
@RunWith(SpringJUnit4ClassRunner.class)
// Tell JUnit the spring configuration file
@ContextConfiguration({"classpath:applicationContext.xml"})
public class SpringMybatisTest {
    @Autowired
    private UserService userService;

/* @Autowired
 private User user;*/

/* @Test
 public void testLogin() {
 //User user = new User();
 user.setUsername("shiyanlou");
 user.setPassword("123456");
 System.out.println(userService.login(user).toString());

 }*/

    @Test
    public void testSelectAllUser() {
        List<User> users = userService.selectAllUser();
        for (User us : users) {
            System.out.println(us.toString());
        }
    }

/* @Test
 public void testAdd() {
 //User user = new User();
 user.setUsername("user2");
 user.setPassword("123456");
 user.setSex("female");
 user.setAge(25);
 userService.addUser(user);
 }

 @Test
 public void testUpdate() {
 //User user = new User();
 user.setId(3);
 user.setUsername("user2");
 user.setPassword("123");
 user.setSex("female");
 user.setAge(30);
 userService.updateUser(user);
 }

 @Test
 public void testUpdate() {
 int id = 3;
 userService.deleteUser(id);
 }*/

}

Here, we use Junit to conduct unit test and test five methods respectively. Here, we only demonstrate the testSelectAllUser() method of querying all users. Open the terminal and enter the mvn test command. The results are as follows:

There is only one piece of data in the user table. We can see that Spring and MyBatis have been successfully integrated.

If you want to inject the User object into the test class, you need to do two things:

  • Add code to the test class
@Autowired
private User user;
  • Add the @ Component annotation in the User class of the model layer
@Component
public class User {
    private Integer id;
    private String username;
    private String password;
    private String sex;
    private Integer age;
    ......
}

Note: however, the objects of general entity classes are not injected, but imported from the outside. This is for the convenience of testing.

After integrating Spring and MyBatis, we need to complete the integration of Spring MVC.

Controller layer implementation

At package com shiyanlou. Create a Controller class usercontroller under Controller Java, the code is as follows:

package com.shiyanlou.controller;

import com.shiyanlou.model.User;
import com.shiyanlou.service.UserService;
import org.apache.ibatis.annotations.Param;
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.util.List;

/**
 * Process user request Controller
 **/
@Controller
public class UserController {

    /**
 * Auto inject UserService
 **/
    @Autowired
    private UserService userService;

    // Sign in
    @RequestMapping("/login")
    public String login(User user, Model model, HttpSession session) {
        User loginUser = userService.login(user);

        if (loginUser != null) {
            session.setAttribute("user", loginUser);
            return "redirect:alluser";
        } else {
            session.setAttribute("message", "username or password is wrong!");
            return "redirect:loginform.jsp";
        }
    }

    // sign out
    @RequestMapping(value = "/loginout")
    public String loginout(HttpSession session) {
        session.invalidate();
        return "redirect:loginform.jsp";
    }

    // Query all users
    @RequestMapping("/alluser")
    public String selectAllUser(HttpServletRequest request) {
        List<User> listUser = userService.selectAllUser();
        request.setAttribute("listUser", listUser);
        return "userlist";
    }

    // Jump to the new user page
    @RequestMapping("/toadduser")
    public String toAddUserPage() {
        return "adduser";
    }

    // New user
    @RequestMapping("/adduser")
    public String addUser(User user, HttpServletRequest request) {
        userService.addUser(user);
        List<User> listUser = userService.selectAllUser();
        request.setAttribute("listUser", listUser);
        return "userlist";
    }

    // Jump to update user page
    @RequestMapping("/toupdateuser")
    public String toUpdateUser(@Param("id") Integer id,
                               HttpServletRequest request, Model model) {
        model.addAttribute("user\_id", id);
        return "updateuser";
    }

    // Update user
    @RequestMapping("/updateuser")
    public String updateUser(User user, HttpServletRequest request) {
        userService.updateUser(user);
        List<User> listUser = userService.selectAllUser();
        request.setAttribute("listUser", listUser);
        return "userlist";
    }

    // delete user
    @RequestMapping("/deleteuser")
    public String deleteUser(@Param("id") Integer id, HttpServletRequest request) {
        userService.deleteUser(id);
        List<User> listUser = userService.selectAllUser();
        request.setAttribute("listUser", listUser);
        return "userlist";
    }
}

JSP page

loginform.jsp

Create a new JSP page under src/main/webapp directory and name it loginform JSP, as the login page, the code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
    <h4>Login Page</h4>
    <form action="login" method="post">
    <font color="red">${sessionScope.message}</font>
        <table>
            <tr>
                <td><label>username:</label></td>
                <td><input type="text" id="username" name="username" />
            </tr>
            <tr>
                <td><label>password:</label></td>
                <td><input type="password" id="password" name="password" />
            </tr>
            <tr>
                <td><input type="submit" value="login" />
            </tr>
        </table>
    </form>
</body>
</html>

userlist.jsp

Create a new directory JSP under webapp/WEB-INF / and a new JSP page named userlist JSP, as the main page, the code is as follows:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ssm</title>
<style type="text/css">
td {
    text-align: center;
    width: 100px;
}
</style>
</head>

<body>
    <div align="right">
        Welcome,[<font color=red>${sessionScope.user.username}</font>] | <a
            href="loginout">Exit</a>
    </div>
    <br>
    <center>
        <table border="1">
            <tbody>
                <tr>
                    <th>id</th>
                    <th>username</th>
                    <th>password</th>
                    <th>sex</th>
                    <th>age</th>
                    <th colspan="2" style="">Options</th>
                </tr>
                <c:if test="${!empty listUser }">
                    <c:forEach items="${listUser}" var="user">
                        <tr>
                            <td>${user.id}</td>
                            <td>${user.username}</td>
                            <td>${user.password}</td>
                            <td>${user.sex}</td>
                            <td>${user.age}</td>
                            <td><a href="toupdateuser?id=${user.id}">modify</a></td>
                            <td><a href="deleteuser?id=${user.id}">delete</a></td>
                        </tr>
                    </c:forEach>
                </c:if>
            </tbody>
        </table>
        <br>
        <a href="toadduser">Add a new user</a>
    </center>
</body>
</html>

adduser.jsp

Create a new JSP page under webapp/WEB-INF/jsp directory and name it addUser JSP, as a new user page, the code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Page</title>
</head>
<body>
    <h4>AddUser Page</h4>
    <form action="adduser" method="post">
        <table>
            <tr>
                <td><label>username:</label></td>
                <td><input type="text" id="username" name="username" />
            </tr>
            <tr>
                <td><label>password:</label></td>
                <td><input type="password" id="password" name="password" />
            </tr>
            <tr>
                <td><label>sex:</label></td>
                <td><input type="text" id="sex" name="sex" />
            </tr>
            <tr>
                <td><label>age:</label></td>
                <td><input type="text" id="age" name="age" />
            </tr>
            <tr>
                <td><input type="submit" value="add" />
            </tr>
        </table>
    </form>
</body>
</html>

updateuser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Modify Page</title>
</head>
<body>
    <h4>Modify Page</h4>
    <form action="updateuser" method="post">
        <table>
            <tr>
                <td><label>id:</label></td>
                <td><input type="text" id="id" name="id" value="${user\_id}" readonly="readonly"/>
            </tr>
            <tr>
                <td><label>username:</label></td>
                <td><input type="text" id="username" name="username" />
            </tr>
            <tr>
                <td><label>password:</label></td>
                <td><input type="password" id="password" name="password" />
            </tr>
            <tr>
                <td><label>sex:</label></td>
                <td><input type="text" id="sex" name="sex" />
            </tr>
            <tr>
                <td><label>age:</label></td>
                <td><input type="text" id="age" name="age" />
            </tr>
            <tr>
                <td><input type="submit" value="modify" />
            </tr>
        </table>
    </form>
</body>
</html>

Configure spring MVC XML file

Create a new Spring MVC configuration file Spring MVC. Under the directory Java Resources/src XML, the code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mvn="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-4.2.xsd
      http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    <mvn:default-servlet-handler/>
    <!-- Automatically scan the package, Spring MVC Will use the bag @Controller The annotated class is registered as Spring of controller -->
    <context:component-scan base-package="com.shiyanlou.controller" />
    <!-- Set default configuration scheme -->
    <mvc:annotation-driven />
    <!-- view resolver  -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

Configure web XML file

Now we come to the last step of integration, configuring web XML file, the code is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app\_4\_0.xsd"
         version="4.0">
    <display-name>SSMTest</display-name>

    <!-- to configure Spring Core listener -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- appoint Spring Configuration file for -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!-- definition Spring MVC Front end controller -->
    <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:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- by DispatcherServlet Establish mapping -->
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- Coding filter -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*
 

 
 
 loginform.jsp
 

At this point, the SSM framework will be fully integrated. Next, we will test it.

Run test

Open the terminal file - > open new terminal, enter mvn jetty:run to run the program, and click the tool - Web Service button to access the web service.

Note: at present, the experimental building only supports 8080 port to start the service. If other ports are used, the service will not be accessible. Here jetty defaults to 8080 port, so there is no need to change it.

Enter the wrong user name or password (our initial data is username:shiyanlou, password:123456).

When the user name and password are correct, enter the home page.

There is only one piece of data here.

Click the Add a new user link below to enter the new user page and fill in the information of the new user.

Click the add button to complete the user adding operation, and you can see that the user is successfully added.

Click the modify link of the user record line with id 2 to enter the update user page and fill in the update information.

Click the modify button to complete the user's update operation, and you can see that the user information is updated successfully.

Click the delete link of the user record line with id 2 to delete the user.

Click the Exit link in the upper right corner to Exit the home page to the login page.

Topics: Python Database MySQL computer