Spring + SpringMVC + Mybatis + Thymeleaf

SpringMVC+Thymeleaf

准备工作步骤

1、构建工程

image-20220902101900220

2、添加maven依赖

<dependencies>
    <!-- SpringMVC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!-- 日志 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency>

    <!-- ServletAPI -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>

    <!-- Spring5和Thymeleaf整合包 -->
    <dependency>
        <groupId>org.thymeleaf</groupId>
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency>
</dependencies>

3、添加web模块

①将pom.xml的打包方式设置为war包

image-20220902100226117

②然后在整个项目的Moduldes配置web.xml路径如下图

image-20220902095903855

③配置web.xml文件:注册SpringMVC的前端控制器DispatcherServlet

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

    <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 --> 
    <servlet> 
        <servlet-name>springMVC</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        
        <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 --> 
        <init-param> 
            <!-- contextConfigLocation为固定值 --> 
            <param-name>contextConfigLocation</param-name> 
            <!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的 src/main/resources --> 
            <param-value>classpath:springMVC.xml</param-value> 
        </init-param> 
        <!--作为框架的核心组件,在启动过程中有大量的初始化操作要做 而这些操作放在第一次请求时才执行会严重影响访问速度 因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时 --> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
        <servlet-name>springMVC</servlet-name> 
        <!--设置springMVC的核心控制器所能处理的请求的请求路径 /所匹配的请求可以是/login或.html或.js或.css方式的请求路径 但是/不能匹配.jsp请求路径的请求 --> 
        <url-pattern>/</url-pattern> 
    </servlet-mapping>
    
    <!--配置springMVC的编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

注意:

配置springNVcC的前端控制器Dispatcherservlet
url-pattern中/和/*的区别:
/: 匹配浏览器向服务器发送的所有请求(不包括.jsp)
/*: 匹配浏览器向服务器发送的所有请求(包括.jsp)

4、spring MVC.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd 
        http://www.springframework.org/schema/mvc 
        https://www.springframework.org/schema/mvc/spring-mvc.xsd 
        http://www.springframework.org/schema/context 
        https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.springmvc.controller"/>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>


    <!--处理静态资源,例如html、js、css、jpg 若只设置该标签,则只能访问静态资源,其他请求则无法访问,此时必须设置<mvc:annotation-driven/>解决问题 -->

    <mvc:default-servlet-handler/>
    <!-- 开启mvc注解驱动 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 处理响应中文内容乱码 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
</beans>

总结:

浏览器发送请求,若请求地址符合前端控制器的url-pattern,该请求就会被前端控制器DispatcherServlet处理。前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应页面。

@RequestMapping注解

@RequestMapping注解的功能

@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。

SpringMVC 接收到指定的请求,就会来找到在映射关系中对应的控制器方法来处理这个请求

@RequestMapping注解的位置

@RequestMapping标识一个类:设置映射请求的请求路径的初始信息

@RequestMapping标识一个方法:设置映射请求请求路径的具体信息

@Controller @RequestMapping("/test") 
public class RequestMappingController { 
    //此时请求映射所映射的请求的请求路径为:/test/testRequestMapping 
    @RequestMapping("/testRequestMapping") 
    public String testRequestMapping(){ 
        return "success"; 
    }
}

@RequestMapping注解的value属性

@RequestMapping注解的value属性通过请求的请求地址匹配请求映射

@RequestMapping注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求

@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射

@RequestMapping注解的method属性

@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射

@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配多种请求方式的请求

若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错

405:Request method ‘POST’ not supported

注:

1、对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解

处理get请求的映射–>@GetMapping

处理post请求的映射–>@PostMapping

处理put请求的映射–>@PutMapping

处理delete请求的映射–>@DeleteMapping

2、常用的请求方式有get,post,put,delete

但是目前浏览器只支持get和post,若在form表单提交时,为method设置了其他请求方式的字符

串(put或delete),则按照默认的请求方式get处理

若要发送put和delete请求,则需要通过spring提供的过滤器HiddenHttpMethodFilter,在RESTful部分会讲到

@RequestMapping注解的params属性(了解)

@RequestMapping注解的params属性通过请求的请求参数匹配请求映射

@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数和请求映射的匹配关系

“param”:要求请求映射所匹配的请求必须携带param请求参数

“!param”:要求请求映射所匹配的请求必须不能携带param请求参数

“param=value”:要求请求映射所匹配的请求必须携带param请求参数且param=value

“param!=value”:要求请求映射所匹配的请求必须携带param请求参数但是param!=value

@RequestMapping( value = {"/testRequestMapping", "/test"} ,
                method = {RequestMethod.GET, RequestMethod.POST} ,
                params = {"username","password!=123456"} 
               )
public String testRequestMapping(){ 
    return "success"; 
}

注:

若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,此时

页面回报错400:Parameter conditions “username, password!=123456” not met for actual

request parameters: username={admin}, password={123456}

@RequestMapping注解的headers属性(了解)

@RequestMapping注解的headers属性通过请求的请求头信息匹配请求映射

@RequestMapping注解的headers属性是一个字符串类型的数组,可以通过四种表达式设置请求头信息和请求映射的匹配关系

“header”:要求请求映射所匹配的请求必须携带header请求头信息

“!header”:要求请求映射所匹配的请求必须不能携带header请求头信息

“header=value”:要求请求映射所匹配的请求必须携带header请求头信息且header=value

“header!=value”:要求请求映射所匹配的请求必须携带header请求头信息且header!=value

若当前请求满足@RequestMapping注解的value和method属性,但是不满足headers属性,此时页面

显示404错误,即资源未找到

SpringMVC支持ant风格的路径

?:表示任意的单个字符

*:表示任意的0个或多个字符

**:表示任意层数的任意目录

注意:在使用时,只能使用//xxx的方式

SpringMVC支持路径中的占位符(重点)

原始方式:/deleteUser?id=1

rest方式:/user/delete/1

SpringMVC路径中的占位符常用于RESTful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参

<a th:href="@{/testRest/1/admin}">测试路径中的占位符-->/testRest</a><br>
@RequestMapping("/testRest/{id}/{username}") 
public String testRest(@PathVariable("id") String id, @PathVariable("username") String username){ 
    System.out.println("id:"+id+",username:"+username); 
    return "success"; 
}
//最终输出的内容为-->id:1,username:admin

注意:

当请求路径中的{}内容与方法中的参数一致,则@PathVariable(“id”)可以省略括号中的内容

如上的接口可以写成如下所示的接口

@RequestMapping("/testRest/{id}/{username}") 
public String testRest(@PathVariable String id, @PathVariable String username){ 
    System.out.println("id:"+id+",username:"+username); 
    return "success"; 
}

SpringMVC获取请求参数

1、通过ServletAPI获取

将HttpServletRequest作为控制器方法的形参,此时HttpServletRequest类型的参数表示封装了当前请求的请求报文的对象

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>表单</title>
</head>
<body>
  <form th:action="@{/add}" method="post">
    username:<input type="text" name="username">
    password:<input type="password" name="password">
    <input type="submit">
  </form>
</body>
</html>
@RequestMapping("/testParam") 

public String testParam(HttpServletRequest request){ 
    String username = request.getParameter("username"); 
    String password = request.getParameter("password"); 
    System.out.println("username:"+username+",password:"+password); 
    return "success"; 
}

2、通过控制器方法的形参获取请求参数

在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在DispatcherServlet中就会将请求参数赋值给相应的形参

<a th:href="@{/testParam(username='admin',password=123456)}">测试获取请求参数-- >/testParam</a><br>
@RequestMapping("/testParam") 
public String testParam(String username, String password){ 
    System.out.println("username:"+username+",password:"+password); 
    return "success"; 
}

注:

若请求所传输的请求参数中有多个同名的请求参数,此时可以在控制器方法的形参中设置字符串

数组或者字符串类型的形参接收此请求参数

若使用字符串数组类型的形参,此参数的数组中包含了每一个数据

若使用字符串类型的形参,此参数的值为每个数据中间使用逗号拼接的结果

3、@RequestParam

@RequestParam是将请求参数和控制器方法的形参创建映射关系

@RequestParam注解一共有三个属性:

  • value:指定为形参赋值的请求参数的参数名

  • required:设置是否必须传输此请求参数,默认值为true,若设置为true时,则当前请求必须传输value所指定的请求参数,若没有传输该请求参数,且没有设置defaultValue属性,则页面报错400:Required String parameter ‘xxx’ is not present;若设置为false,则当前请求不是必须传输value所指定的请求参数,若没有传输,则注解所标识的形参的值为null

  • defaultValue:不管required属性值为true或false,当value所指定的请求参数没有传输或传输的值为""时,则使用默认值为形参赋值

 @PostMapping("/add")
 public String message(@RequestParam String username,@RequestParam("password") String password){
      System.out.println("username:"+username+'\n'+"password:"+password);
      return "success";
}

4、@RequestHeader

@RequestHeader是将请求头信息和控制器方法的形参创建映射关系

@RequestHeader注解一共有三个属性:value、required、defaultValue,用法同@RequestParam

5、@CookieValue

@CookieValue是将cookie数据和控制器方法的形参创建映射关系

@CookieValue注解一共有三个属性:value、required、defaultValue,用法同@RequestParam

6、通过POJO获取请求参数

可以在控制器方法的形参位置设置一个实体类类型的形参,此时若浏览器传输的请求参数的参数名和实体类中的属性名一致,那么请求参数就会为此属性赋值

实体类

public class User {
    private Integer id;
    private String username;

    private String password;

    private String sex;
    private Integer age;



    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
    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 getSex() {
        return sex;
    }

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

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" >
    <title>首页</title>
</head>
<body>

    <p>这是首页</p>

    <form th:action="@{/hello}" method="post">
        姓名:<input type="text" name="username">
        密码:<input type="password" name="password">
        年龄:<input type="text" name="age">
        <input type="submit" name="提交">
    </form>
</body>
</html>

@RequestMapping("/hello")
public String hello(User user){
      Integer age = user.getAge();
      String username = user.getUsername();
      String password = user.getPassword();
      System.out.println("username:"+username+'\n'+"password:"+password+'\n'+"age:"+age);
      return "success";
}

解决获取请求参数的乱码问题

解决获取请求参数的乱码问题,可以使用SpringMVC提供的编码过滤器CharacterEncodingFilter,但是必须在web.xml中进行注册

<!--配置springMVC的编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

注:

SpringMVC中处理编码的过滤器一定要配置到其他过滤器之前,否则无效

域对象共享数据

<!--    通过ModeLAndview向请求域共享数据-->
    <p th:text="${testRequestScope}"></p>

<!--    使用Model向请求域共享数据-->
    <p th:text="${scopeModel}"></p>

<!--    使用ModeLMap向请求域共享数据-->
    <p th:text="${scopeModelMap}"></p>

<!--    使用map向请求域共享数据-->
    <p th:text="${scopeMap}"></p>

1、使用ServletAPI向request域对象共享数据

@RequestMapping("/testServletAPI") 
public String testServletAPI(HttpServletRequest request){ 
    request.setAttribute("testScope", "hello,servletAPI"); 
    return "success"; 
}

2、使用ModelAndView向request域对象共享数据

/**
     * 1、通过ModeLAndview向请求域共享数据
     * 使用ModelAndview时,可以使用其wodel功能向请求域共享数据
     * 使用view功能设置逻辑视图,但是控制器方法一定要将ModelAndview作为方法的返回值
     * @return
     */
    @RequestMapping("/test/maV")
    public ModelAndView testMAV(){
        /**
         *  ModelAndView有Model和View的功能
         *
         *  Model主要用于向请求域共享数据
         *
         *  View主要用于设置视图,实现页面跳转
         */
        ModelAndView andView = new ModelAndView();

        //想请求域中共享数据
        andView.addObject("testRequestScope","hello,ModelAndView");

        //设置逻辑视图
        andView.setViewName("success");
        return andView;
    }

