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来提供。



相关文章
|
1天前
|
存储 JSON JavaScript
使用JSONObject解析与生成JSON数据
使用JSONObject解析与生成JSON数据
|
1天前
|
前端开发 Java Spring
Spring MVC中使用ModelAndView传递数据
Spring MVC中使用ModelAndView传递数据
|
1天前
|
JSON 前端开发 JavaScript
Go怎么解析不定JSON数据?
在Go中处理不确定结构的JSON数据,可以使用`map[string]interface{}`来解析,它能适应各种JSON键值对,但需要类型检查。另一种方法是使用`json.RawMessage`保存原始JSON,之后按需解析。此外,`json.Number`用于处理任意精度的数字。当JSON字段类型未知时,可以先解码到`interface{}`并做类型断言。第三方库如gjson和jsonparser提供更灵活的解析选项。
序-Servlet和SpringMVC的联系和区别-配置路径先想好使用的使用的方法,然后匹配的需要的技术
序-Servlet和SpringMVC的联系和区别-配置路径先想好使用的使用的方法,然后匹配的需要的技术
|
5天前
|
存储 JSON NoSQL
深入解析RedisJSON:在Redis中直接处理JSON数据
深入解析RedisJSON:在Redis中直接处理JSON数据
|
5天前
|
JSON Go 数据格式
技术经验分享:Golang如何解组嵌套的JSON数据的子集
技术经验分享:Golang如何解组嵌套的JSON数据的子集
|
5天前
|
JSON 前端开发 数据格式
SpringMVC的数据响应-直接回写json字符串
SpringMVC的数据响应-直接回写json字符串
|
5天前
|
XML JSON 前端开发
JSON——IT技术人员都必须要了解的一种数据交换格式
JSON——IT技术人员都必须要了解的一种数据交换格式
|
6天前
|
XML 前端开发 Java
SpringMVC的架构有什么优势?——异常处理与文件上传(五)
SpringMVC的架构有什么优势?——异常处理与文件上传(五)
|
6天前
|
前端开发 Java API
SpringMVC的架构有什么优势?——控制器(三)
SpringMVC的架构有什么优势?——控制器(三)