
引言
在現(xiàn)代Web開發(fā)中,SpringMVC是一個廣泛使用的框架,它提供了豐富的功能和靈活的配置選項。本文將深入探討兩個重要的主題:SpringMVC中的JSON數(shù)據(jù)返回和異常處理機制。我們將逐步介紹相關的配置和使用方法,并通過案例和綜合實例來加深理解。
1. SpringMVC之JSON數(shù)據(jù)返回
1.1 導入依賴
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.3</version>
</dependency>
1.2 配置彈簧-MVC.xml
為了使SpringMVC能夠正確處理JSON數(shù)據(jù)返回,我們需要在配置文件中進行相應的配置。以便正確處理JSON數(shù)據(jù)返回的請求。
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<!--處理中文亂碼以及避免IE執(zhí)行AJAX時,返回JSON出現(xiàn)下載文件-->
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
<value>text/json;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
1.3 @ResponseBody注解使用
@ResponseBody
注解的作用是將Controller的方法返回的對象通過適當?shù)霓D(zhuǎn)換器轉(zhuǎn)換為指定的格式之后,寫入到response對象的body區(qū),通常用來返回JSON
數(shù)據(jù)或者是XML數(shù)據(jù)。
注意:在使用此注解之后不會再走視圖解析器,而是直接將數(shù)據(jù)寫入到輸入流中,他的效果等同于通過response對象輸出指定格式的數(shù)據(jù)。
<select id="selBySnamePager" resultType="com.yuan.model.Student" parameterType="com.yuan.model.Student" >
select
<include refid="Base_Column_List" />
from t_mysql_student
<where>
<if test="sname!=null">
and sname like concat('%',#{sname},'%')
</if>
</where>
</select>
<select id="mapListPager" resultType="java.util.Map" parameterType="com.yuan.model.Student" >
select
<include refid="Base_Column_List" />
from t_mysql_student
<where>
<if test="sname != null">
and sname like concat('%',#{sname},'%')
</if>
</where>
</select>
/**
* 返回List<T>
* @param req
* @param student
* @return
*/
@ResponseBody
@RequestMapping("/list")
public List<Student> list(HttpServletRequest req, Student student){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Student> lst = this.studentBiz.selBySnamePager(student, pageBean);
return lst;
}
/**
* 返回T
* @param req
* @param Student
* @return
*/
@ResponseBody
@RequestMapping("/load")
public Student load(HttpServletRequest req, Student Student){
if(Student.getSname() != null){
List<Student> lst = this.studentBiz.selBySnamePager(Student, null);
return lst.get(0);
}
return null;
}
/**
* 返回List<Map>
* @param req
* @param Student
* @return
*/
@ResponseBody
@RequestMapping("/mapList")
public List<Map> mapList(HttpServletRequest req, Student Student){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Map> lst = this.studentBiz.mapListPager(Student, pageBean);
return lst;
}
/**
* 返回Map
* @param req
* @param Student
* @return
*/
@ResponseBody
@RequestMapping("/mapLoad")
public Map mapLoad(HttpServletRequest req, Student Student){
if(Student.getSname() != null){
List<Map> lst = this.studentBiz.mapListPager(Student, null);
return lst.get(0);
}
return null;
}
@ResponseBody
@RequestMapping("/all")
public Map all(HttpServletRequest req, Student Student){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List<Student> lst = this.studentBiz.selBySnamePager(Student, pageBean);
Map map = new HashMap();
map.put("lst",lst);
map.put("pageBean",pageBean);
return map;
}
@ResponseBody
@RequestMapping("/jsonStr")
public String jsonStr(HttpServletRequest req, Student Student){
return "clzEdit";
}
- @JsonIgnore 隱藏json數(shù)據(jù)中的某個屬性
@ToString
public class Student {
@JsonIgnore
@NotBlank(message = "編號不能為空")
private String sid;
@NotBlank(message = "名字不能為空")
private String sname;
@NotBlank(message = "年齡不能為空")
private String sage;
@NotBlank(message = "性別不能為空")
private String ssex;
1.4.Jackson
- 1.4.1.介紹
? Jackson是一個簡單基于Java應用庫,Jackson可以輕松的將Java對象轉(zhuǎn)換成json對象和xml文檔,同樣也可以將json、xml轉(zhuǎn)換成Java對象。Jackson所依賴的jar包較少,簡單易用并且性能也要相對高些,并且Jackson社區(qū)相對比較活躍,更新速度也比較快。
特點
- 容易使用,提供了高層次外觀,簡化常用的用例。
- 無需創(chuàng)建映射,API提供了默認的映射大部分對象序列化。
- 性能高,快速,低內(nèi)存占用
- 創(chuàng)建干凈的json
- 不依賴其他庫
- 代碼開源
1.4.2.常用注解
注解 | 說明 |
---|---|
@JsonIgnore | 作用在字段或方法上,用來完全忽略被注解的字段和方法對應的屬性 |
@JsonProperty | 作用在字段或方法上,用來對屬性的序列化/反序列化,可以用來避免遺漏屬性,同時提供對屬性名稱重命名 |
@JsonIgnoreProperties | 作用在類上,用來說明有些屬性在序列化/反序列化時需要忽略掉 |
@JsonUnwrapped | 作用在屬性字段或方法上,用來將子JSON對象的屬性添加到封閉的JSON對象 |
@JsonFormat | 指定序列化日期/時間值時的格式 |
2. 異常處理機制
2.1 為什么要全局異常處理
異常處理是一個重要的開發(fā)任務,它可以幫助我們更好地處理程序中的錯誤和異常情況。本節(jié)將介紹為什么我們需要全局異常處理機制,并討論其重要性和優(yōu)勢。
2.2 異常處理思路
系統(tǒng)的dao、service、controller出現(xiàn)異常都通過throws Exception向上拋出,最后由springmvc前端控制器交由異常處理器進行異常處理。springmvc提供全局異常處理器(一個系統(tǒng)只有一個異常處理器)進行統(tǒng)一異常處理。
2.3 SpringMVC異常分類
- 使用Spring MVC提供的簡單異常處理器SimpleMappingExceptionResolver;
- 實現(xiàn)Spring的異常處理接口HandlerExceptionResolver自定義自己的異常處理器;
- 使用@ControllerAdvice + @ExceptionHandler
2.4 綜合案例
通過一個綜合案例,我們將深入了解如何在SpringMVC中處理異常情況。本節(jié)將介紹一個實際的案例,并演示如何使用全局異常處理機制來處理異常。
- 異常處理方式一
SpringMVC中自帶了一個異常處理器叫SimpleMappingExceptionResolver,該處理器實現(xiàn)了HandlerExceptionResolver 接口,全局異常處理器都需要實現(xiàn)該接口。
<!-- springmvc提供的簡單異常處理器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- 定義默認的異常處理頁面 -->
<property name="defaultErrorView" value="error"/>
<!-- 定義異常處理頁面用來獲取異常信息的變量名,也可不定義,默認名為exception -->
<property name="exceptionAttribute" value="ex"/>
<!-- 定義需要特殊處理的異常,這是重要點 -->
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop>
</props>
<!-- 還可以定義其他的自定義異常 -->
</property>
</bean>
- error.jsp
<%--
Created by IntelliJ IDEA.
User: yuanh
Date: 2023/9/13
Time: 16:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
異常
${ex}
</body>
</html>
- 異常代碼
-
運行異常效果
-
異常處理方式二
GlobalException
package com.yuan.exception;
public class GlobalException extends RuntimeException {
public GlobalException() {
}
public GlobalException(String message) {
super(message);
}
public GlobalException(String message, Throwable cause) {
super(message, cause);
}
public GlobalException(Throwable cause) {
super(cause);
}
public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
GlobalExceptionHandler
package com.yuan.Component;
import com.yuan.exception.GlobalException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) {
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
if (e instanceof GlobalException){
GlobalException globalException = (GlobalException) e;
mv.addObject("ex",globalException.getMessage());
mv.addObject("msg","全局異常....");
}else if (e instanceof RuntimeException){
RuntimeException runtimeException = (RuntimeException) e;
mv.addObject("ex",runtimeException.getMessage());
mv.addObject("msg","運行時異常....");
}else {
mv.addObject("ex",e.getMessage());
mv.addObject("msg","其他異常....");
}
return mv;
}
}
異常方法
@ResponseBody
@RequestMapping("/jsonStr")
public String jsonStr(HttpServletRequest req, Student Student){
if(true)
throw new GlobalException("異常123");
return "clzEdit";
}
- 處理異常三@ControllerAdvice
package com.yuan.Component;
import com.yuan.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionResolver {
// 跳轉(zhuǎn)錯誤頁面
// @ExceptionHandler
// public ModelAndView handler(Exception e){
// ModelAndView mv = new ModelAndView();
// mv.setViewName("error");
// if (e instanceof GlobalException){
// GlobalException globalException = (GlobalException) e;
// mv.addObject("ex",globalException.getMessage());
// mv.addObject("msg","全局異常....");
// }else if (e instanceof RuntimeException){
// RuntimeException runtimeException = (RuntimeException) e;
// mv.addObject("ex",runtimeException.getMessage());
// mv.addObject("msg","運行時異常....");
// }
// return mv;
// }
// 返回錯誤json數(shù)據(jù)
@ResponseBody
@ExceptionHandler
public Map handler(Exception e){
Map map = new HashMap();
if (e instanceof GlobalException){
GlobalException globalException = (GlobalException) e;
map.put("ex",globalException.getMessage());
map.put("msg","全局異常....");
}else if (e instanceof RuntimeException){
RuntimeException runtimeException = (RuntimeException) e;
map.put("ex",runtimeException.getMessage());
map.put("msg","運行時異常....");
}else {
map.put("ex",e.getMessage());
map.put("msg","其它異常....");
}
return map;
}
}
文章來源:http://www.zghlxwxcb.cn/news/detail-709582.html
總結(jié)
本文深入探討了SpringMVC中的JSON數(shù)據(jù)返回和異常處理機制。我們從配置和使用方法入手,逐步介紹了相關的知識點,并通過案例和綜合實例加深了理解。希望本文能夠幫助讀者更好地理解和應用SpringMVC中的JSON數(shù)據(jù)返回和異常處理機制。文章來源地址http://www.zghlxwxcb.cn/news/detail-709582.html
到了這里,關于“深入理解SpringMVC的JSON數(shù)據(jù)返回和異常處理機制“的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!