SpringMVC教程5[数据回写和异常处理及JSON操作]

简介: 一、数据回写 数据回写:在做数据更新的时候服务端查询的数据自动填充到表单中。

SpringMVC教程4[服务器端校验]

一、数据回写

   数据回写:在做数据更新的时候服务端查询的数据自动填充到表单中。

1.1默认方式

   通过前面讲解的 Map Mode ModelMap绑定数据

  @RequestMapping("/doLogin")
  public String doLogin(String username, String password, Model model) {
    if ("zhangsan".equals(username) && "123".equals(password)) {
      return "index";
    }
    model.addAttribute("username", username);
    model.addAttribute("password", password);
    return "forward:/login";
  }

页面中回写

<form action="/doLogin" method="post">
      <table>
        <tr>
          <td>用户名</td>
          <td><input type="text" name="username" value="${username}"></td>
        </tr>
        <tr>
          <td>密码</td>
          <td><input type="password" name="password" value="${password}"></td>
        </tr>
        <tr>
          <td><input type="submit" value="登录"></td>
        </tr>
      </table>
    </form>

2.通过Model方式

   如果使用对象去接收客户端传来的数据,那么对象默认会被自动放到model中,在前端页面可以直接使用对象中的数据。

   表单代码如下:

  /**
   *
   * 请求地址:
   * http://localhost:8080/SpringMVC-06-backvalue/
   * add1?username=a13&password=11111
   */
  @RequestMapping("/add1")
  public String add1(Book book) {
    System.out.println(book);
    return "/user.jsp";
  }

页面中

  <form action="add1" method="post">
    <table>
      <tr>
        <td>用户名</td>
        <td><input type="text" name="username"
          value="${book.username }"></td>
      </tr>
      <tr>
        <td>用户密码</td>
        <td><input type="text" name="password"
          value="${book.password }"></td>
      </tr>
      <tr>
        <td><input type="submit" value="注册"></td>
      </tr>
    </table>
  </form>

效果

image.png

3.@ModelAttribute注解实现

3.1 修改参数回显变量名

在需要回传的对象前添加@ModelAttribute(“bb”)注解,在界面中就可以通过bb前缀来获取回写信息。

image.pngimage.pngimage.png

3.2 配置全局变量名

   给接口中的每个方法统一返回一份数据

@Controller
public class UserController {
  /**
   *
   * 请求地址: http://localhost:8080/SpringMVC-06-backvalue/
   * add1?username=a13&password=11111
   */
  @RequestMapping("/add1")
  public String add1(@ModelAttribute("bb") Book book) {
    System.out.println(book);
    return "/user.jsp";
  }
  /**
   * 该类中的其他方法处理请求后都会绑定返回List集合,
   * 在页面中可以通过"as"作为key获取
   * @return
   */
  @ModelAttribute("as")
  public List<String> getAllAddress() {
    List<String> as = new ArrayList<>();
    as.add("深圳");
    as.add("广州");
    as.add("海口");
    return as;
  }
}

页面中获取

<body>
  获取全局配置返回的信息:<span style="color:red">${as}</span>
  <form action="add1" method="post">
    <table>
      <tr>
        <td>用户名</td>
        <td><input type="text" name="username"
          value="${bb.username }"></td>
      </tr>
      <tr>
        <td>用户密码</td>
        <td><input type="text" name="password"
          value="${bb.password }"></td>
      </tr>
      <tr>
        <td><input type="submit" value="注册"></td>
      </tr>
    </table>
  </form>
</body>

测试效果:

image.png

二、异常处理

   项目中的异常需要统一处理,正常情况下,需要提前准备好一个错误页面,当项目出错了,将该页面展示给用户。

   步骤:

2.1创建自定义异常类(可选)

/**
 * 自定义异常
 * 
 * @author dpb【波波烤鸭】
 *
 */
public class CustomException extends Exception {
  private String message;
  public CustomException(String message) {
    super(message);
    this.message = message;
  }
  @Override
  public String getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
}

2.2定义异常处理器

/**
 * 自定义异常处理器
 * @author dpb【波波烤鸭】
 *
 */
@Component //注意该类需要交给Spring容器管理
public class MyExceptionResolver implements HandlerExceptionResolver {
  @Override
  public ModelAndView resolveException(HttpServletRequest req
      , HttpServletResponse resp, Object obj,
      Exception ex) {
    System.out.println(ex.getMessage());
    ModelAndView mv = new ModelAndView();
    mv.setViewName("/error.jsp");
    return mv;
  }
}