3、使用Model向request域对象共享数据

//2、使用Model向请求域共享数据
    @RequestMapping("/test/model")
     public String testModel(Model model){
        model.addAttribute("scopeModel","hello,Model");
        return "success";
     }

4、使用map向request域对象共享数据

// 3,使用ModeLMap向请求域共享数据
    @RequestMapping("/test/modelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("scopeModelMap","hello,ModelMap");
        return "success";
    }

5、使用ModelMap向request域对象共享数据

 // 4,使用map向请求域共享数据
    @RequestMapping("/test/map")
    public String testMap(Map<String,Object> map){
        map.put("scopeMap","hello,scopeMap");
        return "success";
    }

6、Model、ModelMap、Map的关系

Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型

public interface Model{} 

public class ModelMap extends LinkedHashMap<String, Object> {} 

public class ExtendedModelMap extends ModelMap implements Model {} 

public class BindingAwareModelMap extends ExtendedModelMap {}

7、向session域共享数据

<!--    向session域共享数据-->
    <p th:text="${session.scopeSession}"></p>
 //向session域共享数据
    @RequestMapping("/test/session")
    public String testSession(HttpSession session){
        session.setAttribute("scopeSession","hello,Session");
        return "success";
    }

8、向application域共享数据

<!--向application域共享数据-->
    <p th:text="${application.testApplication}"></p>
 //向application域共享数据
    @RequestMapping("/test/application")
    public String testApplication(HttpSession session){
        ServletContext context = session.getServletContext();
        context.setAttribute("testApplication","hello,application");
        return "success";

    }

SpringMVC的视图

SpringMVC中的视图是View接口,视图的作用渲染数据,将模型Model中的数据展示给用户

SpringMVC视图的种类很多,默认有转发视图和重定向视图

当工程引入jstl的依赖,转发视图会自动转换为JstlView

若使用的视图技术为Thymeleaf,在SpringMVC的配置文件中配置了Thymeleaf的视图解析器,由此视图解析器解析之后所得到的是ThymeleafView

1、ThymeleafView

当控制器方法中所设置的视图名称没有任何前缀时,此时的视图名称会被SpringMVC配置文件中所配置的视图解析器解析,视图名称拼接视图前缀和视图

后缀所得到的最终路径,会通过转发的方式实现跳转

 <a th:href="@{/test/view/thymeleaf}">测试SpringMVC的视图thymeleafView</a>
    <hr>

    @RequestMapping("/test/view/thymeleaf")
    public String testThymeleafView(){
        return "success";
    }

