• SpringMVC之JSON返回&异常处理机制


    • json处理
    • 统一异常处理

    1.json处理

    1. //pom.xml
    2. "1.0" encoding="UTF-8"?>
    3. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. 4.0.0
    6. org.example
    7. zljzyssm
    8. 1.0-SNAPSHOT
    9. war
    10. zljzyssm Maven Webapp
    11. http://www.example.com
    12. UTF-8
    13. 1.8
    14. 1.8
    15. 3.7.0
    16. 5.0.2.RELEASE
    17. 3.4.5
    18. 5.1.44
    19. 5.1.2
    20. 1.3.1
    21. 2.1.1
    22. 2.4.3
    23. 2.9.1
    24. 3.2.0
    25. 1.7.13
    26. 4.12
    27. 4.0.0
    28. 1.18.2
    29. 1.1.0
    30. 2.10.0
    31. 2.9.0
    32. 1.7.1.RELEASE
    33. 2.9.3
    34. 1.2
    35. 1.1.2
    36. 8.0.47
    37. 1.3.3
    38. 5.0.2.Final
    39. 1.3.2
    40. org.springframework
    41. spring-core
    42. ${spring.version}
    43. org.springframework
    44. spring-beans
    45. ${spring.version}
    46. org.springframework
    47. spring-context
    48. ${spring.version}
    49. org.springframework
    50. spring-orm
    51. ${spring.version}
    52. org.springframework
    53. spring-tx
    54. ${spring.version}
    55. org.springframework
    56. spring-aspects
    57. ${spring.version}
    58. org.springframework
    59. spring-web
    60. ${spring.version}
    61. org.springframework
    62. spring-test
    63. ${spring.version}
    64. org.mybatis
    65. mybatis
    66. ${mybatis.version}
    67. mysql
    68. mysql-connector-java
    69. ${mysql.version}
    70. com.github.pagehelper
    71. pagehelper
    72. ${pagehelper.version}
    73. org.mybatis
    74. mybatis-spring
    75. ${mybatis.spring.version}
    76. org.springframework
    77. spring-context-support
    78. ${spring.version}
    79. org.mybatis.caches
    80. mybatis-ehcache
    81. ${mybatis.ehcache.version}
    82. net.sf.ehcache
    83. ehcache
    84. ${ehcache.version}
    85. redis.clients
    86. jedis
    87. ${redis.version}
    88. org.springframework.data
    89. spring-data-redis
    90. ${redis.spring.version}
    91. com.fasterxml.jackson.core
    92. jackson-databind
    93. ${jackson.version}
    94. com.fasterxml.jackson.core
    95. jackson-core
    96. ${jackson.version}
    97. com.fasterxml.jackson.core
    98. jackson-annotations
    99. ${jackson.version}
    100. org.apache.commons
    101. commons-dbcp2
    102. ${commons.dbcp2.version}
    103. commons-pool2
    104. org.apache.commons
    105. org.apache.commons
    106. commons-pool2
    107. ${commons.pool2.version}
    108. org.springframework
    109. spring-webmvc
    110. ${spring.version}
    111. org.slf4j
    112. slf4j-api
    113. ${slf4j.version}
    114. org.slf4j
    115. jcl-over-slf4j
    116. ${slf4j.version}
    117. runtime
    118. org.apache.logging.log4j
    119. log4j-api
    120. ${log4j2.version}
    121. org.apache.logging.log4j
    122. log4j-core
    123. ${log4j2.version}
    124. org.apache.logging.log4j
    125. log4j-slf4j-impl
    126. ${log4j2.version}
    127. org.apache.logging.log4j
    128. log4j-web
    129. ${log4j2.version}
    130. runtime
    131. com.lmax
    132. disruptor
    133. ${log4j2.disruptor.version}
    134. junit
    135. junit
    136. ${junit.version}
    137. javax.servlet
    138. javax.servlet-api
    139. ${servlet.version}
    140. provided
    141. org.projectlombok
    142. lombok
    143. ${lombok.version}
    144. provided
    145. jstl
    146. jstl
    147. ${jstl.version}
    148. taglibs
    149. standard
    150. ${standard.version}
    151. org.apache.tomcat
    152. tomcat-jsp-api
    153. ${tomcat-jsp-api.version}
    154. commons-fileupload
    155. commons-fileupload
    156. ${commons-fileupload.version}
    157. org.hibernate
    158. hibernate-validator
    159. ${hibernate-validator.version}
    160. org.apache.shiro
    161. shiro-core
    162. ${shiro.version}
    163. org.apache.shiro
    164. shiro-web
    165. ${shiro.version}
    166. org.apache.shiro
    167. shiro-spring
    168. ${shiro.version}
    169. zljzyssm
    170. src/main/java
    171. **/*.xml
    172. src/main/resources
    173. jdbc.properties
    174. *.xml
    175. org.apache.maven.plugins
    176. maven-compiler-plugin
    177. ${maven.compiler.plugin.version}
    178. ${maven.compiler.source}
    179. ${maven.compiler.target}
    180. ${project.build.sourceEncoding}
    181. org.mybatis.generator
    182. mybatis-generator-maven-plugin
    183. 1.3.2
    184. mysql
    185. mysql-connector-java
    186. ${mysql.version}
    187. true
    1. package com.zlj.model;
    2. import com.fasterxml.jackson.annotation.JsonIgnore;
    3. import lombok.ToString;
    4. import org.hibernate.validator.constraints.NotBlank;
    5. import javax.validation.constraints.NotNull;
    6. @ToString
    7. public class Stu {
    8. @NotNull(message = "学生编号不能为空")
    9. // @Size(max = 100,min = 10,message = "大小必须在10至100之间")
    10. protected Integer sid;
    11. @NotBlank(message = "学生名不能为空")
    12. protected String same;
    13. @NotBlank(message = "学生年龄不能为空")
    14. protected Integer sage;
    15. @JsonIgnore
    16. private String spic="暂无图片";
    17. public Stu(Integer sid, String same, Integer sage, String spic) {
    18. this.sid = sid;
    19. this.same = same;
    20. this.sage = sage;
    21. this.spic = spic;
    22. }
    23. public Integer getSid() {
    24. return sid;
    25. }
    26. public void setSid(Integer sid) {
    27. this.sid = sid;
    28. }
    29. public String getSame() {
    30. return same;
    31. }
    32. public void setSame(String same) {
    33. this.same = same;
    34. }
    35. public Integer getSage() {
    36. return sage;
    37. }
    38. public void setSage(Integer sage) {
    39. this.sage = sage;
    40. }
    41. public String getSpic() {
    42. return spic;
    43. }
    44. public void setSpic(String spic) {
    45. this.spic = spic;
    46. }
    47. public Stu() {
    48. }
    49. }

    stu类里@JsonIgnore:隐藏信息  

    1. //StuMapper.xml
    2. "1.0" encoding="UTF-8" ?>
    3. "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    4. "com.zlj.mapper.StuMapper" >
    5. "BaseResultMap" type="com.zlj.model.Stu" >
    6. "sid" jdbcType="INTEGER" javaType="java.lang.Integer" />
    7. "same" jdbcType="VARCHAR" javaType="java.lang.String" />
    8. "sage" jdbcType="INTEGER" javaType="java.lang.Integer" />
    9. "spic" jdbcType="VARCHAR" javaType="java.lang.String" />
    10. "Base_Column_List" >
    11. sid, same, sage, spic
    12. "deleteByPrimaryKey" parameterType="java.lang.Integer" >
    13. delete from student
    14. where sid = #{sid,jdbcType=INTEGER}
    15. "insert" parameterType="com.zlj.model.Stu" >
    16. insert into student (sid, same, sage,
    17. spic)
    18. values (#{sid,jdbcType=INTEGER}, #{same,jdbcType=VARCHAR}, #{sage,jdbcType=INTEGER},
    19. #{spic,jdbcType=VARCHAR})
    20. "insertSelective" parameterType="com.zlj.model.Stu" >
    21. insert into student
    22. "(" suffix=")" suffixOverrides="," >
    23. <if test="sid != null" >
    24. sid,
    25. if>
    26. <if test="same != null" >
    27. same,
    28. if>
    29. <if test="sage != null" >
    30. sage,
    31. if>
    32. <if test="spic != null" >
    33. spic,
    34. if>
    35. "values (" suffix=")" suffixOverrides="," >
    36. <if test="sid != null" >
    37. #{sid,jdbcType=INTEGER},
    38. if>
    39. <if test="same != null" >
    40. #{same,jdbcType=VARCHAR},
    41. if>
    42. <if test="sage != null" >
    43. #{sage,jdbcType=INTEGER},
    44. if>
    45. <if test="spic != null" >
    46. #{spic,jdbcType=VARCHAR},
    47. if>
    48. "updateByPrimaryKeySelective" parameterType="com.zlj.model.Stu" >
    49. update student
    50. <if test="same != null" >
    51. same = #{same,jdbcType=VARCHAR},
    52. if>
    53. <if test="sage != null" >
    54. sage = #{sage,jdbcType=INTEGER},
    55. if>
    56. <if test="spic != null" >
    57. spic = #{spic,jdbcType=VARCHAR},
    58. if>
    59. where sid = #{sid,jdbcType=INTEGER}
    60. "updateByPrimaryKey" parameterType="com.zlj.model.Stu" >
    61. update student
    62. set same = #{same,jdbcType=VARCHAR},
    63. sage = #{sage,jdbcType=INTEGER},
    64. spic = #{spic,jdbcType=VARCHAR}
    65. where sid = #{sid,jdbcType=INTEGER}
    1. package com.zlj.mapper;
    2. import com.zlj.model.Stu;
    3. import org.springframework.stereotype.Repository;
    4. import java.util.List;
    5. import java.util.Map;
    6. @Repository
    7. public interface StuMapper {
    8. int deleteByPrimaryKey(Integer sid);
    9. int insert(Stu record);
    10. int insertSelective(Stu record);
    11. Stu selectByPrimaryKey(Integer sid);
    12. int updateByPrimaryKeySelective(Stu record);
    13. int updateByPrimaryKey(Stu record);
    14. List selectByCon(Stu stu);
    15. List mapListPager(Stu stu, Object o);
    16. }
    1. package com.zlj.biz;
    2. import com.zlj.model.Stu;
    3. import com.zlj.util.PageBean;
    4. import java.util.List;
    5. import java.util.Map;
    6. /**
    7. * @author zlj
    8. * @create 2023-09-07 17:09
    9. */
    10. public interface StuBiz {
    11. int deleteByPrimaryKey(Integer sid);
    12. int insert(Stu record);
    13. int insertSelective(Stu record);
    14. Stu selectByPrimaryKey(Integer sid);
    15. int updateByPrimaryKeySelective(Stu record);
    16. int updateByPrimaryKey(Stu record);
    17. List ListPager(Stu stu, PageBean PageBean);
    18. List mapListPager(Stu stu, Object o);
    19. }
    1. package com.zlj.biz.Impl;
    2. import com.zlj.biz.StuBiz;
    3. import com.zlj.mapper.StuMapper;
    4. import com.zlj.model.Stu;
    5. import com.zlj.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 zlj
    12. * @create 2023-09-08 14:52
    13. */
    14. @Service
    15. public class StuBizImpl implements StuBiz {
    16. @Autowired
    17. private StuMapper stuMapper;
    18. @Override
    19. public int deleteByPrimaryKey(Integer sid) {
    20. return stuMapper.deleteByPrimaryKey(sid);
    21. }
    22. @Override
    23. public int insert(Stu record) {
    24. return stuMapper.insert(record);
    25. }
    26. @Override
    27. public int insertSelective(Stu record) {
    28. return stuMapper.insertSelective(record);
    29. }
    30. @Override
    31. public Stu selectByPrimaryKey(Integer sid) {
    32. return stuMapper.selectByPrimaryKey(sid);
    33. }
    34. @Override
    35. public int updateByPrimaryKeySelective(Stu record) {
    36. return stuMapper.updateByPrimaryKeySelective(record);
    37. }
    38. @Override
    39. public int updateByPrimaryKey(Stu record) {
    40. return stuMapper.updateByPrimaryKey(record);
    41. }
    42. @Override
    43. public List ListPager(Stu stu, PageBean pageBean) {
    44. return stuMapper.selectByCon(stu);
    45. }
    46. @Override
    47. public List mapListPager(Stu stu, Object o) {
    48. return stuMapper.mapListPager(stu,o);
    49. }
    50. }

     

    1. package com.zlj.web;
    2. import com.zlj.biz.StuBiz;
    3. import com.zlj.model.Stu;
    4. import com.zlj.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. //@ResponseBody
    13. //@Controller
    14. @RestController //@RestController=@ResponseBody+@Controller
    15. @RequestMapping("/stu/json")
    16. public class JsonController {
    17. @Autowired
    18. private StuBiz stuBiz;
    19. /**
    20. * 返回List
    21. * @param req
    22. * @param stu
    23. * @return
    24. */
    25. // @ResponseBody
    26. @RequestMapping("/list")
    27. public List list(HttpServletRequest req, Stu stu){
    28. PageBean pageBean = new PageBean();
    29. pageBean.setRequest(req);
    30. List lst = this.stuBiz.ListPager(stu, pageBean);
    31. return lst;
    32. }
    33. /**
    34. * 返回T
    35. * @param req
    36. * @param stu
    37. * @return
    38. */
    39. // @ResponseBody
    40. @RequestMapping("/load")
    41. public Stu load(HttpServletRequest req, Stu stu){
    42. if(stu.getSid() != null){
    43. List lst = this.stuBiz.ListPager(stu, null);
    44. return lst.get(0);
    45. }
    46. return null;
    47. }
    48. /**
    49. * 返回List
    50. * @param req
    51. * @param stu
    52. * @return
    53. */
    54. // @ResponseBody
    55. @RequestMapping("/mapList")
    56. public List mapList(HttpServletRequest req, Stu stu){
    57. PageBean pageBean = new PageBean();
    58. pageBean.setRequest(req);
    59. List lst = this.stuBiz.mapListPager(stu, pageBean);
    60. return lst;
    61. }
    62. /**
    63. * 返回Map
    64. * @param req
    65. * @param stu
    66. * @return
    67. */
    68. // @ResponseBody
    69. @RequestMapping("/mapLoad")
    70. public Map mapLoad(HttpServletRequest req, Stu stu){
    71. if(stu.getSid() != null){
    72. List lst = this.stuBiz.mapListPager(stu, null);
    73. return lst.get(0);
    74. }
    75. return null;
    76. }
    77. // @ResponseBody
    78. @RequestMapping("/all")
    79. public Map all(HttpServletRequest req, Stu stu){
    80. PageBean pageBean = new PageBean();
    81. pageBean.setRequest(req);
    82. List lst = this.stuBiz.ListPager(stu, pageBean);
    83. Map map = new HashMap();
    84. map.put("lst",lst);
    85. map.put("pageBean",pageBean);
    86. return map;
    87. }
    88. // @ResponseBody //返回单个字符串,而不是页面
    89. @RequestMapping("/jsonStr")
    90. public String jsonStr(HttpServletRequest req, Stu stu){
    91. System.out.println("333.....");
    92. return "stuEdit";
    93. }
    94. }

    @RestController=@ResponseBody+@Controller

    2.统一异常处理

    为什么要全局异常处理

    我们知道,系统中异常包括:编译时异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。在开发中,不管是dao层、service层还是controller层,都有可能抛出异常,在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护。

    异常处理思路

    系统的dao、service、controller出现异常都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理。springmvc提供全局异常处理器(一个系统只有一个异常处理器)进行统一异常处理

    处理异常方式一演示(StuBizImpl的mapList方法加 stu=null; System.out.println(stu.getSame();--------jsonCotrollor的list方法加)System.out.println(1 / 0);),spring-mvc.xml配置,建一个error.jsp页面,分别报两个错

    1. package com.zlj.biz.Impl;
    2. import com.zlj.biz.StuBiz;
    3. import com.zlj.mapper.StuMapper;
    4. import com.zlj.model.Stu;
    5. import com.zlj.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 zlj
    12. * @create 2023-09-08 14:52
    13. */
    14. @Service
    15. public class StuBizImpl implements StuBiz {
    16. @Autowired
    17. private StuMapper stuMapper;
    18. @Override
    19. public int deleteByPrimaryKey(Integer sid) {
    20. return stuMapper.deleteByPrimaryKey(sid);
    21. }
    22. @Override
    23. public int insert(Stu record) {
    24. return stuMapper.insert(record);
    25. }
    26. @Override
    27. public int insertSelective(Stu record) {
    28. return stuMapper.insertSelective(record);
    29. }
    30. @Override
    31. public Stu selectByPrimaryKey(Integer sid) {
    32. return stuMapper.selectByPrimaryKey(sid);
    33. }
    34. @Override
    35. public int updateByPrimaryKeySelective(Stu record) {
    36. return stuMapper.updateByPrimaryKeySelective(record);
    37. }
    38. @Override
    39. public int updateByPrimaryKey(Stu record) {
    40. return stuMapper.updateByPrimaryKey(record);
    41. }
    42. @Override
    43. public List ListPager(Stu stu, PageBean pageBean) {
    44. return stuMapper.selectByCon(stu);
    45. }
    46. @Override
    47. public List mapListPager(Stu stu, Object o) {
    48. stu=null;
    49. System.out.println(stu.getSame());
    50. return stuMapper.mapListPager(stu,o);
    51. }
    52. }
    1. package com.zlj.web;
    2. import com.zlj.biz.StuBiz;
    3. import com.zlj.model.Stu;
    4. import com.zlj.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. //@ResponseBody
    13. //@Controller
    14. @RestController //@RestController=@ResponseBody+@Controller
    15. @RequestMapping("/stu/json")
    16. public class JsonController {
    17. @Autowired
    18. private StuBiz stuBiz;
    19. /**
    20. * 返回List
    21. * @param req
    22. * @param stu
    23. * @return
    24. */
    25. // @ResponseBody
    26. @RequestMapping("/list")
    27. public List list(HttpServletRequest req, Stu stu){
    28. PageBean pageBean = new PageBean();
    29. pageBean.setRequest(req);
    30. List lst = this.stuBiz.ListPager(stu, pageBean);
    31. System.out.println(1 / 0);
    32. return lst;
    33. }
    34. /**
    35. * 返回T
    36. * @param req
    37. * @param stu
    38. * @return
    39. */
    40. // @ResponseBody
    41. @RequestMapping("/load")
    42. public Stu load(HttpServletRequest req, Stu stu){
    43. if(stu.getSid() != null){
    44. List lst = this.stuBiz.ListPager(stu, null);
    45. return lst.get(0);
    46. }
    47. return null;
    48. }
    49. /**
    50. * 返回List
    51. * @param req
    52. * @param stu
    53. * @return
    54. */
    55. // @ResponseBody
    56. @RequestMapping("/mapList")
    57. public List mapList(HttpServletRequest req, Stu stu){
    58. PageBean pageBean = new PageBean();
    59. pageBean.setRequest(req);
    60. List lst = this.stuBiz.mapListPager(stu, pageBean);
    61. return lst;
    62. }
    63. /**
    64. * 返回Map
    65. * @param req
    66. * @param stu
    67. * @return
    68. */
    69. // @ResponseBody
    70. @RequestMapping("/mapLoad")
    71. public Map mapLoad(HttpServletRequest req, Stu stu){
    72. if(stu.getSid() != null){
    73. List lst = this.stuBiz.mapListPager(stu, null);
    74. return lst.get(0);
    75. }
    76. return null;
    77. }
    78. // @ResponseBody
    79. @RequestMapping("/all")
    80. public Map all(HttpServletRequest req, Stu stu){
    81. PageBean pageBean = new PageBean();
    82. pageBean.setRequest(req);
    83. List lst = this.stuBiz.ListPager(stu, pageBean);
    84. Map map = new HashMap();
    85. map.put("lst",lst);
    86. map.put("pageBean",pageBean);
    87. return map;
    88. }
    89. // @ResponseBody //返回单个字符串,而不是页面
    90. @RequestMapping("/jsonStr")
    91. public String jsonStr(HttpServletRequest req, Stu stu){
    92. System.out.println("333.....");
    93. return "stuEdit";
    94. }
    95. }
    1. //spring-mvc.xml
    2. "1.0" encoding="UTF-8"?>
    3. "http://www.springframework.org/schema/beans"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:context="http://www.springframework.org/schema/context"
    6. xmlns:aop="http://www.springframework.org/schema/aop"
    7. xmlns:mvc="http://www.springframework.org/schema/mvc"
    8. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    9. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    11. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    12. package="com.zlj"/>
    13. "org.springframework.web.servlet.view.InternalResourceViewResolver">
    14. "viewClass"
    15. value="org.springframework.web.servlet.view.JstlView">
    16. "prefix" value="/WEB-INF/jsp/"/>
    17. "suffix" value=".jsp"/>
    18. "/static/" mapping="/static/**"/>
    19. "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    20. "defaultEncoding" value="UTF-8">
    21. "maxUploadSize" value="52428800">
    22. "resolveLazily" value="true"/>
    23. "com.zlj.interceptor.LoginInterceptor">
    24. "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    25. "messageConverters">
    26. "mappingJackson2HttpMessageConverter"/>
    27. "mappingJackson2HttpMessageConverter"
    28. class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    29. "supportedMediaTypes">
    30. text/html;charset=UTF-8
    31. text/json;charset=UTF-8
    32. application/json;charset=UTF-8
    33. "org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    34. "defaultErrorView" value="error"/>
    35. "exceptionAttribute" value="ex"/>
    36. "exceptionMappings">
    37. "java.lang.RuntimeException">error
    1. package com.zlj.exception;
    2. public class GlobalException extends RuntimeException {
    3. public GlobalException() {
    4. }
    5. public GlobalException(String message) {
    6. super(message);
    7. }
    8. public GlobalException(String message, Throwable cause) {
    9. super(message, cause);
    10. }
    11. public GlobalException(Throwable cause) {
    12. super(cause);
    13. }
    14. public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    15. super(message, cause, enableSuppression, writableStackTrace);
    16. }
    17. }

     

    处理方式二,GobalHandler

    1. package com.zlj.component;
    2. import com.zlj.exception.GlobalException;
    3. import org.springframework.stereotype.Component;
    4. import org.springframework.web.servlet.HandlerExceptionResolver;
    5. import org.springframework.web.servlet.ModelAndView;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. @Component
    9. public class GlobalExceptionHandler implements HandlerExceptionResolver {
    10. @Override
    11. public ModelAndView resolveException(HttpServletRequest httpServletRequest,
    12. HttpServletResponse httpServletResponse,
    13. Object o, Exception e) {
    14. ModelAndView mv = new ModelAndView();
    15. mv.setViewName("error");//WEB-INF/jsp/error.jsp
    16. if (e instanceof GlobalException){
    17. GlobalException globalException = (GlobalException) e;
    18. mv.addObject("ex",globalException.getMessage());
    19. mv.addObject("msg","全局异常....");
    20. }else if (e instanceof RuntimeException){
    21. RuntimeException runtimeException = (RuntimeException) e;
    22. mv.addObject("ex",runtimeException.getMessage());
    23. mv.addObject("msg","运行时异常....");
    24. }else{
    25. mv.addObject("ex",e.getMessage());
    26. mv.addObject("msg","其他异常....");
    27. }
    28. return mv;
    29. }
    30. }

     注:@Component注释后会没有效果

    1. <%--
    2. Created by IntelliJ IDEA.
    3. User: 朱
    4. Date: 2023/9/13
    5. Time: 15:31
    6. To change this template use File | Settings | File Templates.
    7. --%>
    8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    9. Title
    10. 错误信息界面。。。

    11. ${ex}

    12. ${msg}

    方式三

    1. package com.zlj.component;
    2. import com.zlj.exception.GlobalException;
    3. import org.springframework.web.bind.annotation.ControllerAdvice;
    4. import org.springframework.web.bind.annotation.ExceptionHandler;
    5. import org.springframework.web.bind.annotation.ResponseBody;
    6. import java.util.HashMap;
    7. import java.util.Map;
    8. @ControllerAdvice
    9. public class GlobalExceptionResolver {
    10. // 跳转错误页面
    11. // @ExceptionHandler
    12. // public ModelAndView handler(Exception e){
    13. // ModelAndView mv = new ModelAndView();
    14. // mv.setViewName("error");
    15. // if (e instanceof GlobalException){
    16. // GlobalException globalException = (GlobalException) e;
    17. // mv.addObject("ex",globalException.getMessage());
    18. // mv.addObject("msg","全局异常....");
    19. // }else if (e instanceof RuntimeException){
    20. // RuntimeException runtimeException = (RuntimeException) e;
    21. // mv.addObject("ex",runtimeException.getMessage());
    22. // mv.addObject("msg","运行时异常....");
    23. // }
    24. // return mv;
    25. // }
    26. // 返回错误json数据
    27. @ResponseBody
    28. @ExceptionHandler
    29. public Map handler(Exception e){
    30. Map map = new HashMap();
    31. if (e instanceof GlobalException){
    32. GlobalException globalException = (GlobalException) e;
    33. map.put("ex",globalException.getMessage());
    34. map.put("msg","全局异常....");
    35. }else if (e instanceof RuntimeException){
    36. RuntimeException runtimeException = (RuntimeException) e;
    37. map.put("ex",runtimeException.getMessage());
    38. map.put("msg","运行时异常....");
    39. }else {
    40. map.put("ex",e.getMessage());
    41. map.put("msg","其它异常....");
    42. }
    43. return map;
    44. }
    45. }

    1. package com.zlj.component;
    2. import com.zlj.exception.GlobalException;
    3. import org.springframework.web.bind.annotation.ControllerAdvice;
    4. import org.springframework.web.bind.annotation.ExceptionHandler;
    5. import org.springframework.web.servlet.ModelAndView;
    6. @ControllerAdvice
    7. public class GlobalExceptionResolver {
    8. // 跳转错误页面
    9. @ExceptionHandler
    10. public ModelAndView handler(Exception e){
    11. ModelAndView mv = new ModelAndView();
    12. mv.setViewName("error");
    13. if (e instanceof GlobalException){
    14. GlobalException globalException = (GlobalException) e;
    15. mv.addObject("ex",globalException.getMessage());
    16. mv.addObject("msg","全局异常....");
    17. }else if (e instanceof RuntimeException){
    18. RuntimeException runtimeException = (RuntimeException) e;
    19. mv.addObject("ex",runtimeException.getMessage());
    20. mv.addObject("msg","运行时异常....");
    21. }
    22. return mv;
    23. }
    24. // 返回错误json数据
    25. // @ResponseBody
    26. // @ExceptionHandler
    27. // public Map handler(Exception e){
    28. // Map map = new HashMap();
    29. // if (e instanceof GlobalException){
    30. // GlobalException globalException = (GlobalException) e;
    31. // map.put("ex",globalException.getMessage());
    32. // map.put("msg","全局异常....");
    33. // }else if (e instanceof RuntimeException){
    34. // RuntimeException runtimeException = (RuntimeException) e;
    35. // map.put("ex",runtimeException.getMessage());
    36. // map.put("msg","运行时异常....");
    37. // }else {
    38. // map.put("ex",e.getMessage());
    39. // map.put("msg","其它异常....");
    40. // }
    41. // return map;
    42. // }
    43. }

  • 相关阅读:
    大创项目推荐 深度学习的口罩佩戴检测 - opencv 卷积神经网络 机器视觉 深度学习
    微服务低代码Serverless平台(星链)的应用实践
    常见排序算法要点
    基于五等均分法和Bob Stone法衡量RFM顾客价值
    Android中JNI与NDK
    从 Linux 安装到 Hadoop 环境搭建全过程
    cameralink base 接口双通道任意图像数据源模拟
    9月1日目标检测学习笔记——通用物体检测
    计算机网络 | 06.[HTTP篇] HTTP/1.1如何优化
    springboot整合其它项目
  • 原文地址:https://blog.csdn.net/weixin_73471776/article/details/132854072