ssm framework integration (project steps)

I. Introduction

The SSM framework integrates the SpringMVC framework, Spring framework, and MyBatis framework. In order to simplify the tedious and repetitive operations in web development, developers can focus on the development of business processing.

2. SSM framework

2.1. What exactly does SSM integration integrate?

1. Integration of spring and mybaits (data source》sessionFactory》session)
2. Integration of spirng and springMVC

2.2. Why should we integrate them?

Under unified command, all classes and objects used in the two frameworks are managed by spring. Advantages: Seamless connection, using many tools provided by spring.

2.3. Who will integrate it?

The main configuration file of mybatis,
the configuration file of spring,
the configuration file of springMVC,
web.xml

2.4. What is the function of @ResponseBody annotation?

The @ResponseBody annotation is to write the data returned by the current interface directly into the HTTP Response Body.

2.5,JSON

JSON is a tool class provided by FastJson, which provides some data type conversion and data formatting functions.

3. Application scenarios of each framework

3.1, SpringMVC framework

The SpringMVC framework is located in the Controller layer and is mainly used to receive requests initiated by users. After receiving the requests, it can perform certain processing (such as information verification processing through interceptors). After processing, SpringMVC will distribute the request to the processing method in the corresponding Controller class according to the request path. The processing method then calls the business processing logic of the Service layer.

3.2, Spring framework

The Spring framework acts as a glue in SSM, using its object hosting features to organically combine the two independent frameworks SpringMVC and MyBatis. Spring can host the Controller class in SpringMVC and the SqlSession class in MyBatis, simplifying the manual management process. In addition to managing the core classes of SpringMVC and MyBatis, Spring can also manage the main business processing classes.

3.3, MyBatis framework

The MyBatis framework is used to operate the database, and the main functional class SqlSession can perform specific operations on the database.

4. Container management in the SSM framework

  1. SpringMVC container : mainly manages user requests and request results such as Controller objects and views.
  2. Spring container : mainly manages objects such as Service, Dao, and tool classes.
  3. The relationship between the two containers : The SpringMVC container is a sub-container of the Spring container, and the objects in the two containers are managed indirectly.

5. SSM framework integration steps

5.1, project preparation

Creation of databases and data tables.

5.2, create a new project and add dependencies
  1. Use Maven to create a new webapp project
    Insert image description here
  2. Add dependencies and project configuration in the pom.xml file.
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.version>5.2.5.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

    <!-- 连接mysql5 的驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.29</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.2</version>
    </dependency>

    <!-- mybatis依赖 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.2</version>
    </dependency>
    <!-- 参考版本对应 http://www.mybatis.org/spring/ -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- 数据源管理  使用了dbcp2数据 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.1.1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>2.4.2</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- commons 文件上传jar -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- 加入JSON转换工具 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>
  </dependencies>