2、转发视图

SpringMVC中默认的转发视图是InternalResourceView

SpringMVC中创建转发视图的情况:

当控制器方法中所设置的视图名称以"forward:"为前缀时,创建InternalResourceView视图,此时的视

图名称不会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"forward:"去掉,剩余部

分作为最终路径通过转发的方式实现跳转

例如"forward:/",“forward:/employee”

注意:转发的url不变

@RequestMapping("/test/view/forward")
    public String testInternalResoutceView(){
        return "forward:/test/application";//转发到http://localhost:8081/SpringMVC//test/application,但是此时的url任然是http://localhost:8081/SpringMVC/test/view/forward
    }
<a th:href="@{/test/view/forward}">测试SpringMVC的视图InternalResourceView(转发)</a>
    <hr>

3、重定向视图

SpringMVC中默认的重定向视图是RedirectView

当控制器方法中所设置的视图名称以"redirect:"为前缀时,创建RedirectView视图,此时的视图名称不

会被SpringMVC配置文件中所配置的视图解析器解析,而是会将前缀"redirect:"去掉,剩余部分作为最

终路径通过重定向的方式实现跳转

例如"redirect:/","redirect:/employee”

注意:重定向的url会改变

<a th:href="@{/test/view/redirect}">测试SpringMVC的视图RedirectView(重定向)</a>
    <hr>
//重定向
    @RequestMapping("//test/view/redirect")
    public String testRedirectView(){
        return "redirect:/test/application";//转发到http://localhost:8081/SpringMVC//test/application,但是此时的url就是http://localhost:8081/SpringMVC//test/application,而不是http://localhost:8081/SpringMVC/test/view/redirect
    }

4、视图控制器view-controller

当控制器方法中,仅仅用来实现页面跳转,即只需要设置视图名称时,可以将处理器方法使用view-controller标签进行表示,在SpringMVC.xml配置文件中添加配置如下

<!--    视图控制器:为当前的请求直接设置视图名称实现页面跳转
若设置视图控制器,则只有视图控制器所设置的请求会被处理,其他的请求将全部404此时必须在配置一个标签:<mvc : annotation-driven />
-->
    <mvc:view-controller path="/" view-name="index"/>

此时在controller控制器就不需要如下的方法

@RequestMapping("/")
    public String test(){

        //将逻辑视图返回
        return "index";
    }

RESTful

1、RESTful简介

REST:Representational State Transfer,表现层资源状态转移。

①资源

资源是一种看待服务器的方式,即,将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念。因为资源是一个抽象的概念,所以它不仅仅能代表服务器文件系统中的一个文件、数据库中的一张表等等具体的东西,可以将资源设计的要多抽象有多抽象,只要想象力允许而且客户端应用开发者能够理解。与面向对象设计类似,资源是以名词为核心来组织的,首先关注的是名词。一个资源可以由一个或多个URI来标识。URI既是资源的名称,也是资源在Web上的地址。对某个资源感兴趣的客户端应用,可以通过资源的URI与其进行交互。

②资源的表述

资源的表述是一段对于资源在某个特定时刻的状态的描述。可以在客户端-服务器端之间转移(交换)。资源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频等等。资源的表述格式可以通过协商机制来确定。请求-响应方向的表述通常使用不同的格式。

③状态转移

状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的。

2、RESTful的实现

具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。

它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE用来删除资源。

REST 风格提倡 URL 地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为 URL 地址的一部分,以保证整体风格的一致性。

操作传统方式RESTFUL风格
查询操作getUserById?id=1user/1–>get请求方式
保存操作saveUseruser–>post请求方式
删除操作deleteUser?id=1user/1–>delete请求方式
更新操作updateUseruser–>put请求方式

3、HiddenHttpMethodFilter

由于浏览器只支持发送get和post方式的请求,那么该如何发送put和delete请求呢?

SpringMVC 提供了 HiddenHttpMethodFilter 帮助我们 POST 请求转换为 DELETE PUT 请求

HiddenHttpMethodFilter 处理put和delete请求的条件:

  • a>当前请求的请求方式必须为post

  • b>当前请求必须传输请求参数_method

满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数_method的值才是最终的请求方式。

在web.xml中注册HiddenHttpMethodFilter

<!--设置处理请求方式的过滤器-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
<h1>欢迎使用SpringMVC的Restful风格</h1>
  <a th:href="@{/user}">查询所有用户</a><br>
  <a th:href="@{/user/1}">查询id为1的用户</a><br>

    <form th:action="@{/user}" method="post">
        <input type="submit" value="添加用户信息">
    </form>

    <form th:action="@{/user}" method="post">
        <input type="hidden" name="_method" value="put">
        <input type="submit" value="修改用户信息">
    </form>

  <form th:action="@{/user/1}" method="post">
      <input type="hidden" name="_method" value="delete">
      <input type="submit" value="删除id为1的用户信息">
  </form>
/**
 * 查询所有的用户信息-->/user-->get
 * 根据id查询用户信息-->/user/1-->get
 * 添加用户信息-->/user-->post
 * 修改用户信息-->/user-->put
 * 删除用户信息-->/user/1-->delete
 */

/**
 * 注意:浏览器目前只能发送get和post请求
 * 若要发送put和delete请求,需要在web.xml中配置一个过滤器HiddenHttpMethodFilter配置了过滤器之后,发送的请求要满足两个条件,才能将请求方式转换为put或delete
 * 1、当前请求必须为post
 * 2、当前请求必须传输请求参数_method,_method的值才是最终的请求方式
 */
@Controller
public class TestRestfulController {

    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String getAllUser(){

        System.out.println("这是get请求");
        System.out.println("查询所有的用户信息-->/user-->get");
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String getUserById(@PathVariable Integer id){
        System.out.println("这是get请求");
        System.out.println("根据id查询用户信息-->/user/"+id+"-->get");
        return "success";
    }

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String insertUser(){
        System.out.println("这是post请求");
        System.out.println("添加用户信息-->/user-->post");
        return "success";
    }

    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String updateUser(){
        System.out.println("这是put请求");
        System.out.println("修改用户信息-->/user-->put");
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String deleteUser(){
        System.out.println("这是delete请求");
        System.out.println("删除用户信息-->/user/1-->delete");
        return "success";
    }
}

注意:

目前为止,SpringMVC中提供了两个过滤器:CharacterEncodingFilter和

HiddenHttpMethodFilter

在web.xml中注册时,必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter

原因:

在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字

符集的

request.setCharacterEncoding(encoding) 方法要求前面不能有任何获取请求参数的操作

而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作:

String paramValue = request.getParameter(this.methodParam);

RESTful案例

实体类

public class Employee {
    private Integer id;
    private String lastName;
    private String email;
    //1 male, 0 female
    private Integer gender;

    public Employee() {
    }

    public Employee(Integer id, String lastName, String email, Integer gender) {
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
    }

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", gender=" + gender +
                '}';
    }
}

mapper,这里先写死,正常开发从数据库中获取

@Repository
public class EmployeeMapper {
    private static Map<Integer, Employee> employees = null;
    static{
        employees = new HashMap<Integer, Employee>();
        employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1));
        employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1));
        employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0));
        employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0));
        employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1));
    }
    private static Integer initId = 1006;
    
    //保存或修改方法
    public void save(Employee employee){
        if(employee.getId() == null){
            employee.setId(initId++);
        }
        employees.put(employee.getId(), employee);
    }

    //获取所有员工信息方法
    public Collection<Employee> getAll(){
        return employees.values();
    }

    //通过id来获取员工信息
    public Employee get(Integer id){
        return employees.get(id);
    }

    //通过id来删除员工信息
    public void delete(Integer id){
        employees.remove(id);
    }
}

