• SpringMVC处理ajax请求


    目录

    ⚪准备工作

    ⭐axios回顾  

    1.axios中文文档

    2.实例方法

    一、测试SpringMVC处理ajax请求 

    二、@RequestBody

    三、使用@RequestBody获取json格式的请求参数

    ⭐使用@RequestBody注解将json格式的请求参数转换为Java对象

    1.导入Jackson的依赖

    2.在SpringMVC的配置文件中设置开启MVC的注解驱动

    3.在处理请求的控制器方法的形参位置,直接设置json格式的请求参数要转换的Java类型的形参

    三、@ResponseBody

    四、@ResponseBody响应浏览器json格式的数据

    1.导入Jackson的依赖

    2.在SpringMVC的配置文件中设置开启MVC的注解驱动

    3.使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到浏览器

    ⚪常见的Java对象转换为json的结果

    五、@RestController注解


    ⚪准备工作

    配置web.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:mvc="http://www.springframework.org/schema/mvc"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    8. http://www.springframework.org/schema/mvc
    9. http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
    10. http://www.springframework.org/schema/context
    11. http://www.springframework.org/schema/context/spring-context-4.2.xsd">
    12. <context:component-scan base-package="com.atguigu.controller">context:component-scan>
    13. <bean id="viewResolver"
    14. class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    15. <property name="order" value="1"/>
    16. <property name="characterEncoding" value="UTF-8"/>
    17. <property name="templateEngine">
    18. <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
    19. <property name="templateResolver">
    20. <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    21. <property name="prefix" value="/WEB-INF/templates/"/>
    22. <property name="suffix" value=".html"/>
    23. <property name="templateMode" value="HTML5"/>
    24. <property name="characterEncoding" value="UTF-8" />
    25. bean>
    26. property>
    27. bean>
    28. property>
    29. bean>
    30. <mvc:default-servlet-handler/>
    31. <mvc:annotation-driven/>
    32. <mvc:view-controller path="/" view-name="index">mvc:view-controller>
    33. beans>

    创建控制层

    1. package com.atguigu.controller;
    2. import org.springframework.stereotype.Controller;
    3. @Controller
    4. public class TestAjaxController {
    5. }

    创建首页

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>首页title>
    6. head>
    7. <body>
    8. <div id="app">
    9. <h1>index.htmlh1>
    10. <input type="button" value="测试SpringMVC处理ajax请求" @click="testAjax()">
    11. div>
    12. <script type="text/javascript" th:src="@{/js/vue.js}">script>
    13. <script type="text/javascript" th:src="@{/js/axios.miin.js}">script>
    14. <script type="text/javascript">
    15. /**
    16. * axios({
    17. url:"", 请求路径
    18. method:"", 请求方式
    19. params:{},
    20. 以 name=value&name=value方式发送的请求参数
    21. 不管使用的请求方式是get还是post,请求参数都会被拼接到请求地址后
    22. 此种方式的请求参数可以通过request.getParameter()获取
    23. data:{}
    24. 以json格式发送的请求参数
    25. 请求参数会被保存到请求报文的请求体传输到服务器(get没有请求体)
    26. 此种方式的请求参数不可以通过request.getParameter()获取
    27. }).then(response=>{
    28. console.log(response.data);
    29. });
    30. */
    31. var vue = new Vue({
    32. el:"#app",
    33. methods:{
    34. testAjax(){
    35. axios.post("");
    36. }
    37. }
    38. });
    39. script>
    40. body>
    41. html>

    项目目录

    ⭐axios回顾  

    1.axios中文文档

    axios中文文档|axios中文网 | axios (axios-js.com)

    2.实例方法

    一、测试SpringMVC处理ajax请求 

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>首页title>
    6. head>
    7. <body>
    8. <div id="app">
    9. <h1>index.htmlh1>
    10. <input type="button" value="测试SpringMVC处理ajax请求" @click="testAjax()">
    11. div>
    12. <script type="text/javascript" th:src="@{/js/vue.js}">script>
    13. <script type="text/javascript" th:src="@{/js/axios.min.js}">script>
    14. <script type="text/javascript">
    15. var vue = new Vue({
    16. el:"#app",
    17. methods:{
    18. testAjax(){
    19. axios.post(
    20. "/SpringMVC/test/ajax?id=1001",
    21. {username:"admin",password:"123456"}
    22. ).then(response=>{
    23. console.log(response.data)
    24. });
    25. }
    26. }
    27. });
    28. script>
    29. body>
    30. html>
    1. import org.springframework.stereotype.Controller;
    2. import org.springframework.web.bind.annotation.RequestMapping;
    3. import javax.servlet.http.HttpServletResponse;
    4. import java.io.IOException;
    5. @Controller
    6. public class TestAjaxController {
    7. @RequestMapping("/test/ajax")
    8. public void testAjax(Integer id, HttpServletResponse response) throws IOException {
    9. System.out.println("id :" + id);
    10. response.getWriter().write("hello,axios");
    11. }
    12. }

    二、@RequestBody

    将请求体中的内容和控制器方法的形参进行绑定

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

    1. @RequestMapping("/test/ajax")
    2. public void testAjax(Integer id, @RequestBody String requestBody, HttpServletResponse response) throws IOException {
    3. System.out.println("requestBody :" + requestBody);
    4. System.out.println("id :" + id);
    5. response.getWriter().write("hello,axios");
    6. }

    三、使用@RequestBody获取json格式的请求参数

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

    • name=value&name=value...,此时的请求参数可以通过request.getParameter()获取,对应 SpringMVC中,可以直接通过控制器方法的形参获取此类请求参数
    • {key:value,key:value,...},此时无法通过request.getParameter()获取,之前我们使用操作 json的相关jar包gson或jackson处理此类请求参数,可以将其转换为指定的实体类对象或map集合。在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将此类请求参数转换为java对象

    ⭐使用@RequestBody注解将json格式的请求参数转换为Java对象

    1.导入Jackson的依赖

    (在pom.xml中)

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.coregroupId>
    3. <artifactId>jackson-databindartifactId>
    4. <version>2.11.3version>
    5. dependency>

    2.在SpringMVC的配置文件中设置开启MVC的注解驱动

    <mvc:annotation-driven/>

    3.在处理请求的控制器方法的形参位置,直接设置json格式的请求参数要转换的Java类型的形参

    使用 @RequestBody注解标识即可

    ⚪创建实体类User

    1. package com.atguigu.pojo;
    2. public class User {
    3. private Integer id;
    4. private String username;
    5. private String password;
    6. private Integer age;
    7. private String gender;
    8. public User() {
    9. }
    10. public User(Integer id, String username, String password, Integer age, String gender) {
    11. this.id = id;
    12. this.username = username;
    13. this.password = password;
    14. this.age = age;
    15. this.gender = gender;
    16. }
    17. public Integer getId() {
    18. return id;
    19. }
    20. public void setId(Integer id) {
    21. this.id = id;
    22. }
    23. public String getUsername() {
    24. return username;
    25. }
    26. public void setUsername(String username) {
    27. this.username = username;
    28. }
    29. public String getPassword() {
    30. return password;
    31. }
    32. public void setPassword(String password) {
    33. this.password = password;
    34. }
    35. public Integer getAge() {
    36. return age;
    37. }
    38. public void setAge(Integer age) {
    39. this.age = age;
    40. }
    41. public String getGender() {
    42. return gender;
    43. }
    44. public void setGender(String gender) {
    45. this.gender = gender;
    46. }
    47. @Override
    48. public String toString() {
    49. return "User{" +
    50. "id=" + id +
    51. ", username='" + username + '\'' +
    52. ", password='" + password + '\'' +
    53. ", age=" + age +
    54. ", gender='" + gender + '\'' +
    55. '}';
    56. }
    57. }

    ⚪控制器方法

    1. @RequestMapping("/test/RequestBody/json")
    2. public void testRequestBody(@RequestBody User user,HttpServletResponse response) throws IOException {
    3. System.out.println(user);
    4. response.getWriter().write("hello.RequestBody");
    5. }
    6. @RequestMapping("/test/RequestBody/json")
    7. public void testRequestBody(@RequestBody Map map, HttpServletResponse response) throws IOException {
    8. System.out.println(map);
    9. response.getWriter().write("hello.RequestBody");
    10. }

    三、@ResponseBody

    @ResponseBody:将所标识的控制器方法的返回值作为响应报文的响应体响应到浏览器

    <a th:href="@{/test/ResponseBody}">测试@ResponseBody注解响应浏览器数据a><br>
    1. @RequestMapping("/test/ResponseBody")
    2. @ResponseBody
    3. public String testResponseBody(){
    4. return "success";
    5. }

     

    四、@ResponseBody响应浏览器json格式的数据

    1.导入Jackson的依赖

    (在pom.xml中)

    1. <dependency>
    2. <groupId>com.fasterxml.jackson.coregroupId>
    3. <artifactId>jackson-databindartifactId>
    4. <version>2.11.3version>
    5. dependency>

    2.在SpringMVC的配置文件中设置开启MVC的注解驱动

    <mvc:annotation-driven/>

    3.使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到浏览器

    <input type="button" value="使用@ResponseBody注解响应json格式的数据" @click="testResponseBody()">
    1. testResponseBody(){
    2. axios.post(
    3. "/SpringMVC/test/ResponseBody/json"
    4. ).then(response=>{
    5. console.log(response.data);
    6. });
    7. }

    响应不同的数据: 

    1. public User testResponseBodyJson(){
    2. User user = new User(1001, "admin", "123456", 20, "男");
    3. return user;
    4. }
    1. @RequestMapping("/test/ResponseBody/json")
    2. @ResponseBody
    3. public List testResponseBodyJson(){
    4. User user1 = new User(1001, "admin1", "123456", 20, "男");
    5. User user2 = new User(1002, "admin2", "123456", 20, "男");
    6. User user3 = new User(1003, "admin3", "123456", 20, "男");
    7. List list = Arrays.asList(user1, user2, user3);
    8. return list;
    9. }
    1. public Map testResponseBodyJson(){
    2. User user1 = new User(1001, "admin1", "123456", 20, "男");
    3. User user2 = new User(1002, "admin2", "123456", 20, "男");
    4. User user3 = new User(1003, "admin3", "123456", 20, "男");
    5. Map map = new HashMap<>();
    6. map.put("1001", user1);
    7. map.put("1002", user2);
    8. map.put("1003", user3);
    9. return map;
    10. }

    ⚪常见的Java对象转换为json的结果

    1. 实体类 —— > json对象 
    2. map —— >json 对象
    3. list —— > json数组

    五、@RestController注解

    @RestController注解是springMVC提供的一个复合注解

    标识在控制器的类上

    相当于为类添加了 @Controller注解,并且为其中的每个方法添加了@ResponseBody注解

  • 相关阅读:
    这一篇让你搞定 Flutter 的数据表格
    Python 插入、替换、提取、或删除Excel中的图片
    Kubernetes - Kubernetes详解;安装部署(一)
    自动化测试测试框架封装改造
    一分钟学习数据安全—自主管理身份SSI可验证凭证
    警惕Mallox勒索病毒的最新变种malloxx,您需要知道的预防和恢复方法。
    利用SpringBoot重写黑马旅游网
    ESP32-S3上手开发
    LeetCode 202 快乐数
    5.0、C语言——函数
  • 原文地址:https://blog.csdn.net/m0_52982868/article/details/126321488