5.3, configure web.xml file
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Application</display-name>

  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--  页面中输入的中文,调到后端,出现乱码解决的问题  -->
  <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>/*</url-pattern>
  </filter-mapping>
</web-app>
5.4. Create the directory structure. The structure diagram of Bean, Dao, Service and controller is as follows:

Insert image description here

5.5, configure each configuration file
  1. jdbc.properties. Database configuration information file.
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/yonghu?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT-8
user=
pwd=
  1. mybatis.xml. MyBatis main configuration file, the configuration of the data source in the file is executed by Spring.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--  日志  -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>
</configuration>
  1. applicationContext.xml。Spring整合MyBatis
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd

	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd

	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 加载属性文件   -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 创建dbcp2数据源 此数据源可以替换为阿里的 德鲁伊   -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${pwd}"></property>
    </bean>
    <!--  整合了sqlSessionFactory 包含了 数据源(dataSource)、配置文件(config)和映射文件(mapper)  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!--  扫描mapper接口  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xinxi2.dao"></property>
    </bean>

    <!--  扫描业务逻辑层的注解  -->
    <context:component-scan base-package="com.xinxi2"></context:component-scan>

    <!--  引入事务管理器 管理指定的数据源  -->
    <bean id="txMapper" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--  把事务管理管理,变成增强(通知),同时指定了方法的事务传播机制  -->
    <tx:advice id="txAdvice" transaction-manager="txMapper">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>


    <aop:config>
        <aop:pointcut id="servicePointcut" expression="execution(* com.xinxi2.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"></aop:advisor>
    </aop:config>
    <import resource="springmvc.xml"></import>
</beans>
  1. springmvc.xml. Spring integrated service.
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd

	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd

	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd

	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">

<!--  扫描  -->
    <context:component-scan base-package="com.xinxi2.controller"></context:component-scan>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <!-- Date的日期转换器 -->
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

<!--  常用视图解析器    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=""></property>
    </bean>

<!--  解决了静态资源的加载问题  -->
    <mvc:resources mapping="/static/**" location="/static/"></mvc:resources>


    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.RuntimeException">error.jsp</prop>
            </props>
        </property>
    </bean>

<!--  配置multipartResolver,用于上传文件,使用spring的CommonsMultipartResolver  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

<!--    <mvc:interceptors>-->
<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/hello/**"/>-->
<!--            <mvc:exclude-mapping path="/hello/hello04"/>-->
<!--            <bean class="com.Interceptor.LoginInterceptor"></bean>-->
<!--        </mvc:interceptor>-->
<!--    </mvc:interceptors>-->

</beans>
5.6. Write business implementation code, Bean entity class, dao layer interface, mapper file, service layer business processing class, controller layer control class, etc.

Bean entity class

package com.xinxi2.bean;

import com.alibaba.fastjson.annotation.JSONField;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Bookmanage {
    
    

    /** 图书编号 */
    private Integer id ;
    /** 图书名称 */
    private String name ;
    /** 图书作者 */
    private String author ;
    /** 购买时间 */
    @DateTimeFormat(pattern="yyyy-MM-dd") // String 转 Date 视图到控制层
    @JSONField(format = "yyyy-MM_dd")
    private Date time ;
    /** 图书分类 */
    private Integer type ;

    /** 图书编号 */
    public Integer getId(){
    
    
        return this.id;
    }
    /** 图书编号 */
    public void setId(Integer id){
    
    
        this.id=id;
    }
    /** 图书名称 */
    public String getName(){
    
    
        return this.name;
    }
    /** 图书名称 */
    public void setName(String name){
    
    
        this.name=name;
    }
    /** 图书作者 */
    public String getAuthor(){
    
    
        return this.author;
    }
    /** 图书作者 */
    public void setAuthor(String author){
    
    
        this.author=author;
    }
    /** 购买时间 */
    public Date getTime(){
    
    
        return this.time;
    }
    /** 购买时间 */
    public void setTime(Date time){
    
    
        this.time=time;
    }
    /** 图书分类 */
    public Integer getType(){
    
    
        return this.type;
    }
    /** 图书分类 */
    public void setType(Integer type){
    
    
        this.type=type;
    }
}

Dao floor

  1. BookmanageMapper.java
package com.xinxi2.dao;

import com.xinxi2.bean.Bookmanage;

import java.util.List;

public interface BookmanageMapper {

    List<Bookmanage> getlistBookmanage(Bookmanage bookmanage);

    int addBookmanage(Bookmanage bookmanage);

    Bookmanage updateByid(Integer id);

    int updateBookmanage(Bookmanage bookmanage);

    int deleteBookmanage(int id);

}
  1. BookmanageMapper.xml