2.3需要异常处理的地方抛出异常

image.png

2.4测试

image.pngimage.png

三、JSON数据交互

3.1响应JSON数据

1. 添加依赖:

   对于Gson和jackson这两个json处理依赖,直接添加即可。 除此之外,其他的json解析器如fastjson都需要手动配置HttpMessageConverter.

   实际上,在SpringMVC中,是由一个名叫HttpMessageConverter的类来提供对象到JSON字符串的转换的。而SpringMVC默认就提供了Gson和Jackson的HttpMessageConverter,分别是org.springframework.http.converter.json.GsonHttpMessageConverter和MappingJackson2HttpMessageConverter。对于其他的JSON解析器,只需要开发者手动配置一下HttpMessageConverter即可。

   本案例使用 jackson处理

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

image.png

2.在返回对象上添加@ResponseBody注解即可

/**
 * JSON
 * 
 * @author dpb【波波烤鸭】
 *
 */
@Controller
public class UserController {
  @GetMapping("/user")
  @ResponseBody
  public User getUser() {
    User user = new User();
    List<String> favorites = new ArrayList<>();
    favorites.add("足球");
    favorites.add("篮球");
    user.setFavorites(favorites);
    user.setUsername("zhagnsan");
    user.setPassword("123");
    return user;
  }
  @GetMapping("/users")
  @ResponseBody
  public List<User> getALlUser() {
    List<User> users = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      User e = new User();
      e.setUsername("zhangsan:" + i);
      e.setPassword("pwd:" + i);
      users.add(e);
    }
    return users;
  }
  @GetMapping("/map")
  @ResponseBody
  public Map<String, Object> user() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("total", 100);
    map.put("rows", "aaa");
    return map;
  }
}

3.测试

JSON对象

image.png描述JSON数组嵌套

image.png

Map返回JSON数据

image.png额外说明:

默认情况下,JSON处理的HttpMessageConverter在org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter类中,如果当前项目的classpath下有jackson或者gson的依赖,则会被该类自动加载,然后,创建相应的HttpMessageConverter。

对于fastjson,由于系统未提供自动支持,因此需要开发者手动配置fastjson的HttpMessageConverter,配置方式如下:

1.引入fastjson依赖

2.加入配置:

<mvc:annotation-driven validator="validatorFactoryBean">
    <mvc:message-converters>
      <bean
        class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
    </mvc:message-converters>
  </mvc:annotation-driven>

   HttpMessageConverter承担两个事:

   1.将请求结果转为json

   2.将浏览器发送来的json转为对象

3.2 接收JSON数据

   注意:json只能是在请求体中,因此,json只能放在post或者put请求中,注意,请勿使用get/delete请求去测试json参数传递。

   示例代码如下:

/**
 * JSON
 * 
 * @author dpb【波波烤鸭】
 *
 */
@Controller
public class UserController {
  @PostMapping("/test2")
  @ResponseBody
  public void test2(@RequestBody User user) {
    System.out.println(user);
  }
}

通过jquery的ajax发送json数据测试

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
  <input type="button" value="提交JSON数据" onclick="fun1();">
  <script type="text/javascript">
    function fun1(){
      $.ajax({
                type: 'POST',
                url: "test2",
                contentType: "application/json",//如果想以json格式把数据提交到后台的话,这个必须有,否则只会当做表单提交
                data: JSON.stringify({"username":"sam","password":"12"}),//JSON.stringify()必须有,否则只会当做表单的格式提交
                dataType: "json",//期待返回的数据类型
                success: function(data){
                    alert("success:"+data);
                },
                error:function(data){
                    alert("error"+data); 
                }
              });
    }
  </script>
</body>
</html>

image.png服务端获取到了ajax提交的json数据

image.png在springmvc中,直接接收json参数,如果参数中有日期的话,不需要定义日期类型转换器,日期的转换由gson/jackson/fastjson来提供。



相关文章
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
1183 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
1800 0
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
1203 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
1400 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
773 0
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
JSON 人工智能 Go
在Golang中序列化JSON字符串的教程
在Golang中,使用`json.Marshal()`可将数据结构序列化为JSON格式。若直接对JSON字符串进行序列化,会因转义字符导致错误。解决方案包括使用`[]byte`或`json.RawMessage()`来避免双引号被转义,从而正确实现JSON的序列化与反序列化。
924 7
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
1098 0
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
557 0
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
577 0