Controller控制器

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeMapper employeeMapper;

    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    public String getAllEmployee(Model model){

        //获取所有的员工信息
        Collection<Employee> allEmployee = employeeMapper.getAll();

        //将所有员工的信息在请求域中共享
        model.addAttribute("allEmployee",allEmployee);

        //跳转到列表页
        return "employee_list";
    }

    //添加员工
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String addEmployee(Employee employee){
        employeeMapper.save(employee);

        //添加成功后重定向到显示所有员工页面
        return "redirect:/employee";
    }


    //根据id查询员工信息
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
    public String getEmployeeById(@PathVariable Integer id,Model model){

        //根据id查询员工信息
        Employee employee = employeeMapper.get(id);

        //将员工信息共享到请求域中
        model.addAttribute("employee",employee);

        //跳转到employee_add.html页面
        return "employee_update";
    }


    //修改员工信息
    @RequestMapping(value = "/employee",method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        //调用修改员工信息的方法
        employeeMapper.save(employee);

        //重定向到所有员工列表/employee
        return "redirect:/employee";
    }

    //删除员工信息
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
    public String deteleEmployee(@PathVariable Integer id){
        //调用删除员工信息的方法
        employeeMapper.delete(id);

        //删除成功后回到显示员工列表页面
        return "redirect:/employee";
    }
}

功能清单

功能URL地址请求方式
访问首页√/GET
查询全部数据√/employeeGET
删除√/employee/2DELETE
跳转到添加数据页面√/toAddGET
执行保存√GET/employeePOST
跳转到更新数据页面√/employee/{id}GET
执行更新√/employeePUT

创建前端页面

①创建employee_list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>employee_list</title>

    <!-- 引用css样式-->
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
<div id="app">
  <table>
    <tr>
      <th colspan="5">employee_list</th>
    </tr>

    <tr>
      <th>id</th>
      <th>lastName</th>
      <th>email</th>
      <th>gender</th>
      <th>options(<a th:href="@{/to/add}">add</a>)</th>
    </tr>

    <tr th:each="employee : ${allEmployee}">
      <td th:text="${employee.id}"></td>
      <td th:text="${employee.lastName}"></td>
      <td th:text="${employee.email}"></td>

      <!--thmeleaf三目运算使用-->
      <td th:text="${employee.gender} == 1? '':''"></td>
      <td>
        <a th:href="@{'/employee/'+${employee.id}}">编辑</a>
        <a @click="deleteEmployee()" th:href="@{'/employee/'+${employee.id}}">删除</a>
      </td>
    </tr>
  </table>

   <!--删除功能,delete请求方式的表单 --> 
  <form method="post">
    <input type="hidden" name="_method" value="delete">
  </form>
</div>

  <!--  使用vue实现删除功能-->
  <script type="text/javascript" th:src="@{/static/js/vue.js}"></script>

  <script type="text/javascript">
    var vue = new Vue({
      el:"#app",
      methods:{
        deleteEmployee(){
          //获取form表单
          var form = document.getElementsByTagName("form")[0];

          //将超链接的href属性值赋值给form表单的action属性
          //event.target表示当前触发事件的标签
          form.action = event.target.href;

          //将表单提交
          form.submit();

          //阻止超链接的默认行为
          event.preventDefault();
        }
      }

    })
  </script>
</body>
</html>
②创建employee_add.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title> add employee</title>

    <!-- 引用css样式-->
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
  <form th:action="@{/employee}" method="post">
    <table>
      <tr>
        <th colspan="2">add employee</th>
      </tr>

      <tr>
        <td>lastName</td>
        <td>
          <input type="text" name="lastName">
        </td>
      </tr>

      <tr>
        <td>email</td>
        <td>
          <input type="text" name="email">
        </td>
      </tr>

      <tr>
        <td>gender</td>
        <td>
          <input type="radio" name="gender" value="1"><input type="radio" name="gender" value="0"></td>
      </tr>

      <tr>
        <td colspan="2">
          <input type="submit" value="添加">
        </td>
      </tr>
    </table>
  </form>
</body>
</html>
③创建employee_update.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title> add employee</title>

    <!-- 引用css样式-->
    <link rel="stylesheet" th:href="@{/static/css/index_work.css}">
</head>
<body>
  <form th:action="@{/employee}" method="post">
    <input type="hidden" value="put" name="_method">
    <input type="hidden" name="id" th:value="${employee.id}">
    <table>
      <tr>
        <th colspan="2">add employee</th>
      </tr>

      <tr>
        <td>lastName</td>
        <td>
          <input type="text" name="lastName" th:value="${employee.lastName}">
        </td>
      </tr>

      <tr>
        <td>email</td>
        <td>
          <input type="text" name="email" th:value="${employee.email}">
        </td>
      </tr>

      <tr>
        <td>gender</td>
        <td>
          <!--th:field="${employee.gender}" 数据回显-->
          <input type="radio" name="gender" value="1" th:field="${employee.gender}"><input type="radio" name="gender" value="0" th:field="${employee.gender}"></td>
      </tr>

      <tr>
        <td colspan="2">
          <input type="submit" value="提交修改">
        </td>
      </tr>
    </table>
  </form>
</body>
</html>

SpringMVC处理ajax(axios)请求

axios({
       url: '', //请求路径
       method: '',//请求方法
       params: '',//请求参数
       data: '',//请求参数
   }).then(res => {
       //.then(res =>{})表示ajax请求成功后服务器返回来的结果
       console.log(res.data)
   })

params请求参数的方式:
     以name=value&name=value的方式发送的请求参数
     不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后
     此种方式的请求参数可以通过request.getParameter()获取

data请求参数的方式:
    以json格式发送的请求参数,请求参数会被保存到请求报文的请求体传输到服务器
    此种方式的请求参数不能通过request.getParameter()获取

index.html页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
 <div id="app">
     <h1>index.html</h1>
     <input type="button" value="测试springMVC处理Ajax请求" @click="testAjax">
 </div>


  <script type="text/javascript" th:src="@{static/js/vue.js}"></script>
  <script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>

 <!--
                 axios({
                        url: '', //请求路径
                        method: '',//请求方法
                        params: '',//请求参数
                        data: '',//请求参数
                    }).then(res => {
                        //.then(res =>{})表示ajax请求成功后服务器返回来的结果
                        console.log(res.data)
                    })

                 params请求参数的方式:
                      以name=value&name=value的方式发送的请求参数
                      不管使用的请求方式是get或post,请求参数都会被拼接到请求地址后
                      此种方式的请求参数可以通过request.getParameter()获取

                 data请求参数的方式:
                     以json格式发送的请求参数,请求参数会被保存到请求报文的请求体传输到服务器
                     此种方式的请求参数不能通过request.getParameter()获取

 -->


  <script type="text/javascript">
     var app = new Vue({
          el:"#app",
         // data:{},
         methods:{
              testAjax(){
                    axios.post("/ajax/test?id=1001",
                        {
                            username: "admin",
                            password: "123456"
                        }
                    ).then(res =>{
                        console.log(res.data)
                    })
              }
         }
      })
  </script>