<?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.xinxi2.dao.BookmanageMapper">

    <resultMap id="Bookmanageinto" type="com.xinxi2.bean.Bookmanage">
        <id property="id" column="id"></id>
        <result property="name" column="name"></result>
        <result property="author" column="author"></result>
        <result property="time" column="time"></result>
        <result property="type" column="type"></result>
    </resultMap>
    <select id="getlistBookmanage" resultType="com.xinxi2.bean.Bookmanage" resultMap="Bookmanageinto">
        SELECT `id`,`name`,`author`,`time`,`type` FROM `bookmanage`
        <where>
            <if test="id!=null">
                and id = #{id}
            </if>
            <if test="name!=null">
                and `name` = #{name}
            </if>
            <if test="author!=null">
                and author = #{author}
            </if>
            <if test="time!=null">
                and `time` = #{time}
            </if>
            <if test="type!=null">
                and `type` = #{type}
            </if>
        </where>
    </select>

    <insert id="addBookmanage">
        insert into `bookmanage`(id,`name`,`author`,`time`,`type`)
        values(#{id},#{name},#{author},#{time},#{type})
    </insert>

    <select id="updateByid" parameterType="integer" resultMap="Bookmanageinto">
        SELECT `id`,`name`,`author`,`time`,`type` FROM `bookmanage`
        where id=#{id}
    </select>

    <update id="updateBookmanage">
        update `bookmanage`
        <set>
            <if test="id!=null">
                id = #{id},
            </if>
            <if test="name!=null">
                `name` = #{name},
            </if>
            <if test="author!=null">
                author = #{author},
            </if>
            <if test="time!=null">
                `time` = #{time},
            </if>
            <if test="type!=null">
                `type` = #{type},
            </if>
        </set>
            where id=#{id}
    </update>

    <delete id="deleteBookmanage">
        delete from `bookmanage` where id=#{id}
    </delete>
</mapper>

Service layer
3. BookmanageService.java

package com.xinxi2.service;

import com.xinxi2.bean.Bookmanage;

import java.util.List;

public interface BookmanageService {
    
    

    List<Bookmanage> getlistBookmanage(Bookmanage bookmanage);

    int addBookmanage(Bookmanage bookmanage);

    Bookmanage updateByid(Integer id);

    int updateBookmanage(Bookmanage bookmanage);

    int deleteBookmanage(int id);
}

  1. BookmanageServiceImpl.java
package com.xinxi2.service.impl;

import com.xinxi2.bean.Bookmanage;
import com.xinxi2.dao.BookmanageMapper;
import com.xinxi2.service.BookmanageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("bookmanageService")
public class BookmanageServiceImpl implements BookmanageService {
    
    

    @Autowired
    private BookmanageMapper bookmanageMapper;

    @Override
    public List<Bookmanage> getlistBookmanage(Bookmanage bookmanage) {
    
    
        return bookmanageMapper.getlistBookmanage(bookmanage);
    }

    @Override
    public int addBookmanage(Bookmanage bookmanage) {
    
    
        return bookmanageMapper.addBookmanage(bookmanage);
    }

    @Override
    public Bookmanage updateByid(Integer id) {
    
    
        return bookmanageMapper.updateByid(id);
    }

    @Override
    public int updateBookmanage(Bookmanage bookmanage) {
    
    
        return bookmanageMapper.updateBookmanage(bookmanage);
    }

    @Override
    public int deleteBookmanage(int id) {
    
    
        return bookmanageMapper.deleteBookmanage(id);
    }
}

Controller layer
5. BookmanageConntroller.java

package com.xinxi2.controller;


import com.xinxi2.bean.Bookmanage;
import com.xinxi2.service.BookmanageService;
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.nio.channels.Pipe;
import java.util.List;

@Controller
@RequestMapping("/bookmanageConntroller")
public class BookmanageConntroller {
    
    

    @Autowired
    private BookmanageService bookmanageService;

    @RequestMapping("/listBookmanage")
    public String ListBookmanage(Bookmanage bookmanage, Model model){
    
    
        List<Bookmanage> list = bookmanageService.getlistBookmanage(bookmanage);
        model.addAttribute("tsList",list);
        return "list.jsp";
    }

    @RequestMapping("tiaozhuan")
    public String tiaozhuan(){
    
    
        return "add.jsp";
    }

    @RequestMapping("/addBookmanage")
    public String addBookmanage(Bookmanage bookmanage){
    
    
        bookmanageService.addBookmanage(bookmanage);
        return "redirect:/bookmanageConntroller/listBookmanage";
    }

    @RequestMapping("/updateById")
    public String updateById(int id,Model model){
    
    
        Bookmanage bookmanage = bookmanageService.updateByid(id);
        model.addAttribute("emp",bookmanage);
        return "update.jsp";
    }

    @RequestMapping("/update")
    public String update(Bookmanage bookmanage){
    
    
        bookmanageService.updateBookmanage(bookmanage);
        return "redirect:/bookmanageConntroller/listBookmanage";
    }

    @RequestMapping("/delete")
    public String delete(int id){
    
    
        bookmanageService.deleteBookmanage(id);
        return "redirect:/bookmanageConntroller/listBookmanage";
    }
}
5.7, write jsp page.

add.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/7/3
  Time: 16:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="/bookmanageConntroller/addBookmanage">
    图书名称:<input type="text" name="name"><br>
    图书作者:<input type="text" name="author"><br>
    购买时间:<input type="text" name="time"><br>
    图书分类:<input type="text" name="type"><br>
    <input type="submit">
</form>
</body>
</html>

list.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/7/3
  Time: 16:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table border="1">
    <tr>
        <td>图书编号</td>
        <td>图书名称</td>
        <td>图书作者</td>
        <td>购买时间</td>
        <td>图书分类</td>
        <td>操作</td>
    </tr>
    <c:forEach items="${tsList}" var="b">
        <tr>
            <td>${b.id}</td>
            <td>${b.name}</td>
            <td>${b.author}</td>
            <td>${b.time}</td>
            <td class="Fenlei">${b.type}</td>
            <td>
                <a href="/bookmanageConntroller/updateById?id=${b.id}">修改</a>
                <a href="/bookmanageConntroller/delete?id=${b.id}">删除</a>
            </td>
        </tr>
    </c:forEach>
</table>
<a href="/bookmanageConntroller/tiaozhuan">添加</a>
</body>
<script>
    var fenlei = document.getElementsByClassName("Fenlei");
    for (var i=0;i<fenlei.length;i++){
      
      
        var fenleiVal = fenlei[i].innerHTML;
        if (fenleiVal==1){
      
      
            fenlei[i].innerHTML="计算机/软件"
        }else if (fenleiVal==2){
      
      
            fenlei[i].innerHTML="小说/文摘"
        }else {
      
      
            fenlei[i].innerHTML="杂项"
        }
    }
</script>
</html>

update.jsp

<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/7/3
  Time: 16:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="/bookmanageConntroller/update">
    <input type="hidden" name="id" value="${emp.id}">
    图书名称:<input type="text" name="name" value="${emp.name}"><br>
    图书作者:<input type="text" name="author" value="${emp.author}"><br>
    购买时间:<input type="text" name="time" value="${emp.time}"><br>
    图书分类:<input type="text" name="type" value="${emp.type}"><br>
    <input type="submit">
</form>
</body>
</html>

6. Chinese garbled characters and date issues during JSON data transmission

6.1. Solve the problem of Chinese garbled characters during JSON data transmission.

The reason is that
the Spring MVC framework has a built-in message converter (org.springframework.http.converter.StringHttpMessageConverter) that handles String type data. The conversion character encoding in this message converter is fixed to "ISO-8859-1".

  1. Method 1:
    Set the encoding format on the controller method
@ResponseBody
@GetMapping(value="/{id}/view"
	,produces={
    
    "application/json;charset=UTF-8"})
public Object view(@PathVariable String id){
    
    
	//…….中间代码省略	
}
  1. Method 2:
    Assemble the message converter StringHttpMessageConverter
<mvc:annotation-driven>
	<mvc:message-converters>
		<bean class=
			"org.springframework.http.converter.StringHttpMessageConverter">
			<property name="supportedMediaTypes">
				<list>
					<value>application/json;charset=UTF-8</value>
				</list>
			</property>
		</bean>
	</mvc:message-converters>
</mvc:annotation-driven>
6.2. Solve the date format problem that occurs during JSON data transmission

Reason
Date format: timestamp format (1077033600000) “yyyy-MM-dd”

  1. Method 1
    Annotation method
public class SysUser(){
    
    
	@DateTimeFormat(pattern="yyyy-MM-dd")
	@JSONField(format="yyyy-MM-dd")
	private Date birthday;
	// 省略其他属性及getter、setter方法
}
  1. Method 2:
    Assemble the message converter StringHttpMessageConverter
<mvc:annotation-driven>
	<mvc:message-converters>
		<bean class=
			"org.springframework.http.converter.StringHttpMessageConverter">
			<property name="supportedMediaTypes">
				<list>
					<value>application/json;charset=UTF-8</value>
				</list>
			</property>
		</bean>
	</mvc:message-converters>
</mvc:annotation-driven>

7. Multi-view parser

  1. The same data content can be returned in different formats to present different view effects based on the Accept value, extension, etc.
  2. The user details query interface returns data in JSON pure data format.
    Insert image description here
7.1, Multi-view parsing manager ContentNegotiationManager
  1. Determine the MIME type required by the request to determine the view to use
  2. favorParameter
    indicates that parameter matching is supported. The MIME type can be determined based on the request parameter value. The default request parameter is format and the default value is true (supported)
  3. favorPathExtension
    indicates whether the extension is supported. The extension refers to xxx.json, xxx.xml and other forms. The default is true (supported)
  4. defaultContentType
    configures the default ContentType type
  5. mediaTypes
    determines the display type of data returned by the interface based on the MIME type of the request parameter. MIME types include json=application/json, xml=application/xml, html=text/html, etc.
7.2, multi-view resolver ContentNegotiatingViewResolver
  1. contentNegotiationManager
    injects a custom multi-view parsing manager
  2. defaultViews
    specifies the default view
  3. viewResolvers
    sets view resolvers

8. Data format conversion in Spring MVC framework

  1. Enter the new user information in the add user function. After clicking save, the system reports an error
    400 status code: The request format sent by the client is incorrect.
    Console: BindException
    Insert image description here
    . Time data cannot be automatically converted and bound in Spring MVC.
    The solution
    must be manual. Only by configuring the binding of custom data types can this function be
    converted and formatted.
    Insert image description here
  2. DataBinder
    core component of data binding
    core dispatch
  3. ConversionService
    The core interface of Spring type conversion system
    solves the problem of converting time format strings into Date type data in form forms
  4. Validator: data verification
  5. BindingResult
    contains the input parameter object that has completed data binding and the corresponding verification error object

Configuring the mvc:annotation-driven/ tag will register a default ConversionService instance, so that the method input parameter binding can support annotation-driven functions, so the date conversion problem can be solved by formatting annotations.

  1. Use a custom data format converter to implement date type data binding function
  2. Converter
    Function: Convert data from one type to another type
    Method: convert()
  3. Implementation steps
    : Create a custom data format converter.
    Assemble the custom ConversionService
    and use @InitBinder to assemble the custom editor
    . Create BaseController.java
@InitBinder
public void initBinder(WebDataBinder dataBinder){
    
    
    logger.info("进入BaseController的initBinder方法");
    dataBinder.registerCustomEditor(Date.class, new 	CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}

9. Use Spring MVC to implement single file upload

9.1, implementation steps
  1. Import dependent jar packages
    <!-- commons 文件上传jar -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  1. Configure MultipartResolver parser
<!--  配置multipartResolver,用于上传文件,使用spring的CommonsMultipartResolver  -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize" value="5000000"></property>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>
  1. Writing the Controller layer
    @RequestMapping("/addsysUser")
    public String addsysUser(SysUser sysUser, HttpServletRequest request, MultipartFile photo){
    
    
        String fileType = photo.getOriginalFilename();
        int index = fileType.lastIndexOf(".");
        fileType = fileType.substring(index);
        String path = request.getSession().getServletContext().getRealPath("static"+ File.separator+"uploadfiles");
        long filename = System.currentTimeMillis();
        System.out.println(path);
        System.out.println(fileType);
        System.out.println(path+"\\"+filename+fileType);
        File file = new File(path+"\\"+filename+fileType);

        try {
    
    
            photo.transferTo(file);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        sysUser.setAvatar(filename+fileType);
        sysUserService.addSysUser(sysUser);
        return "redirect:/sysUserController/sysUser";
    }
  1. Write jsp
<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2023/6/29
  Time: 15:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<!--  一定要在from加enctype -->
<form method="post" action="/sysUserController/addsysUser" enctype="multipart/form-data">
    用户名<input type="text" name="userName"><br>
    昵称<input type="text" name="nickName"><br>
    密码<input type="text" name="password"><br>
    账号状态<input type="text" name="status"><br>
    邮箱<input type="text" name="email"><br>
    手机号<input type="text" name="phonenumber"><br>
    用户性别<input type="text" name="sex"><br>
    头像<input type="file" name="photo"><br>  // 注意用file
    用户类型<input type="text" name="userType"><br>
    创建人的用户id<input type="text" name="createBy"><br>
    创建时间<input type="text" name="createTime"><br>
    更新人<input type="text" name="updateBy"><br>
    更新时间<input type="text" name="updateTime"><br>
    删除标志<input type="text" name="delFlag"><br>
    <input type="submit">
</form>
</body>
</html>

Insert image description here

Finish! ! ! !

Guess you like

Origin blog.csdn.net/H20031011/article/details/131520022