SpringMVC学习(八):使用RESTFul模拟操作用户数据资源

简介: SpringMVC学习(八):使用RESTFul模拟操作用户数据资源

文档结构:

20210819120042189.png


springMVC.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--    开启组件扫描-->
    <context:component-scan base-package="demo.controller"></context:component-scan>
    <!-- 配置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>
<!--    视图控制器,没有控制器也可以跳转到首页,适用于仅仅用来实现页面跳转,没有任何请求处理的过程-->
    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--    开启mvc的注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <mvc:view-controller path="/test_rest" view-name="test_rest"></mvc:view-controller>
</beans>


web.xml

<?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">
    //配置编码过滤器
    <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>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    //配置springMVC的前端控制器DispatcherServlet
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


首先是GET和POST的模拟,比较简单,就直接贴代码了:


UserController.java:

package demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * RESTFul模拟用户资源的增删改查
 *
 * /user    GET     查询所有用户信息
 * /user/1  GET     根据用户id查询信息
 * /user    POST    添加用户信息
 * /user    PUT     修改用户信息
 * /user    DELETE  删除所有用户信息
 * /user/1  DELETE  根据id删除用户信息
 */
@Controller
public class UserController {
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String getAllUser(){
        System.out.println("查询所有用户信息");
        return "success";
    }
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String getUserById(){
        System.out.println("根据用户id查询信息");
        return "success";
    }
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(String username,String password){
        System.out.println("添加用户信息成功,用户名:"+username+" 密码:"+password);
        return "success";
    }
}


test_view.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a th:href="@{/user}">查询所有用户信息</a>
    <a th:href="@{/user/1}">根据id查询用户信息</a>
    <form th:action="@{user}" method="post">
        用户名: <input type="text" name="username">    <br>
        密  码: <input type="password" name="password">    <br>
        <input type="submit" value="增加">    <br>
    </form>
</body>
</html>


success.html(用来作为成功跳转的判断):

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


运行起来测试一下:

20210819120417339.png


只是简单模拟,页面比较丑

点击 查询:

20210819120500544.png

成功跳转,控制台也有输出:


20210819120605265.png


再退回来点击根据id查询:


20210819120627276.png


成功跳转,路径也正确,控制台也有输出:

20210819120720730.png

再退回来把表单填写完整,点击增加:

20210819120809985.png20210819120830983.png


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


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


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


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


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


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


先在web.xml中注册HiddenHttpMethodFilter

<!--    配置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>


<form th:action="@{user}" method="post">
        <input type="hidden" name="_method" value="put">
        用户名: <input type="text" name="username">    <br>
        密  码: <input type="password" name="password">    <br>
        <input type="submit" value="修改">    <br>
    </form>
    <form th:action="@{user/1}" method="post">
        <input type="hidden" name="_method" value="delete">
        用户名: <input type="text" name="username">    <br>
        <input type="submit" value="删除">    <br>
    </form>


注意,隐藏的input标签中的value才是真正的请求参数

@RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String updateUser(String username,String password){
        System.out.println("修改用户信息成功,用户名:"+username+" 密码:"+password);
        return "success";
    }
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String deleteUser(String username){
        System.out.println("删除用户信息成功,用户名:"+username);
        return "success";
    }


控制器和前面大致相同

测试一下:

20210819143839183.png20210819144154663.png2021081914340947.png20210819143425740.png20210819144221701.png20210819144243716.png20210819144305439.png



相关文章
|
3月前
|
前端开发 JavaScript
[SpringMVC]restful风格
[SpringMVC]restful风格
39 1
[SpringMVC]restful风格
|
8月前
|
XML JSON 前端开发
SpringMVC进阶-异常拦截器文件上传和Restful风格(1)
SpringMVC进阶-异常拦截器文件上传和Restful风格(1)
33 0
|
9月前
|
Java 测试技术 API
Java RESTful中的PATCH请求:局部更新与资源修改
在RESTful架构中,PATCH请求是一种用于局部更新已有资源的操作。PATCH请求允许客户端将部分数据发送到服务器,以便对资源进行局部修改,而不必替换整个资源。本文将引导您深入了解Java中使用PATCH请求构建RESTful API,探讨其特点、实现方式、用例以及在实际应用中的优势。
|
16天前
|
XML JSON 数据库
SpringMVC RESTful
SpringMVC RESTful
22 0
|
3月前
|
XML JSON Java
基于springMVC的RESTful服务实现
  RESTful(RESTful Web Services)一种架构风格,表述性状态转移,它不是一个软件,也不是一个标准,而是一种思想,不依赖于任何通信协议,但是开发时要成功映射到某协议时也需要遵循其标准,但不包含对通信协议的更改
24 1
|
4月前
|
XML JSON 前端开发
SpringMVC之视图和RESTful
【1月更文挑战第19天】 一、SpringMVC的视图 1、ThymeleafView 2、转发视图 3、重定向视图 4、视图控制器view-controller 二、RESTful 1、RESTful简介 a>资源 b>资源的表述 c>状态转移 2、RESTful的实现 3、HiddenHttpMethodFilter
62 0
|
4月前
|
XML JSON 数据库
SpringMVC之RESTful(含实际代码操作)
SpringMVC之RESTful(含实际代码操作)
|
5月前
|
XML JSON Java
SpringMVC原理分析 | Controller配置、RestFul风格
SpringMVC原理分析 | Controller配置、RestFul风格
32 0
|
5月前
|
前端开发
SpringMVC-RESTful快速开发及案例:基于RESTful页面数据交互
SpringMVC-RESTful快速开发及案例:基于RESTful页面数据交互
38 0
|
5月前
|
XML JSON Java
SpringMVC与REST相结合实现RESTful风格
SpringMVC与REST相结合实现RESTful风格
73 0