</body>
</html>

controller

@Controller
public class TestAjaxController {
    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public void testAjax(Integer id, HttpServletResponse response) throws IOException {
        System.out.println("id:"+id);
        response.getWriter().write("hello.axios");
    }
}

1、@RequestBody

@RequestBody可以获取请求体信息,使用@RequestBody注解标识控制器方法的形参,当前请求的请求体就会为当前注解所标识的形参赋值

@Controller
public class TestAjaxController {
    @RequestMapping(value = "/test",method = RequestMethod.POST)
    public void testAjax(Integer id,@RequestBody String requestBody, HttpServletResponse response) throws IOException {
        System.out.println("RequestBody:"+requestBody);
        System.out.println("id:"+id);
        response.getWriter().write("hello.axios");
    }
}

image-20220904121109369

2、@RequestBody获取json格式的请求参数

在使用了axios发送ajax请求之后,浏览器发送到服务器的请求参数有两种格式:

1、name=value&name=value…,此时的请求参数可以通过request.getParameter()获取,对应SpringMVC中,可以直接通过控制器方法的形参获取此类请求参数

2、{key:value,key:value,…},此时无法通过request.getParameter()获取,之前我们使用操作json的相关jar包gson或jackson处理此类请求参数,可以将其转换为指定的实体类对象或map集

合。在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将此类请求参数转换为java对象

使用@RequestBody获取json格式的请求参数的条件:

①导入jackson的依赖

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.12.1</version> 
</dependency>

②SpringMVC的配置文件中设置开启mvc的注解驱动

<!--开启mvc的注解驱动--> 
<mvc:annotation-driven />

③在控制器方法的形参位置,设置json格式的请求参数要转换成的java类型(实体类或map)的参数,并使用@RequestBody注解标识

<body>
 <div id="app">
     <h1>index.html</h1>
     <input type="button" value="测试@RequestBody处理json格式的请求" @click="testRequestBody">
 </div>
  <script type="text/javascript" th:src="@{static/js/vue.js}"></script>
  <script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
 <script type="text/javascript">
     var app = new Vue({
          el:"#app",
         // data:{},
         methods:{
             testRequestBody(){
                  axios.post("/ajax/test/requestBody/json",
                      {
                          username: "admin",
                          password: "123456",
                          age: 23,
                          gender: "男"
                      }
                  ).then(res =>{
                      console,log(res.data)
                  })
             }
         }
      })
  </script>
</body>

pojo实体类

package com.springmvc.ajax.pojo;

public class User {

    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String  gender;

    public User() {
    }

    public User(Integer id, String username, String password, Integer age, String gender) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
        this.gender = gender;
    }

    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 Integer getAge() {
        return age;
    }

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

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

controller

 @RequestMapping(value = "/test/requestBody/json",method = RequestMethod.POST)
    public void testRequestBody(@RequestBody User user, HttpServletResponse response) throws IOException {
        System.out.println(user);
        response.getWriter().write("hello,@RequestBody");
    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2eccv86m-1663079569537)(D:\java笔记\笔记\SpringMVC+thymleaf.assets\image-20220904123043595.png)]

若没有对应的实体类,则在controller使用map集合页可以,如下(没有对应的实体类)

@RequestMapping(value = "/test/requestBody/json",method = RequestMethod.POST)
    public void testRequestBody(@RequestBody Map<String,Object> map, HttpServletResponse response) throws IOException {
        System.out.println(map);
        response.getWriter().write("hello,@RequestBody");
    }

image-20220904123848453

3、@ResponseBody

@ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到浏览器

 @RequestMapping(value = "/test/responseBody",method = RequestMethod.GET)
    @ResponseBody
    public String testResponseBody(){
        return "success";
    }

image-20220904124815538

4、@ResponseBody响应浏览器json数据

服务器处理ajax请求之后,大多数情况都需要向浏览器响应一个java对象,此时必须将java对象转换为json字符串才可以响应到浏览器,之前我们使用操作json数据的jar包gson或jackson将java对象转换为json字符串。在SpringMVC中,我们可以直接使用@ResponseBody注解实现此功能

@ResponseBody响应浏览器json数据的条件:

①导入jackson的依赖

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.12.1</version> 
</dependency>

②SpringMVC的配置文件中设置开启mvc的注解驱动

<!--开启mvc的注解驱动--> 
<mvc:annotation-driven />

③、使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器

的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到

浏览器

<body>
 <div id="app">
     <h1>index.html</h1>
     <a th:href="@{/test/responseBody}">测试@ResponseBody注解响应浏览器数据</a><br>
     <input type="button" value="测试@ResponseBody注解响应json格式的数据" @click="testResponseBody"><br>
 </div>


  <script type="text/javascript" th:src="@{static/js/vue.js}"></script>
  <script type="text/javascript" th:src="@{/static/js/axios.min.js}"></script>
  <script type="text/javascript">
     var app = new Vue({
          el:"#app",
         // data:{},
         methods:{
             testRequestBody(){
                  axios.post("/ajax/test/requestBody/json",
                      {
                          username: "admin",
                          password: "123456",
                          age: 23,
                          gender: "男"
                      }
                  ).then(res =>{
                      console.log(res.data)
                  })
             },
             testResponseBody(){
                  axios.post("/ajax/test/responseBody/json").then(res =>{
                      console.log(res.data)
                  })
             }
         }
      })
  </script>
</body>

④contrlloer

	//返回一条信息
	@RequestMapping(value = "/test/responseBody/json")
    @ResponseBody
    public User testResponseBodyJson(){
        User user = new User(1001, "admin", "123456", 23, "男");
        return user;
    }

	//返回多条信息,使用map集合接收
    @RequestMapping(value = "/test/responseBody/json")
    @ResponseBody
    public Map<String,Object> testResponseBodyJson(){
        User user1 = new User(1001, "admin", "123456", 23, "男");
        User user2 = new User(1002, "zhangsan", "123456", 30, "女");
        User user3 = new User(1003, "wangwu", "123456", 20, "男");
        User user4 = new User(1004, "lisi", "123456", 18, "女");
        Map<String, Object> map = new HashMap<>();
        map.put("1",user1);
        map.put("2",user2);
        map.put("3",user3);
        map.put("4",user4);

        return map;
    }

	//返回多条信息,使用list集合接收
    @RequestMapping(value = "/test/responseBody/json")
    @ResponseBody
    public List<User> testResponseBodyJson(){
        User user1 = new User(1001, "admin", "123456", 23, "男");
        User user2 = new User(1002, "zhangsan", "123456", 30, "女");
        User user3 = new User(1003, "wangwu", "123456", 20, "男");
        User user4 = new User(1004, "lisi", "123456", 18, "女");
        List<User> list = Arrays.asList(user1, user2, user3, user4);
        return list;
    }

