• springMVC之JSON和全局异常处理


    目录

    一、json解析

    1.1 导入pom依赖

    1.2 添加适配器

    1.3 使用注解 完成后台代码

    ①返回JSON字符串

     JsonController 

    index.jsp

    ​编辑

    ②、返回List

    ③、返回List

    ④、返回T

    ⑤、返回Map

    ⑥、返回混合

     二、全局异常处理的三种形式

      2.1 使用springMVC提供的简单异常处理器

    2.2 使用接口

     2.3 使用注解

     三、json统一处理

    一、json解析

    springMVC框架如何产生JSON格式的数据:

            ①、导入pom依赖 Jackson

            ②、配置springMVC.xml 作用:是做JSON数据转换的

            ③、使用注解@responseBody能够将任何数据转成JSON对象

    1.1 导入pom依赖

          com.fasterxml.jackson.core

          jackson-databind

          2.9.3

       

       

          com.fasterxml.jackson.core

          jackson-core

          2.9.3

       

       

          com.fasterxml.jackson.core

          jackson-annotations

          2.9.3

       

     pom.xml

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <parent>
    5. <artifactId>ideamavenartifactId>
    6. <groupId>org.examplegroupId>
    7. <version>1.0-SNAPSHOTversion>
    8. parent>
    9. <modelVersion>4.0.0modelVersion>
    10. <artifactId>ssm2artifactId>
    11. <packaging>warpackaging>
    12. <name>ssm2 Maven Webappname>
    13. <url>http://www.example.comurl>
    14. <properties>
    15. <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    16. <maven.compiler.source>1.8maven.compiler.source>
    17. <maven.compiler.target>1.8maven.compiler.target>
    18. <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
    19. <spring.version>5.0.2.RELEASEspring.version>
    20. <mybatis.version>3.4.5mybatis.version>
    21. <mysql.version>5.1.44mysql.version>
    22. <pagehelper.version>5.1.2pagehelper.version>
    23. <mybatis.spring.version>1.3.1mybatis.spring.version>
    24. <commons.dbcp2.version>2.1.1commons.dbcp2.version>
    25. <commons.pool2.version>2.4.3commons.pool2.version>
    26. <log4j2.version>2.9.1log4j2.version>
    27. <junit.version>4.12junit.version>
    28. <servlet.version>4.0.0servlet.version>
    29. <lombok.version>1.18.2lombok.version>
    30. properties>
    31. <dependencies>
    32. <dependency>
    33. <groupId>org.springframeworkgroupId>
    34. <artifactId>spring-contextartifactId>
    35. <version>${spring.version}version>
    36. dependency>
    37. <dependency>
    38. <groupId>org.springframeworkgroupId>
    39. <artifactId>spring-ormartifactId>
    40. <version>${spring.version}version>
    41. dependency>
    42. <dependency>
    43. <groupId>org.springframeworkgroupId>
    44. <artifactId>spring-txartifactId>
    45. <version>${spring.version}version>
    46. dependency>
    47. <dependency>
    48. <groupId>org.springframeworkgroupId>
    49. <artifactId>spring-aspectsartifactId>
    50. <version>${spring.version}version>
    51. dependency>
    52. <dependency>
    53. <groupId>org.springframeworkgroupId>
    54. <artifactId>spring-webartifactId>
    55. <version>${spring.version}version>
    56. dependency>
    57. <dependency>
    58. <groupId>org.springframeworkgroupId>
    59. <artifactId>spring-testartifactId>
    60. <version>${spring.version}version>
    61. dependency>
    62. <dependency>
    63. <groupId>org.mybatisgroupId>
    64. <artifactId>mybatisartifactId>
    65. <version>${mybatis.version}version>
    66. dependency>
    67. <dependency>
    68. <groupId>mysqlgroupId>
    69. <artifactId>mysql-connector-javaartifactId>
    70. <version>${mysql.version}version>
    71. dependency>
    72. <dependency>
    73. <groupId>com.github.pagehelpergroupId>
    74. <artifactId>pagehelperartifactId>
    75. <version>${pagehelper.version}version>
    76. dependency>
    77. <dependency>
    78. <groupId>org.mybatisgroupId>
    79. <artifactId>mybatis-springartifactId>
    80. <version>${mybatis.spring.version}version>
    81. dependency>
    82. <dependency>
    83. <groupId>org.apache.commonsgroupId>
    84. <artifactId>commons-dbcp2artifactId>
    85. <version>${commons.dbcp2.version}version>
    86. dependency>
    87. <dependency>
    88. <groupId>org.apache.commonsgroupId>
    89. <artifactId>commons-pool2artifactId>
    90. <version>${commons.pool2.version}version>
    91. dependency>
    92. <dependency>
    93. <groupId>org.apache.logging.log4jgroupId>
    94. <artifactId>log4j-coreartifactId>
    95. <version>${log4j2.version}version>
    96. dependency>
    97. <dependency>
    98. <groupId>org.apache.logging.log4jgroupId>
    99. <artifactId>log4j-apiartifactId>
    100. <version>${log4j2.version}version>
    101. dependency>
    102. <dependency>
    103. <groupId>org.apache.logging.log4jgroupId>
    104. <artifactId>log4j-webartifactId>
    105. <version>${log4j2.version}version>
    106. dependency>
    107. <dependency>
    108. <groupId>junitgroupId>
    109. <artifactId>junitartifactId>
    110. <version>${junit.version}version>
    111. <scope>testscope>
    112. dependency>
    113. <dependency>
    114. <groupId>javax.servletgroupId>
    115. <artifactId>javax.servlet-apiartifactId>
    116. <version>${servlet.version}version>
    117. <scope>providedscope>
    118. dependency>
    119. <dependency>
    120. <groupId>org.projectlombokgroupId>
    121. <artifactId>lombokartifactId>
    122. <version>${lombok.version}version>
    123. <scope>providedscope>
    124. dependency>
    125. <dependency>
    126. <groupId>org.springframeworkgroupId>
    127. <artifactId>spring-webmvcartifactId>
    128. <version>${spring.version}version>
    129. dependency>
    130. <dependency>
    131. <groupId>javax.servlet.jspgroupId>
    132. <artifactId>javax.servlet.jsp-apiartifactId>
    133. <version>2.3.3version>
    134. dependency>
    135. <dependency>
    136. <groupId>jstlgroupId>
    137. <artifactId>jstlartifactId>
    138. <version>1.2version>
    139. dependency>
    140. <dependency>
    141. <groupId>taglibsgroupId>
    142. <artifactId>standardartifactId>
    143. <version>1.1.2version>
    144. dependency>
    145. <dependency>
    146. <groupId>commons-fileuploadgroupId>
    147. <artifactId>commons-fileuploadartifactId>
    148. <version>1.3.3version>
    149. dependency>
    150. <dependency>
    151. <groupId>org.hibernategroupId>
    152. <artifactId>hibernate-validatorartifactId>
    153. <version>6.0.7.Finalversion>
    154. dependency>
    155. <dependency>
    156. <groupId>com.fasterxml.jackson.coregroupId>
    157. <artifactId>jackson-databindartifactId>
    158. <version>2.9.3version>
    159. dependency>
    160. <dependency>
    161. <groupId>com.fasterxml.jackson.coregroupId>
    162. <artifactId>jackson-coreartifactId>
    163. <version>2.9.3version>
    164. dependency>
    165. <dependency>
    166. <groupId>com.fasterxml.jackson.coregroupId>
    167. <artifactId>jackson-annotationsartifactId>
    168. <version>2.9.3version>
    169. dependency>
    170. dependencies>
    171. <build>
    172. <finalName>ssm2finalName>
    173. <resources>
    174. <resource>
    175. <directory>src/main/javadirectory>
    176. <includes>
    177. <include>**/*.xmlinclude>
    178. includes>
    179. resource>
    180. <resource>
    181. <directory>src/main/resourcesdirectory>
    182. <includes>
    183. <include>jdbc.propertiesinclude>
    184. <include>*.xmlinclude>
    185. includes>
    186. resource>
    187. resources>
    188. <pluginManagement>
    189. <plugins>
    190. <plugin>
    191. <groupId>org.apache.maven.pluginsgroupId>
    192. <artifactId>maven-compiler-pluginartifactId>
    193. <version>${maven.compiler.plugin.version}version>
    194. <configuration>
    195. <source>${maven.compiler.source}source>
    196. <target>${maven.compiler.target}target>
    197. <encoding>${project.build.sourceEncoding}encoding>
    198. configuration>
    199. plugin>
    200. <plugin>
    201. <groupId>org.mybatis.generatorgroupId>
    202. <artifactId>mybatis-generator-maven-pluginartifactId>
    203. <version>1.3.2version>
    204. <dependencies>
    205. <dependency>
    206. <groupId>mysqlgroupId>
    207. <artifactId>mysql-connector-javaartifactId>
    208. <version>${mysql.version}version>
    209. dependency>
    210. dependencies>
    211. <configuration>
    212. <overwrite>trueoverwrite>
    213. configuration>
    214. plugin>
    215. <plugin>
    216. <artifactId>maven-clean-pluginartifactId>
    217. <version>3.1.0version>
    218. plugin>
    219. <plugin>
    220. <artifactId>maven-resources-pluginartifactId>
    221. <version>3.0.2version>
    222. plugin>
    223. <plugin>
    224. <artifactId>maven-compiler-pluginartifactId>
    225. <version>3.8.0version>
    226. plugin>
    227. <plugin>
    228. <artifactId>maven-surefire-pluginartifactId>
    229. <version>2.22.1version>
    230. plugin>
    231. <plugin>
    232. <artifactId>maven-war-pluginartifactId>
    233. <version>3.2.2version>
    234. plugin>
    235. <plugin>
    236. <artifactId>maven-install-pluginartifactId>
    237. <version>2.5.2version>
    238. plugin>
    239. <plugin>
    240. <artifactId>maven-deploy-pluginartifactId>
    241. <version>2.8.2version>
    242. plugin>
    243. plugins>
    244. pluginManagement>
    245. build>
    246. project>

    1.2 添加适配器

    支持json数据返回的适配器
    1. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    2. <property name="messageConverters">
    3. <list>
    4. <ref bean="mappingJackson2HttpMessageConverter"/>
    5. list>
    6. property>
    7. bean>
    8. <bean id="mappingJackson2HttpMessageConverter"
    9. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    10. <property name="supportedMediaTypes">
    11. <list>
    12. <value>text/html;charset=UTF-8value>
    13. <value>text/json;charset=UTF-8value>
    14. <value>application/json;charset=UTF-8value>
    15. list>
    16. property>
    17. bean>

    springmvc-servlet.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" xmlns:aop="http://www.springframework.org/schema/aop"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    8. <aop:aspectj-autoproxy/>
    9. <context:component-scan base-package="com.cdl"/>
    10. <mvc:annotation-driven>mvc:annotation-driven>
    11. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    12. <property name="viewClass"
    13. value="org.springframework.web.servlet.view.JstlView">property>
    14. <property name="prefix" value="/"/>
    15. <property name="suffix" value=".jsp"/>
    16. bean>
    17. <mvc:resources location="/static/" mapping="/static/**"/>
    18. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    19. <property name="defaultEncoding" value="UTF-8">property>
    20. <property name="maxUploadSize" value="52428800">property>
    21. <property name="resolveLazily" value="true"/>
    22. bean>
    23. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    24. <property name="messageConverters">
    25. <list>
    26. <ref bean="mappingJackson2HttpMessageConverter"/>
    27. list>
    28. property>
    29. bean>
    30. <bean id="mappingJackson2HttpMessageConverter"
    31. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    32. <property name="supportedMediaTypes">
    33. <list>
    34. <value>text/html;charset=UTF-8value>
    35. <value>text/json;charset=UTF-8value>
    36. <value>application/json;charset=UTF-8value>
    37. list>
    38. property>
    39. bean>
    40. beans>

    1.3 使用注解 完成后台代码

    ①返回JSON字符串

    1. package com.cdl.ssm.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. import org.springframework.web.bind.annotation.ResponseBody;
    5. /**
    6. * @author cdl
    7. * @site www.cdl.com
    8. * @create 2022-08-22 16:42
    9. */
    10. @Controller
    11. @RequestMapping("/clz/json")
    12. public class JsonController {
    13. @ResponseBody
    14. @RequestMapping("/clzEdit")
    15. public String clzEdit(){
    16. System.out.println("JsonController.clzEdit");
    17. return "clzEdit";
    18. }
    19. }

    结果:

     返回一个字符串而不是跳一个页面了

    添加一个listMapPager的方法

    在clazzMapper.xml中配置该方法

    1. <select id="listMapPager" parameterType="com.cdl.ssm.model.Clazz" resultType="java.util.Map">
    2. select
    3. <include refid="Base_Column_List" />
    4. from t_struts_class
    5. <where>
    6. <if test="cname != null and cname!= ''">
    7. and cname like CONCAT('%',#{cname},'%')
    8. if>
    9. <if test="cid != null and cid!= ''">
    10. and cid = #{cid}
    11. if>
    12. where>
    13. select>

     ClazzMapper 

    1. package com.cdl.ssm.mapper;
    2. import com.cdl.ssm.model.Clazz;
    3. import org.springframework.stereotype.Repository;
    4. import java.util.List;
    5. import java.util.Map;
    6. @Repository
    7. public interface ClazzMapper {
    8. int deleteByPrimaryKey(Integer cid);
    9. int insert(Clazz record);
    10. int insertSelective(Clazz record);
    11. Clazz selectByPrimaryKey(Integer cid);
    12. List listPager(Clazz clazz);
    13. List listMapPager(Clazz clazz);
    14. int updateByPrimaryKeySelective(Clazz record);
    15. int updateByPrimaryKey(Clazz record);
    16. }

     ClazzBiz 

    1. package com.cdl.ssm.biz;
    2. import com.cdl.ssm.model.Clazz;
    3. import com.cdl.ssm.util.PageBean;
    4. import java.util.List;
    5. import java.util.Map;
    6. public interface ClazzBiz {
    7. int deleteByPrimaryKey(Integer cid);
    8. int insert(Clazz record);
    9. int insertSelective(Clazz record);
    10. Clazz selectByPrimaryKey(Integer cid);
    11. List listPager(Clazz clazz, PageBean pageBean);
    12. int updateByPrimaryKeySelective(Clazz record);
    13. int updateByPrimaryKey(Clazz record);
    14. List listMapPager(Clazz clazz, PageBean pageBean);
    15. }

     ClazzBizImpl 

    1. package com.cdl.ssm.biz.impl;
    2. import com.cdl.ssm.biz.ClazzBiz;
    3. import com.cdl.ssm.mapper.ClazzMapper;
    4. import com.cdl.ssm.model.Clazz;
    5. import com.cdl.ssm.util.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. import java.util.Map;
    10. /**
    11. * @author cdl
    12. * @site www.cdl.com
    13. * @create 2022-08-17 20:22
    14. */
    15. @Service
    16. public class ClazzBizImpl implements ClazzBiz {
    17. @Autowired
    18. private ClazzMapper clazzMapper;
    19. @Override
    20. public int deleteByPrimaryKey(Integer cid) {
    21. return clazzMapper.deleteByPrimaryKey(cid);
    22. }
    23. @Override
    24. public int insert(Clazz record) {
    25. return clazzMapper.insert(record);
    26. }
    27. @Override
    28. public int insertSelective(Clazz record) {
    29. return clazzMapper.insertSelective(record);
    30. }
    31. @Override
    32. public Clazz selectByPrimaryKey(Integer cid) {
    33. return clazzMapper.selectByPrimaryKey(cid);
    34. }
    35. @Override
    36. public List listPager(Clazz clazz, PageBean pageBean) {
    37. List clazzes = clazzMapper.listPager(clazz);
    38. // System.out.println(clazzes);
    39. return clazzes;
    40. }
    41. @Override
    42. public int updateByPrimaryKeySelective(Clazz record) {
    43. return clazzMapper.updateByPrimaryKeySelective(record);
    44. }
    45. @Override
    46. public int updateByPrimaryKey(Clazz record) {
    47. return clazzMapper.updateByPrimaryKey(record);
    48. }
    49. @Override
    50. public List listMapPager(Clazz clazz, PageBean pageBean) {
    51. return clazzMapper.listMapPager(clazz);
    52. }
    53. }

     JsonController 

    1. package com.cdl.ssm.controller;
    2. import com.cdl.ssm.biz.ClazzBiz;
    3. import com.cdl.ssm.model.Clazz;
    4. import com.cdl.ssm.util.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Controller;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.ResponseBody;
    9. import javax.servlet.http.HttpServletRequest;
    10. import java.util.HashMap;
    11. import java.util.List;
    12. import java.util.Map;
    13. /**
    14. * @author cdl
    15. * @site www.cdl.com
    16. * @create 2022-08-22 16:42
    17. */
    18. @Controller
    19. @RequestMapping("/clz/json")
    20. public class JsonController {
    21. @Autowired
    22. private ClazzBiz clazzBiz;
    23. @ResponseBody
    24. @RequestMapping("/clzEdit")
    25. public String clzEdit(){
    26. System.out.println("JsonController.clzEdit");
    27. return "clzEdit";
    28. }
    29. //返回list
    30. @ResponseBody
    31. @RequestMapping("/list")
    32. public List list(HttpServletRequest request,Clazz clazz){
    33. PageBean pageBean = new PageBean();
    34. pageBean.setRequest(request);
    35. return this.clazzBiz.listPager(clazz,pageBean);
    36. }
    37. //返回list
    38. @ResponseBody
    39. @RequestMapping("/listMap")
    40. public List listMap(HttpServletRequest request, Clazz clazz){
    41. PageBean pageBean = new PageBean();
    42. pageBean.setRequest(request);
    43. return this.clazzBiz.listMapPager(clazz,pageBean);
    44. }
    45. //返回单个Map集合
    46. @ResponseBody
    47. @RequestMapping("/map")
    48. public Map map(HttpServletRequest req, Clazz clazz){
    49. PageBean pageBean = new PageBean();
    50. pageBean.setRequest(req);
    51. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    52. }
    53. //T
    54. @ResponseBody
    55. @RequestMapping("/load")
    56. public Clazz load(HttpServletRequest req, Clazz clazz){
    57. PageBean pageBean = new PageBean();
    58. pageBean.setRequest(req);
    59. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    60. }
    61. //混合
    62. @ResponseBody
    63. @RequestMapping("/hunhe")
    64. public Map hunhe(HttpServletRequest req, Clazz clazz){
    65. PageBean pageBean = new PageBean();
    66. pageBean.setRequest(req);
    67. List lst = this.clazzBiz.listPager(clazz, pageBean);
    68. Map map = new HashMap();
    69. map.put("data",lst);
    70. map.put("pagebean",pageBean);
    71. return map;
    72. }
    73. }

    index.jsp

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: Lenovo
    4. Date: 2022/8/19
    5. Time: 20:33
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. <html>
    10. <head>
    11. <title>测试json数据返回title>
    12. head>
    13. <body>
    14. <a href="${pageContext.request.contextPath}/clz/json/list">返回list<T>对象a><hr>
    15. <a href="${pageContext.request.contextPath}/clz/json/listMap">返回list<Map>对象a><hr>
    16. <a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回T对象a><hr>
    17. <a href="${pageContext.request.contextPath}/clz/json/map?cid=1">返回map对象a><hr>
    18. <a href="${pageContext.request.contextPath}/clz/json/hunhe">返回混合对象a><hr>
    19. body>
    20. html>

    ②、返回List

    ③、返回List

    ④、返回T

    ⑤、返回Map

    ⑥、返回混合

     二、全局异常处理的三种形式

    @ResponseBody+@Controller=@RestController

    为什么要用全局异常处理:

            在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护

     JsonController 

    1. package com.cdl.ssm.controller;
    2. import com.cdl.ssm.biz.ClazzBiz;
    3. import com.cdl.ssm.model.Clazz;
    4. import com.cdl.ssm.util.PageBean;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import javax.servlet.http.HttpServletRequest;
    9. import java.util.HashMap;
    10. import java.util.List;
    11. import java.util.Map;
    12. /**
    13. * @author cdl
    14. * @site www.cdl.com
    15. * @create 2022-08-22 16:42
    16. */
    17. @RestController
    18. @RequestMapping("/clz/json")
    19. public class JsonController {
    20. @Autowired
    21. private ClazzBiz clazzBiz;
    22. @RequestMapping("/clzEdit")
    23. public String clzEdit(){
    24. System.out.println("JsonController.clzEdit");
    25. return "clzEdit";
    26. }
    27. //返回list
    28. @RequestMapping("/list")
    29. public List list(HttpServletRequest request,Clazz clazz){
    30. PageBean pageBean = new PageBean();
    31. pageBean.setRequest(request);
    32. if (true)
    33. throw new RuntimeException("查询异常,错误出现在 JsonController.list...");
    34. return this.clazzBiz.listPager(clazz,pageBean);
    35. }
    36. //返回list
    37. @RequestMapping("/listMap")
    38. public List listMap(HttpServletRequest request, Clazz clazz){
    39. PageBean pageBean = new PageBean();
    40. pageBean.setRequest(request);
    41. return this.clazzBiz.listMapPager(clazz,pageBean);
    42. }
    43. //返回单个Map集合
    44. @RequestMapping("/map")
    45. public Map map(HttpServletRequest req, Clazz clazz){
    46. PageBean pageBean = new PageBean();
    47. pageBean.setRequest(req);
    48. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    49. }
    50. //T
    51. @RequestMapping("/load")
    52. public Clazz load(HttpServletRequest req, Clazz clazz){
    53. PageBean pageBean = new PageBean();
    54. pageBean.setRequest(req);
    55. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    56. }
    57. //混合
    58. @RequestMapping("/hunhe")
    59. public Map hunhe(HttpServletRequest req, Clazz clazz){
    60. PageBean pageBean = new PageBean();
    61. pageBean.setRequest(req);
    62. List lst = this.clazzBiz.listPager(clazz, pageBean);
    63. Map map = new HashMap();
    64. map.put("data",lst);
    65. map.put("pagebean",pageBean);
    66. return map;
    67. }
    68. }

     ClazzBizImpl 

    1. package com.cdl.ssm.biz.impl;
    2. import com.cdl.ssm.biz.ClazzBiz;
    3. import com.cdl.ssm.mapper.ClazzMapper;
    4. import com.cdl.ssm.model.Clazz;
    5. import com.cdl.ssm.util.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.stereotype.Service;
    8. import java.util.List;
    9. import java.util.Map;
    10. /**
    11. * @author cdl
    12. * @site www.cdl.com
    13. * @create 2022-08-17 20:22
    14. */
    15. @Service
    16. public class ClazzBizImpl implements ClazzBiz {
    17. @Autowired
    18. private ClazzMapper clazzMapper;
    19. @Override
    20. public int deleteByPrimaryKey(Integer cid) {
    21. return clazzMapper.deleteByPrimaryKey(cid);
    22. }
    23. @Override
    24. public int insert(Clazz record) {
    25. return clazzMapper.insert(record);
    26. }
    27. @Override
    28. public int insertSelective(Clazz record) {
    29. return clazzMapper.insertSelective(record);
    30. }
    31. @Override
    32. public Clazz selectByPrimaryKey(Integer cid) {
    33. return clazzMapper.selectByPrimaryKey(cid);
    34. }
    35. @Override
    36. public List listPager(Clazz clazz, PageBean pageBean) {
    37. List clazzes = clazzMapper.listPager(clazz);
    38. // System.out.println(clazzes);
    39. return clazzes;
    40. }
    41. @Override
    42. public int updateByPrimaryKeySelective(Clazz record) {
    43. return clazzMapper.updateByPrimaryKeySelective(record);
    44. }
    45. @Override
    46. public int updateByPrimaryKey(Clazz record) {
    47. return clazzMapper.updateByPrimaryKey(record);
    48. }
    49. @Override
    50. public List listMapPager(Clazz clazz, PageBean pageBean) {
    51. if (true)
    52. throw new RuntimeException("查询异常,错误出现在 ClazzBizImpl.list...");
    53. return clazzMapper.listMapPager(clazz);
    54. }
    55. }

     

     这样标记异常很不方便,所以我们要采用springMVC的三种异常处理方式

    1、配置springmvc.xml使用SpringMVC提供的简单异常处理器SimpleMappingExceptionResolver;

    2、实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;

    3、使用@ControllerAdvice + @ExceptionHandler

      2.1 使用springMVC提供的简单异常处理器

       

           

           

           

           

           

           

               

                    error

               

               

           

       

    springmvc-servlet.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" xmlns:aop="http://www.springframework.org/schema/aop"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    8. <aop:aspectj-autoproxy/>
    9. <context:component-scan base-package="com.cdl"/>
    10. <mvc:annotation-driven>mvc:annotation-driven>
    11. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    12. <property name="viewClass"
    13. value="org.springframework.web.servlet.view.JstlView">property>
    14. <property name="prefix" value="/"/>
    15. <property name="suffix" value=".jsp"/>
    16. bean>
    17. <mvc:resources location="/static/" mapping="/static/**"/>
    18. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    19. <property name="defaultEncoding" value="UTF-8">property>
    20. <property name="maxUploadSize" value="52428800">property>
    21. <property name="resolveLazily" value="true"/>
    22. bean>
    23. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    24. <property name="messageConverters">
    25. <list>
    26. <ref bean="mappingJackson2HttpMessageConverter"/>
    27. list>
    28. property>
    29. bean>
    30. <bean id="mappingJackson2HttpMessageConverter"
    31. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    32. <property name="supportedMediaTypes">
    33. <list>
    34. <value>text/html;charset=UTF-8value>
    35. <value>text/json;charset=UTF-8value>
    36. <value>application/json;charset=UTF-8value>
    37. list>
    38. property>
    39. bean>
    40. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    41. <property name="defaultErrorView" value="error"/>
    42. <property name="exceptionAttribute" value="ex"/>
    43. <property name="exceptionMappings">
    44. <props>
    45. <prop key="java.lang.RuntimeException">errorprop>
    46. props>
    47. property>
    48. bean>
    49. beans>

     error.jsp

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>错误信息页面title>
    5. head>
    6. <body>
    7. ${ex}
    8. body>
    9. html>

     

     因为不太灵活,采取第二中方式

    2.2 使用接口

    把统一异常处理注了,以免产生冲突 

     GlobalException 

    1. package com.cdl.ssm.exception;
    2. /**
    3. * @author cdl
    4. * @site www.cdl.com
    5. * @create 2022-08-22 20:05
    6. */
    7. public class GlobalException extends RuntimeException{
    8. public GlobalException() {
    9. }
    10. public GlobalException(String message) {
    11. super(message);
    12. }
    13. public GlobalException(String message, Throwable cause) {
    14. super(message, cause);
    15. }
    16. public GlobalException(Throwable cause) {
    17. super(cause);
    18. }
    19. public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    20. super(message, cause, enableSuppression, writableStackTrace);
    21. }
    22. }

     GlobalHandlerExceptionResovler 

    1. package com.cdl.ssm.exception;
    2. import org.springframework.stereotype.Component;
    3. import org.springframework.web.servlet.HandlerExceptionResolver;
    4. import org.springframework.web.servlet.ModelAndView;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletResponse;
    7. /**
    8. * @author cdl
    9. * @site www.cdl.com
    10. * @create 2022-08-22 20:15
    11. *
    12. * 处理全局异常的解析器
    13. */
    14. @Component
    15. public class GlobalHandlerExceptionResovler implements HandlerExceptionResolver {
    16. /**
    17. *
    18. * @param httpServletRequest
    19. * @param httpServletResponse
    20. * @param o 目标对象
    21. * @param e 目标对象执行出现的异常对象
    22. * @return
    23. */
    24. @Override
    25. public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    26. ModelAndView mv = new ModelAndView();
    27. mv.setViewName("error");
    28. if(e instanceof GlobalException){
    29. GlobalException exception =(GlobalException) e;
    30. mv.addObject("ex",exception.getMessage());
    31. mv.addObject("msg","全局异常,错误码203");
    32. } else if(e instanceof RuntimeException){
    33. RuntimeException exception =(RuntimeException) e;
    34. mv.addObject("ex",exception.getMessage());
    35. mv.addObject("msg","运行异常,错误码503");
    36. }
    37. return mv;
    38. }
    39. }

     JsonController 

    1. package com.cdl.ssm.controller;
    2. import com.cdl.ssm.biz.ClazzBiz;
    3. import com.cdl.ssm.exception.GlobalException;
    4. import com.cdl.ssm.model.Clazz;
    5. import com.cdl.ssm.util.PageBean;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.web.bind.annotation.RestController;
    9. import javax.servlet.http.HttpServletRequest;
    10. import java.util.HashMap;
    11. import java.util.List;
    12. import java.util.Map;
    13. /**
    14. * @author cdl
    15. * @site www.cdl.com
    16. * @create 2022-08-22 16:42
    17. */
    18. @RestController
    19. @RequestMapping("/clz/json")
    20. public class JsonController {
    21. @Autowired
    22. private ClazzBiz clazzBiz;
    23. @RequestMapping("/clzEdit")
    24. public String clzEdit(){
    25. System.out.println("JsonController.clzEdit");
    26. return "clzEdit";
    27. }
    28. //返回list
    29. @RequestMapping("/list")
    30. public List list(HttpServletRequest request,Clazz clazz){
    31. PageBean pageBean = new PageBean();
    32. pageBean.setRequest(request);
    33. if (true)
    34. throw new RuntimeException("查询异常,错误出现在 JsonController.list...");
    35. return this.clazzBiz.listPager(clazz,pageBean);
    36. }
    37. //返回list
    38. @RequestMapping("/listMap")
    39. public List listMap(HttpServletRequest request, Clazz clazz){
    40. PageBean pageBean = new PageBean();
    41. pageBean.setRequest(request);
    42. return this.clazzBiz.listMapPager(clazz,pageBean);
    43. }
    44. //返回单个Map集合
    45. @RequestMapping("/map")
    46. public Map map(HttpServletRequest req, Clazz clazz){
    47. PageBean pageBean = new PageBean();
    48. pageBean.setRequest(req);
    49. return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
    50. }
    51. //T
    52. @RequestMapping("/load")
    53. public Clazz load(HttpServletRequest req, Clazz clazz){
    54. PageBean pageBean = new PageBean();
    55. pageBean.setRequest(req);
    56. if(true)
    57. throw new GlobalException("系统繁忙,请参考E007;");
    58. return this.clazzBiz.listPager(clazz,pageBean).get(0);
    59. }
    60. //混合
    61. @RequestMapping("/hunhe")
    62. public Map hunhe(HttpServletRequest req, Clazz clazz){
    63. PageBean pageBean = new PageBean();
    64. pageBean.setRequest(req);
    65. List lst = this.clazzBiz.listPager(clazz, pageBean);
    66. Map map = new HashMap();
    67. map.put("data",lst);
    68. map.put("pagebean",pageBean);
    69. return map;
    70. }
    71. }

    error.jsp

    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>错误信息页面title>
    5. head>
    6. <body>
    7. ${msg}
    8. <hr>
    9. ${ex}
    10. body>
    11. html>

     

     点击出现以下两种结果

     

     2.3 使用注解

    为了不受使用接口的影响

     

    如图注释 

     GlobalExceptionResolver 

    1. package com.cdl.ssm.exception;
    2. import org.springframework.web.bind.annotation.ControllerAdvice;
    3. import org.springframework.web.bind.annotation.ExceptionHandler;
    4. import org.springframework.web.servlet.ModelAndView;
    5. /**
    6. * @author cdl
    7. * @site www.cdl.com
    8. * @create 2022-08-24 8:55
    9. */
    10. @ControllerAdvice
    11. public class GlobalExceptionResolver {
    12. @ExceptionHandler
    13. public ModelAndView handler(Exception e){
    14. ModelAndView mv = new ModelAndView();
    15. mv.setViewName("error");
    16. if(e instanceof GlobalException){
    17. GlobalException exception =(GlobalException) e;
    18. mv.addObject("ex",exception.getMessage());
    19. mv.addObject("msg","GlobalExceptionResolver全局异常,错误码203");
    20. } else if(e instanceof RuntimeException){
    21. RuntimeException exception =(RuntimeException) e;
    22. mv.addObject("ex",exception.getMessage());
    23. mv.addObject("msg","GlobalExceptionResolver运行异常,错误码503");
    24. }
    25. return mv;
    26. }
    27. }

     点击出现两种结果

     

     三、json统一处理

    GlobalExceptionResolver2 

    1. package com.cdl.ssm.exception;
    2. import org.springframework.web.bind.annotation.ExceptionHandler;
    3. import org.springframework.web.bind.annotation.RestControllerAdvice;
    4. import java.util.HashMap;
    5. import java.util.Map;
    6. /**
    7. * @author cdl
    8. * @site www.cdl.com
    9. * @create 2022-08-24 8:55
    10. *
    11. * 当出现异常,统一向前端响应错误信息的JSON对象数据
    12. */
    13. @RestControllerAdvice
    14. public class GlobalExceptionResolver2 {
    15. @ExceptionHandler
    16. public Map handler(Exception e){
    17. Map map = new HashMap();
    18. if(e instanceof GlobalException){
    19. GlobalException exception =(GlobalException) e;
    20. map.put("ex",exception.getMessage());
    21. map.put("msg","GlobalExceptionResolver2全局异常,错误码203");
    22. } else if(e instanceof RuntimeException){
    23. RuntimeException exception =(RuntimeException) e;
    24. map.put("ex",exception.getMessage());
    25. map.put("msg","GlobalExceptionResolver2运行异常,错误码503");
    26. }
    27. return map;
    28. }
    29. }

     出现以下两种结果

     

     

  • 相关阅读:
    UE4 关卡蓝图实现开关门
    Mysql JSON对象和JSON数组查询
    计算机毕业设计JAVA二手物品置换平台mybatis+源码+调试部署+系统+数据库+lw
    C++项目实战——基于多设计模式下的同步&异步日志系统-⑫-日志宏&全局接口设计(代理模式)
    mysql笔记:10. 日志
    SpringBoot 整合【MybatisPlus、Shiro】实现权限认证信息
    WordPress还是Shopify?如何选择最适合您业务的网站建设平台?
    数学建模:模糊综合评价分析
    记录QEMU上模拟ARM运行环境(内核 2.6.30)
    【RocketMQ】【源码】延迟消息实现原理
  • 原文地址:https://blog.csdn.net/weixin_62735525/article/details/126468559