目录
springMVC框架如何产生JSON格式的数据:
①、导入pom依赖 Jackson
②、配置springMVC.xml 作用:是做JSON数据转换的
③、使用注解@responseBody能够将任何数据转成JSON对象
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.0" encoding="UTF-8"?>
-
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <parent>
- <artifactId>ideamavenartifactId>
- <groupId>org.examplegroupId>
- <version>1.0-SNAPSHOTversion>
- parent>
- <modelVersion>4.0.0modelVersion>
-
- <artifactId>ssm2artifactId>
- <packaging>warpackaging>
-
- <name>ssm2 Maven Webappname>
-
- <url>http://www.example.comurl>
-
- <properties>
- <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
- <maven.compiler.source>1.8maven.compiler.source>
- <maven.compiler.target>1.8maven.compiler.target>
- <maven.compiler.plugin.version>3.7.0maven.compiler.plugin.version>
-
-
-
- <spring.version>5.0.2.RELEASEspring.version>
-
- <mybatis.version>3.4.5mybatis.version>
-
- <mysql.version>5.1.44mysql.version>
-
- <pagehelper.version>5.1.2pagehelper.version>
-
- <mybatis.spring.version>1.3.1mybatis.spring.version>
-
- <commons.dbcp2.version>2.1.1commons.dbcp2.version>
- <commons.pool2.version>2.4.3commons.pool2.version>
-
- <log4j2.version>2.9.1log4j2.version>
-
- <junit.version>4.12junit.version>
- <servlet.version>4.0.0servlet.version>
- <lombok.version>1.18.2lombok.version>
- properties>
-
- <dependencies>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-ormartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-txartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-aspectsartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webartifactId>
- <version>${spring.version}version>
- dependency>
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-testartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>${mybatis.version}version>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>${mysql.version}version>
- dependency>
-
- <dependency>
- <groupId>com.github.pagehelpergroupId>
- <artifactId>pagehelperartifactId>
- <version>${pagehelper.version}version>
- dependency>
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatis-springartifactId>
- <version>${mybatis.spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-dbcp2artifactId>
- <version>${commons.dbcp2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.commonsgroupId>
- <artifactId>commons-pool2artifactId>
- <version>${commons.pool2.version}version>
- dependency>
-
-
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-coreartifactId>
- <version>${log4j2.version}version>
- dependency>
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-apiartifactId>
- <version>${log4j2.version}version>
- dependency>
-
- <dependency>
- <groupId>org.apache.logging.log4jgroupId>
- <artifactId>log4j-webartifactId>
- <version>${log4j2.version}version>
- dependency>
-
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>${junit.version}version>
- <scope>testscope>
- dependency>
- <dependency>
- <groupId>javax.servletgroupId>
- <artifactId>javax.servlet-apiartifactId>
- <version>${servlet.version}version>
- <scope>providedscope>
- dependency>
- <dependency>
- <groupId>org.projectlombokgroupId>
- <artifactId>lombokartifactId>
- <version>${lombok.version}version>
- <scope>providedscope>
- dependency>
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-webmvcartifactId>
- <version>${spring.version}version>
- dependency>
-
-
- <dependency>
- <groupId>javax.servlet.jspgroupId>
- <artifactId>javax.servlet.jsp-apiartifactId>
- <version>2.3.3version>
- dependency>
- <dependency>
- <groupId>jstlgroupId>
- <artifactId>jstlartifactId>
- <version>1.2version>
- dependency>
- <dependency>
- <groupId>taglibsgroupId>
- <artifactId>standardartifactId>
- <version>1.1.2version>
- dependency>
-
- <dependency>
- <groupId>commons-fileuploadgroupId>
- <artifactId>commons-fileuploadartifactId>
- <version>1.3.3version>
- dependency>
-
-
- <dependency>
- <groupId>org.hibernategroupId>
- <artifactId>hibernate-validatorartifactId>
- <version>6.0.7.Finalversion>
- dependency>
-
-
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-databindartifactId>
- <version>2.9.3version>
- dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-coreartifactId>
- <version>2.9.3version>
- dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.coregroupId>
- <artifactId>jackson-annotationsartifactId>
- <version>2.9.3version>
- dependency>
-
-
-
- dependencies>
-
-
- <build>
- <finalName>ssm2finalName>
-
- <resources>
-
- <resource>
- <directory>src/main/javadirectory>
- <includes>
- <include>**/*.xmlinclude>
- includes>
- resource>
-
- <resource>
- <directory>src/main/resourcesdirectory>
- <includes>
- <include>jdbc.propertiesinclude>
- <include>*.xmlinclude>
- includes>
- resource>
- resources>
-
-
-
- <pluginManagement>
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-compiler-pluginartifactId>
- <version>${maven.compiler.plugin.version}version>
- <configuration>
- <source>${maven.compiler.source}source>
- <target>${maven.compiler.target}target>
- <encoding>${project.build.sourceEncoding}encoding>
- configuration>
- plugin>
- <plugin>
- <groupId>org.mybatis.generatorgroupId>
- <artifactId>mybatis-generator-maven-pluginartifactId>
- <version>1.3.2version>
- <dependencies>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>${mysql.version}version>
- dependency>
- dependencies>
- <configuration>
- <overwrite>trueoverwrite>
- configuration>
- plugin>
-
-
-
- <plugin>
- <artifactId>maven-clean-pluginartifactId>
- <version>3.1.0version>
- plugin>
-
- <plugin>
- <artifactId>maven-resources-pluginartifactId>
- <version>3.0.2version>
- plugin>
- <plugin>
- <artifactId>maven-compiler-pluginartifactId>
- <version>3.8.0version>
- plugin>
- <plugin>
- <artifactId>maven-surefire-pluginartifactId>
- <version>2.22.1version>
- plugin>
- <plugin>
- <artifactId>maven-war-pluginartifactId>
- <version>3.2.2version>
- plugin>
- <plugin>
- <artifactId>maven-install-pluginartifactId>
- <version>2.5.2version>
- plugin>
- <plugin>
- <artifactId>maven-deploy-pluginartifactId>
- <version>2.8.2version>
- plugin>
- plugins>
- pluginManagement>
- build>
- project>
支持json数据返回的适配器
- <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">
-
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8value>
- <value>text/json;charset=UTF-8value>
- <value>application/json;charset=UTF-8value>
- list>
- property>
- bean>
springmvc-servlet.xml
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- 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">
-
-
- <aop:aspectj-autoproxy/>
- <context:component-scan base-package="com.cdl"/>
-
-
-
-
- <mvc:annotation-driven>mvc:annotation-driven>
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView">property>
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"/>
- bean>
-
-
-
-
-
- <mvc:resources location="/static/" mapping="/static/**"/>
-
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
-
- <property name="defaultEncoding" value="UTF-8">property>
-
- <property name="maxUploadSize" value="52428800">property>
-
- <property name="resolveLazily" value="true"/>
- bean>
-
-
-
-
-
-
-
-
- <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">
-
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8value>
- <value>text/json;charset=UTF-8value>
- <value>application/json;charset=UTF-8value>
- list>
- property>
- bean>
-
-
- beans>
- package com.cdl.ssm.controller;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-22 16:42
- */
- @Controller
- @RequestMapping("/clz/json")
- public class JsonController {
-
- @ResponseBody
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- }
结果:
返回一个字符串而不是跳一个页面了
添加一个listMapPager的方法
在clazzMapper.xml中配置该方法
- <select id="listMapPager" parameterType="com.cdl.ssm.model.Clazz" resultType="java.util.Map">
- select
- <include refid="Base_Column_List" />
- from t_struts_class
- <where>
- <if test="cname != null and cname!= ''">
- and cname like CONCAT('%',#{cname},'%')
- if>
- <if test="cid != null and cid!= ''">
- and cid = #{cid}
- if>
- where>
- select>
ClazzMapper
- package com.cdl.ssm.mapper;
-
- import com.cdl.ssm.model.Clazz;
- import org.springframework.stereotype.Repository;
-
- import java.util.List;
- import java.util.Map;
-
- @Repository
- public interface ClazzMapper {
- int deleteByPrimaryKey(Integer cid);
-
- int insert(Clazz record);
-
- int insertSelective(Clazz record);
-
- Clazz selectByPrimaryKey(Integer cid);
-
- List
listPager(Clazz clazz); -
- List
-
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
- }
ClazzBiz
- package com.cdl.ssm.biz;
-
- import com.cdl.ssm.model.Clazz;
- import com.cdl.ssm.util.PageBean;
-
- import java.util.List;
- import java.util.Map;
-
- public interface ClazzBiz {
- int deleteByPrimaryKey(Integer cid);
-
- int insert(Clazz record);
-
- int insertSelective(Clazz record);
-
- Clazz selectByPrimaryKey(Integer cid);
-
- List
listPager(Clazz clazz, PageBean pageBean); -
- int updateByPrimaryKeySelective(Clazz record);
-
- int updateByPrimaryKey(Clazz record);
-
-
- List
-
-
- }
ClazzBizImpl
- package com.cdl.ssm.biz.impl;
-
- import com.cdl.ssm.biz.ClazzBiz;
- import com.cdl.ssm.mapper.ClazzMapper;
- import com.cdl.ssm.model.Clazz;
- import com.cdl.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-17 20:22
- */
- @Service
- public class ClazzBizImpl implements ClazzBiz {
- @Autowired
- private ClazzMapper clazzMapper;
-
- @Override
- public int deleteByPrimaryKey(Integer cid) {
- return clazzMapper.deleteByPrimaryKey(cid);
- }
-
- @Override
- public int insert(Clazz record) {
- return clazzMapper.insert(record);
- }
-
- @Override
- public int insertSelective(Clazz record) {
- return clazzMapper.insertSelective(record);
- }
-
- @Override
- public Clazz selectByPrimaryKey(Integer cid) {
- return clazzMapper.selectByPrimaryKey(cid);
- }
-
- @Override
- public List
listPager(Clazz clazz, PageBean pageBean) { - List
clazzes = clazzMapper.listPager(clazz); - // System.out.println(clazzes);
- return clazzes;
- }
-
- @Override
- public int updateByPrimaryKeySelective(Clazz record) {
- return clazzMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(Clazz record) {
- return clazzMapper.updateByPrimaryKey(record);
- }
-
- @Override
- public List
- return clazzMapper.listMapPager(clazz);
- }
- }
- package com.cdl.ssm.controller;
-
- import com.cdl.ssm.biz.ClazzBiz;
- import com.cdl.ssm.model.Clazz;
- import com.cdl.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-22 16:42
- */
- @Controller
- @RequestMapping("/clz/json")
- public class JsonController {
-
- @Autowired
- private ClazzBiz clazzBiz;
-
- @ResponseBody
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- //返回list
- @ResponseBody
- @RequestMapping("/list")
- public List
list(HttpServletRequest request,Clazz clazz){ - PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- //返回list
- @ResponseBody
- @RequestMapping("/listMap")
- public List
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- //返回单个Map集合
- @ResponseBody
- @RequestMapping("/map")
- public Map map(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- //T
- @ResponseBody
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- //混合
- @ResponseBody
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map = new HashMap();
- map.put("data",lst);
- map.put("pagebean",pageBean);
- return map;
- }
-
- }
- <%--
- Created by IntelliJ IDEA.
- User: Lenovo
- Date: 2022/8/19
- Time: 20:33
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>测试json数据返回title>
- head>
- <body>
- <a href="${pageContext.request.contextPath}/clz/json/list">返回list<T>对象a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/listMap">返回list<Map>对象a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/load?cid=1">返回T对象a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/map?cid=1">返回map对象a><hr>
- <a href="${pageContext.request.contextPath}/clz/json/hunhe">返回混合对象a><hr>
-
-
- body>
- html>
@ResponseBody+@Controller=@RestController为什么要用全局异常处理:
在springmvc中,能将所有类型的异常处理从各处理过程解耦出来,既保证了相关处理过程的功能较单一,也实现了异常信息的统一处理和维护
JsonController
- package com.cdl.ssm.controller;
-
- import com.cdl.ssm.biz.ClazzBiz;
- import com.cdl.ssm.model.Clazz;
- import com.cdl.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-22 16:42
- */
- @RestController
- @RequestMapping("/clz/json")
- public class JsonController {
-
- @Autowired
- private ClazzBiz clazzBiz;
-
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- //返回list
- @RequestMapping("/list")
- public List
list(HttpServletRequest request,Clazz clazz){ - PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- if (true)
- throw new RuntimeException("查询异常,错误出现在 JsonController.list...");
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- //返回list
- @RequestMapping("/listMap")
- public List
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- //返回单个Map集合
- @RequestMapping("/map")
- public Map map(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- //T
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- //混合
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map = new HashMap();
- map.put("data",lst);
- map.put("pagebean",pageBean);
- return map;
- }
-
- }
ClazzBizImpl
- package com.cdl.ssm.biz.impl;
-
- import com.cdl.ssm.biz.ClazzBiz;
- import com.cdl.ssm.mapper.ClazzMapper;
- import com.cdl.ssm.model.Clazz;
- import com.cdl.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-17 20:22
- */
- @Service
- public class ClazzBizImpl implements ClazzBiz {
- @Autowired
- private ClazzMapper clazzMapper;
-
- @Override
- public int deleteByPrimaryKey(Integer cid) {
- return clazzMapper.deleteByPrimaryKey(cid);
- }
-
- @Override
- public int insert(Clazz record) {
- return clazzMapper.insert(record);
- }
-
- @Override
- public int insertSelective(Clazz record) {
- return clazzMapper.insertSelective(record);
- }
-
- @Override
- public Clazz selectByPrimaryKey(Integer cid) {
- return clazzMapper.selectByPrimaryKey(cid);
- }
-
- @Override
- public List
listPager(Clazz clazz, PageBean pageBean) { - List
clazzes = clazzMapper.listPager(clazz); - // System.out.println(clazzes);
- return clazzes;
- }
-
- @Override
- public int updateByPrimaryKeySelective(Clazz record) {
- return clazzMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(Clazz record) {
- return clazzMapper.updateByPrimaryKey(record);
- }
-
- @Override
- public List
- if (true)
- throw new RuntimeException("查询异常,错误出现在 ClazzBizImpl.list...");
- return clazzMapper.listMapPager(clazz);
- }
- }
这样标记异常很不方便,所以我们要采用springMVC的三种异常处理方式
1、配置springmvc.xml使用SpringMVC提供的简单异常处理器SimpleMappingExceptionResolver;
2、实现Spring的异常处理接口HandlerExceptionResolver自定义自己的异常处理器;
3、使用@ControllerAdvice + @ExceptionHandler
error
springmvc-servlet.xml
- "1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
- 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">
-
-
- <aop:aspectj-autoproxy/>
- <context:component-scan base-package="com.cdl"/>
-
-
-
-
- <mvc:annotation-driven>mvc:annotation-driven>
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
- <property name="viewClass"
- value="org.springframework.web.servlet.view.JstlView">property>
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"/>
- bean>
-
-
-
-
-
- <mvc:resources location="/static/" mapping="/static/**"/>
-
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
-
- <property name="defaultEncoding" value="UTF-8">property>
-
- <property name="maxUploadSize" value="52428800">property>
-
- <property name="resolveLazily" value="true"/>
- bean>
-
-
-
-
-
-
-
-
- <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">
-
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8value>
- <value>text/json;charset=UTF-8value>
- <value>application/json;charset=UTF-8value>
- list>
- property>
- bean>
-
-
-
- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
-
- <property name="defaultErrorView" value="error"/>
-
- <property name="exceptionAttribute" value="ex"/>
-
- <property name="exceptionMappings">
- <props>
- <prop key="java.lang.RuntimeException">errorprop>
- props>
-
- property>
- bean>
-
-
- beans>
error.jsp
-
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>错误信息页面title>
- head>
- <body>
- ${ex}
- body>
- html>
因为不太灵活,采取第二中方式
把统一异常处理注了,以免产生冲突
GlobalException
- package com.cdl.ssm.exception;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-22 20:05
- */
- 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);
- }
- }
GlobalHandlerExceptionResovler
- package com.cdl.ssm.exception;
-
- 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;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-22 20:15
- *
- * 处理全局异常的解析器
- */
- @Component
- public class GlobalHandlerExceptionResovler implements HandlerExceptionResolver {
-
- /**
- *
- * @param httpServletRequest
- * @param httpServletResponse
- * @param o 目标对象
- * @param e 目标对象执行出现的异常对象
- * @return
- */
- @Override
- public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
-
- ModelAndView mv = new ModelAndView();
- mv.setViewName("error");
- if(e instanceof GlobalException){
- GlobalException exception =(GlobalException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","全局异常,错误码203");
- } else if(e instanceof RuntimeException){
- RuntimeException exception =(RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","运行异常,错误码503");
- }
- return mv;
- }
- }
-
JsonController
- package com.cdl.ssm.controller;
-
- import com.cdl.ssm.biz.ClazzBiz;
- import com.cdl.ssm.exception.GlobalException;
- import com.cdl.ssm.model.Clazz;
- import com.cdl.ssm.util.PageBean;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-22 16:42
- */
- @RestController
- @RequestMapping("/clz/json")
- public class JsonController {
-
- @Autowired
- private ClazzBiz clazzBiz;
-
- @RequestMapping("/clzEdit")
- public String clzEdit(){
- System.out.println("JsonController.clzEdit");
- return "clzEdit";
- }
-
- //返回list
- @RequestMapping("/list")
- public List
list(HttpServletRequest request,Clazz clazz){ - PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- if (true)
- throw new RuntimeException("查询异常,错误出现在 JsonController.list...");
- return this.clazzBiz.listPager(clazz,pageBean);
- }
-
- //返回list
- @RequestMapping("/listMap")
- public List
- PageBean pageBean = new PageBean();
- pageBean.setRequest(request);
- return this.clazzBiz.listMapPager(clazz,pageBean);
- }
-
- //返回单个Map集合
- @RequestMapping("/map")
- public Map map(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- return this.clazzBiz.listMapPager(clazz,pageBean).get(0);
- }
-
- //T
- @RequestMapping("/load")
- public Clazz load(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- if(true)
- throw new GlobalException("系统繁忙,请参考E007;");
- return this.clazzBiz.listPager(clazz,pageBean).get(0);
- }
-
- //混合
- @RequestMapping("/hunhe")
- public Map hunhe(HttpServletRequest req, Clazz clazz){
- PageBean pageBean = new PageBean();
- pageBean.setRequest(req);
- List
lst = this.clazzBiz.listPager(clazz, pageBean); - Map map = new HashMap();
- map.put("data",lst);
- map.put("pagebean",pageBean);
- return map;
- }
-
- }
error.jsp
-
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>错误信息页面title>
- head>
- <body>
- ${msg}
- <hr>
- ${ex}
- body>
- html>
点击出现以下两种结果
为了不受使用接口的影响
如图注释
GlobalExceptionResolver
- package com.cdl.ssm.exception;
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-24 8:55
- */
- @ControllerAdvice
- public class GlobalExceptionResolver {
-
- @ExceptionHandler
- public ModelAndView handler(Exception e){
- ModelAndView mv = new ModelAndView();
- mv.setViewName("error");
- if(e instanceof GlobalException){
- GlobalException exception =(GlobalException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","GlobalExceptionResolver全局异常,错误码203");
- } else if(e instanceof RuntimeException){
- RuntimeException exception =(RuntimeException) e;
- mv.addObject("ex",exception.getMessage());
- mv.addObject("msg","GlobalExceptionResolver运行异常,错误码503");
- }
- return mv;
- }
-
-
-
- }
点击出现两种结果
GlobalExceptionResolver2
- package com.cdl.ssm.exception;
-
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * @author cdl
- * @site www.cdl.com
- * @create 2022-08-24 8:55
- *
- * 当出现异常,统一向前端响应错误信息的JSON对象数据
- */
- @RestControllerAdvice
- public class GlobalExceptionResolver2 {
-
- @ExceptionHandler
- public Map handler(Exception e){
- Map map = new HashMap();
- if(e instanceof GlobalException){
- GlobalException exception =(GlobalException) e;
- map.put("ex",exception.getMessage());
- map.put("msg","GlobalExceptionResolver2全局异常,错误码203");
- } else if(e instanceof RuntimeException){
- RuntimeException exception =(RuntimeException) e;
- map.put("ex",exception.getMessage());
- map.put("msg","GlobalExceptionResolver2运行异常,错误码503");
- }
- return map;
- }
-
-
-
- }
出现以下两种结果