@RestController注解

@RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller注解,并且为其中的每个方法添加了@ResponseBody注解

文件上传和下载

1、文件下载

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

使用ResponseEntity实现下载文件的功能

  //文件下载
    @RequestMapping(value = "/test/down")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();

        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/1.jpg");

        //创建输入流
        InputStream is = new FileInputStream(realPath);

        //创建字节数组
        byte[] bytes = new byte[is.available()];

        //将流读到字节数组中
        is.read(bytes);

        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();

        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename=1.jpg");

        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;

        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        //关闭输入流
        is.close(); return responseEntity;
    }

2、文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”,SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息

上传步骤:

①添加依赖:

<dependency> 
    <groupId>commons-fileupload</groupId> 
    <artifactId>commons-fileupload</artifactId> 
    <version>1.3.1</version> 
</dependency>

②在SpringMVC的配置文件中添加配置:

<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象--> 
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> </bean>

③控制器方法:

form表单

 	<!--注意:input标签的name属性值必须与上传文件控制器的形参同名-->
	<form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
         头像:<input type="file" name="multipartFile"><br>
             <input type="submit" value="上传">
     </form>
 //文件上传

    /**
     * 文件上传要求
     * l、form表单的请求方式必须为post
     * 2、form表单必须设置属性enctype="multipart/form-data"
     * @param session
     * @return
     */
    @RequestMapping(value = "/test/up",method = RequestMethod.POST)
    public String testUp(MultipartFile multipartFile,HttpSession session) throws IOException {

        //获取上传的文件名称
        String filename = multipartFile.getOriginalFilename();
        System.out.println(filename);

        //获取servletContext对象
        ServletContext servletContext = session.getServletContext();

        //获取当前工程下multipartFile目录的真实路径
        String realPath = servletContext.getRealPath("multipartFile");

        //创建realPath所对应的file对象
        File path = new File(realPath);

        //判断path所对应目录是否存在
        if (!path.exists()){
            path.mkdir(); //如果不存在就创建该目录
        }
        String finalPath = realPath + File.separator + filename;

        //上传文件
        multipartFile.transferTo(new File(finalPath));
        return "success";
    }

拦截器

1、拦截器的配置

SpringMVC中的拦截器用于拦截控制器方法的执行

SpringMVC中的拦截器需要实现HandlerInterceptor

SpringMVC的拦截器必须在SpringMVC的配置文件中进行配置:

<bean class="com.atguigu.interceptor.FirstInterceptor"></bean> 
<ref bean="firstInterceptor"></ref> 
<!-- 以上两种配置方式都是对DispatcherServlet所处理的所有的请求进行拦截 --> 
<mvc:interceptor> 
    <mvc:mapping path="/**"/> 
    <mvc:exclude-mapping path="/testRequestEntity"/> 
    <ref bean="firstInterceptor"></ref> 
</mvc:interceptor> 
<!--以上配置方式可以通过ref或bean标签设置拦截器,通过mvc:mapping设置需要拦截的请求,通过 mvc:exclude-mapping设置需要排除的请求,即不需要拦截的请求 -->

2、拦截器的三个抽象方法

SpringMVC中的拦截器有三个抽象方法:

preHandle:控制器方法执行之前执行preHandle(),其boolean类型的返回值表示是否拦截或放行,返回true为放行,即调用控制器方法;返回false表示拦截,即不调用控制器方法

postHandle:控制器方法执行之后执行postHandle()

afterCompletion:处理完视图和模型数据,渲染视图完毕之后执行afterCompletion()

①若每个拦截器的preHandle()都返回true

此时多个拦截器的执行顺序和拦截器在SpringMVC的配置文件的配置顺序有关:

preHandle()会按照配置的顺序执行,而postHandle()和afterCompletion()会按照配置的反序执行

②若某个拦截器的preHandle()返回了false

preHandle()返回false和它之前的拦截器的preHandle()都会执行,postHandle()都不执行,返回false

的拦截器之前的拦截器的afterCompletion()会执行

异常处理器

1、基于配置的异常处理

SpringMVC提供了一个处理控制器方法执行过程中所出现的异常的接口:HandlerExceptionResolver

HandlerExceptionResolver接口的实现类有:DefaultHandlerExceptionResolver和SimpleMappingExceptionResolver

SpringMVC提供了自定义的异常处理器SimpleMappingExceptionResolver,使用方式:

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
    <property name="exceptionMappings"> 
        <props> 
            <!--properties的键表示处理器方法执行过程中出现的异常 properties的值表示若出现指定异常时,设置一个新的视图名称,跳转到指定页面 --> 
            <prop key="java.lang.ArithmeticException">error</prop> 
        </props> 
    </property> 
    <!--exceptionAttribute属性设置一个属性名,将出现的异常信息在请求域中进行共享 --> 
    <property name="exceptionAttribute" value="ex"></property> 
</bean>

2、基于注解的异常处理

//@ControllerAdvice将当前类标识为异常处理的组件 
@ControllerAdvice 
public class ExceptionController { 
    //@ExceptionHandler用于设置所标识方法处理的异常 
    @ExceptionHandler(ArithmeticException.class) 
    
    //ex表示当前请求处理中出现的异常对象 
    public String handleArithmeticException(Exception ex, Model model){ 
        model.addAttribute("ex", ex); 
        return "error";
    } 
}

注解配置SpringMVC

1、创建初始化类,代替web.xml

在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,名为AbstractAnnotationConfigDispatcherServletInitializer,

当我们的类扩展了AbstractAnnotationConfigDispatcherServletInitializer并将其部署到Servlet3.0容器的时候,容器会自动发现它,并用它来配置Servlet上下文。

/**
 * 该类用于代替web.xml配置文件
 */
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    /**
     * 设置一个配置类代替spring的配置文件
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    /**
     * 设置一个配置类代替SpringMVC的配置文件
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }


    /**
     * 指定DispatcherServlet的映射规则,即url-pattern
     * @return
     */
    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    /**
     * 设置当前的过滤器
     * @return
     */
    @Override
    protected Filter[] getServletFilters() {

        //创建编码过滤器
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");//设置编码
        encodingFilter.setForceEncoding(true);

        //创建处理请求方式的过滤器
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        return new Filter[]{encodingFilter,hiddenHttpMethodFilter};
    }
}

2、创建SpringConfig配置类,代替spring的配置文件

@Configuration //将该类表示为配置类
public class SpringConfig {
}

3、创建WebConfig配置类,代替SpringMVC的配置文件

/**
 * 该类用于代替SpringMVC.xml的配置文件
 *
 *扫描组件、视图解析器、默认的servlet、 mvc的注解驱动视图控制器、文件上传解析器、拦截器、异常解析器
 */

@Configuration //将该类表示为配置类
@ComponentScan("com.springmvc.annotation.controller") //扫描组件
@EnableWebMvc //开启mvc注解驱动
public class WebConfig implements WebMvcConfigurer {

    /**
     * 默认的servlet处理静态资源
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    /**
     * 配置视图解析器
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
    }

    /**
     * //配置文件上传解析器
     * @return
     */
    @Bean //可以将标识的方法的返回值作为bean进行管理,bean的id为方法的方法名
    public CommonsMultipartResolver multipartResolver(){
        return new CommonsMultipartResolver();
    }

    /**
     * 配置拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        FirstInterceptor firstInterceptor = new FirstInterceptor();
        registry.addInterceptor(firstInterceptor).addPathPatterns("/**");
    }

    /**
     * 配置异常解析器
     * @param resolvers
     */
    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties = new Properties();
        properties.setProperty("java.lang.ArithmeticException","error");
        resolver.setExceptionMappings(properties);
        resolver.setExceptionAttribute("ex");
        resolvers.add(resolver);
    }

    //配置生成模板解析器
    @Bean
    public ITemplateResolver templateResolver() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();

        // ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过 WebApplicationContext 的方法获得
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
        templateResolver.setPrefix("/WEB-INF/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }

    //生成模板引擎并为模板引擎注入模板解析器
    @Bean
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

    //生成视图解析器并未解析器注入模板引擎
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setCharacterEncoding("UTF-8");
        viewResolver.setTemplateEngine(templateEngine);
        return viewResolver;
    }
}

4、测试功能

创建index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
  <h1 style="text-align: center">首页</h1>
</body>
</html>

@RequestMapping("/") 
public String index(){ 
    return "index"; 
}

image-20220905234121001

SpringMVC执行流程

1、SpringMVC常用组件

  • DispatcherServlet:前端控制器,不需要工程师开发,由框架提供

    • 作用:统一处理请求和响应,整个流程控制的中心,由它调用其它组件处理用户的请求
  • HandlerMapping:处理器映射器,不需要工程师开发,由框架提供

    • 作用:根据请求的url、method等信息查找Handler,即控制器方法
  • Handler:处理器,需要工程师开发

    • 作用:在DispatcherServlet的控制下Handler对具体的用户请求进行处理
  • HandlerAdapter:处理器适配器,不需要工程师开发,由框架提供

    • 作用:通过HandlerAdapter对处理器(控制器方法)进行执行
  • ViewResolver:视图解析器,不需要工程师开发,由框架提供

    • 作用:进行视图解析,得到相应的视图,例如:ThymeleafView、InternalResourceView、RedirectView
  • View:视图

    • 作用:将模型数据通过页面展示给用户

SSM整合

1、ContextLoaderListener

Spring提供了监听器ContextLoaderListener,实现ServletContextListener接口,可监听ServletContext的状态,在web服务器的启动,读取Spring的配置文件,创建Spring的IOC容器。web应用中必须在web.xml中配置

<listener> 
    <!--配置Spring的监听器,在服务器启动时加载Spring的配置文件 
		Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml 
		可通过上下文参数自定义Spring配置文件的位置和名称 --> 
    <listener- class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<!--自定义Spring配置文件的位置和名称--> 
<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:spring.xml</param-value> 
</context-param>

2、准备工作

①创建Maven Module
②导入依赖
<packaging>war</packaging> 
<properties> 
    <spring.version>5.3.1</spring.version> 
</properties> 
<dependencies> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-context</artifactId> 
        <version>${spring.version}</version> 
    </dependency> 
    
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version> 
    </dependency> 
    
    <!--springmvc--> 
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-web</artifactId> 
        <version>${spring.version}</version> 
    </dependency>
    
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-webmvc</artifactId> 
        <version>${spring.version}</version> 
    </dependency> 
    
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-jdbc</artifactId> 
        <version>${spring.version}</version> 
    </dependency> 
    
    <dependency> 
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId> 
        <version>${spring.version}</version> 
    </dependency> 
    
    <dependency> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-test</artifactId> 
        <version>${spring.version}</version> 
    </dependency> 
    
    <!-- Mybatis核心 --> 
    <dependency> 
        <groupId>org.mybatis</groupId> 
        <artifactId>mybatis</artifactId> 
        <version>3.5.7</version> 
    </dependency> 
    
    <!--mybatis和spring的整合包--> 
    <dependency> 
        <groupId>org.mybatis</groupId> 
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency> 
    
    <!-- 连接池 --> 
    <dependency> 
        <groupId>com.alibaba</groupId> 
        <artifactId>druid</artifactId> 
        <version>1.0.9</version> 
    </dependency> 
    
    <!-- junit测试 --> 
    <dependency> 
        <groupId>junit</groupId> 
        <artifactId>junit</artifactId> 
        <version>4.12</version> 
        <scope>test</scope>
    </dependency> 
    
    <!-- MySQL驱动 --> 
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version> 
    </dependency> 
    
    <!-- log4j日志 -->
    <dependency> 
        <groupId>log4j</groupId> 
        <artifactId>log4j</artifactId>
        <version>1.2.17</version> 
    </dependency>
    
    <dependency> 
        <groupId>com.github.pagehelper</groupId> 
        <artifactId>pagehelper</artifactId> 
        <version>5.2.0</version> 
    </dependency> 
    
    <!-- 日志 --> 
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.3</version>
    </dependency> 
    
    <!-- ServletAPI --> 
    <dependency> 
        <groupId>javax.servlet</groupId> 
        <artifactId>javax.servlet-api</artifactId> 
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency> 
    
    <dependency> 
        <groupId>com.fasterxml.jackson.core</groupId> 
        <artifactId>jackson-databind</artifactId>
        <version>2.12.1</version> 
    </dependency> 
    
    <dependency> 
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version> 
    </dependency> 
    
    <!-- Spring5和Thymeleaf整合包 --> 
    <dependency> 
        <groupId>org.thymeleaf</groupId> 
        <artifactId>thymeleaf-spring5</artifactId>
        <version>3.0.12.RELEASE</version>
    </dependency> 
    
    <!--lombok-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
    </dependency>
</dependencies>
③创建表
CREATE TABLE `t_emp` ( 
    `emp_id` int(11) NOT NULL AUTO_INCREMENT, 
    `emp_name` varchar(20) DEFAULT NULL,
    `age` int(11) DEFAULT NULL,
    `sex` int(11) DEFAULT NULL,
    `email` varchar(50) DEFAULT NULL,
    PRIMARY KEY (`emp_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

3、配置web.xml

<!--配置springMVC的编码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 设置Spring的配置文件的位置和名称 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:Spring.xml</param-value>
    </context-param>

    <!-- 配置Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--
        配置springNVcC的前端控制器Dispatcherservlet
        url-pattern中/和/*的区别:
        /:匹配浏览器向服务器发送的所有请求(不包括.jsp
        /*:匹配浏览器向服务器发送的所有请求(包括.jsp)
    -->

    <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 通过初始化参数指定SpringMVC配置文件的位置和名称 -->
        <init-param>
            <!-- contextConfigLocation为固定值 -->
            <param-name>contextConfigLocation</param-name>
            <!-- 使用classpath:表示从类路径查找配置文件,例如maven工程中的 src/main/resources -->
            <param-value>classpath:SpringMVC.xml</param-value>
        </init-param>
        <!--作为框架的核心组件,在启动过程中有大量的初始化操作要做
        而这些操作放在第一次请求时才执行会严重影响访问速度
        因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时 -->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <!--设置springMVC的核心控制器所能处理的请求的请求路径
        /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
        但是/不能匹配.jsp请求路径的请求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--设置处理请求方式的过滤器-->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

4、创建SpringMVC的配置文件并配置

<!-- 自动扫描包 -->
    <context:component-scan base-package="com.ssm"/>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>

                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>


    <!--处理静态资源,例如html、js、css、jpg 若只设置该标签,则只能访问静态资源,其他请求则无法访问,此时必须设置<mvc:annotation-driven/>解决问题 -->

    <mvc:default-servlet-handler/>
    <!-- 开启mvc注解驱动 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 处理响应中文内容乱码 -->
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/to/add" view-name="employee_add"/>

5、搭建MyBatis环境

①创建属性文件application.properties
jdbc.username=root 

jdbc.password=123456

jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC 

jdbc.driver=com.mysql.cj.jdbc.Driver 
②创建MyBatis的核心配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>

            <!--将下划线映射为驼峰-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>

    <plugins>
        <!--配置分页插件-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    </plugins>
</configuration>
③创建Mapper接口和映射文件
public interface EmployeeMapper { 
     //查询所有员工
    List<Employee> getAllEmployee();

    //添加员工
    void insertEmployee(Employee employee);

    //删除员工
    void deleteEmployee(@Param("empId") Integer empId);

    //根据id查询员工
    Employee selectEmployeeById(@Param("empId") Integer empId);

    //修改员工信息
    void updateEmployee(Employee employee);
}
<?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.ssm.mapper.EmployeeMapper">


    <!--    查询所有用户信息-->
    <select id="getAllEmployee" resultType="Employee">
        select *
        from t_emp
  </select>

    <!--添加员工-->
    <insert id="insertEmployee"  parameterType="Employee">
        insert into t_emp values (null,#{empName},#{age},#{sex},#{email})
    </insert>

    <!--删除员工-->
    <delete id="deleteEmployee" >
        delete from t_emp where emp_id = #{empId}
    </delete>

    <!--修改员工信息-->
    <update id="updateEmployee" parameterType="Employee">
        update t_emp set emp_name = #{empName},age = #{age},sex = #{sex},email = #{email} where emp_id = #{empId}
    </update>

    <!--根据id查询员工信息-->
    <select id="selectEmployeeById" resultType="Employee">
        select * from t_emp where emp_id = #{empId}
    </select>
</mapper>
④创建日志文件log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n"/>
        </layout>
    </appender>

    <logger name="java.sql">
        <level value="debug"/>
    </logger>

    <logger name="org.apache.ibatis">
        <level value="info"/>
    </logger>

    <root>
        <level value="debug"/>
        <appender-ref ref="STDOUT"/>
    </root>
</log4j:configuration>

6、创建Spring的配置文件并配置

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

    <!--扫描组件(除了控制层)-->
    <context:component-scan base-package="com.ssm">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--引入application.properties文件-->
    <context:property-placeholder location="classpath:application.properties"/>

    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <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>


    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--开启事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置SqlSessionFactoryBean,可以直接在spring的IOC中获取SqlSessionFactory-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置Mybatis的核心配置文件的路径-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>

        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"/>

        <!--配置包的别名-->
        <property name="typeAliasesPackage" value="com.ssm.entity"/>
        <!--设置映射文件的路径,只有映射文件的包和mapper接口的包不一致时需要设置-->
        <!--<property name="mapperLocations" value="classpath:mappers/*.xml"/>-->

        <!--配置分页插件-->
        <!--<property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor"/>
            </array>
        </property>-->
    </bean>

    <!--配置mapper接口的扫描,可以将指定包下所有的mapper接口,通过SqlSession创建代理实现类对象,并将这些对象交给IoC容器管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.ssm.mapper"/>
    </bean>


</beans>

7、控制层代码编写

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 查询所有员工
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    public String getAllEmployee(Model model){
        //查询所有员工信息
       List<Employee> list =  employeeService.getAllEmployee();

       //将员工信息在请求域中共享
        model.addAttribute("employees",list);

        //跳转到employee_list.html页面
        return "employee_list";
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @RequestMapping(value = "/insert",method = RequestMethod.POST)
    public String insertEmployee(Employee employee){
        employeeService.insertEmployee(employee);
        return "redirect:/employee/page/1";
    }

    /**
     * 删除员工信息
     * @param empId
     * @return
     */
    @RequestMapping(value = "/delete/{empId}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("empId") Integer empId){
        employeeService.deleteEmployee(empId);
        return "redirect:/employee/page/1";
    }

    /**
     * 通过id来查询员工信息
     * @param empId
     * @return
     */
    @RequestMapping(value = "/getById/{empId}",method = RequestMethod.GET)
    public String getEmployeeById(@PathVariable("empId") Integer empId,Model model){
        Employee one = employeeService.selectEmployeeById(empId);
        model.addAttribute("employee",one);
        return "employee_update";
    }

    /**
     * 修改员工信息
     * @param employee
     * @return
     */
    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeService.updateEmployee(employee);
        return "redirect:/employee/page/1";
    }

    /**
     * 分页显示员工信息
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee/page/{pageNum}",method = RequestMethod.GET)
    public String getEmployeePage(@PathVariable Integer pageNum,Model model){
        //获取员工的分页信息
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNum);

        //将分页数据共享到请求域中
        model.addAttribute("page",page);

        //跳转到employee_list.html
        return "employee_list";
    }


}

8、业务层代码编写

public interface EmployeeService {
    //查询所有员工信息
    List<Employee> getAllEmployee();

    //添加员工
    void insertEmployee(Employee employee);

    //删除员工信息
    void deleteEmployee(Integer empId);

    //通过id来查询员工信息
    Employee selectEmployeeById(Integer empId);

    //修改员工信息
    void updateEmployee(Employee employee);

    //分页显示员工信息
    PageInfo<Employee> getEmployeePage(Integer pageNum);
}
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;
    //查询所有员工信息
    @Override
    public List<Employee> getAllEmployee() {

        return employeeMapper.getAllEmployee();
    }

    /**
     * 添加员工
     * @param employee
     */
    @Override
    public void insertEmployee(Employee employee) {
        employeeMapper.insertEmployee(employee);
    }

    /**
     * 删除员工信息
     * @param empId
     */
    @Override
    public void deleteEmployee(Integer empId) {
        employeeMapper.deleteEmployee(empId);
    }

    /**
     * 通过id来查询员工信息
     * @param empId
     * @return
     */
    @Override
    public Employee selectEmployeeById(Integer empId) {
        return employeeMapper.selectEmployeeById(empId);
    }

    /**
     * 修改员工信息
     * @param employee
     */
    @Override
    public void updateEmployee(Employee employee) {
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 分页显示员工信息
     * @param pageNum
     * @return
     */
    @Override
    public PageInfo<Employee> getEmployeePage(Integer pageNum) {
        //开启分页功能
        PageHelper.startPage(pageNum, 4);

        //查询所有员工
        List<Employee> list = employeeMapper.getAllEmployee();

        //获取分页相关信息
        PageInfo<Employee> page = new PageInfo<>(list,5);
        return page;
    }
}

9、实体类

@Data
public class Employee {
    private Integer empId;
    private String empName;
    private Integer age;
    private Integer sex;
    private String email;

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值