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

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 Tair(兼容Redis),内存型 2GB
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
简介: SpringMVC之JSON返回&异常处理机制
  • json处理
  • 统一异常处理

1.json处理

//pom.xml
<?xml version="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">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>zljzyssm</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>zljzyssm Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
    <!--添加jar包依赖-->
    <!--1.spring 5.0.2.RELEASE相关-->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!--2.mybatis相关-->
    <mybatis.version>3.4.5</mybatis.version>
    <!--mysql-->
    <mysql.version>5.1.44</mysql.version>
    <!--pagehelper分页jar依赖-->
    <pagehelper.version>5.1.2</pagehelper.version>
    <!--mybatis与spring集成jar依赖-->
    <mybatis.spring.version>1.3.1</mybatis.spring.version>
    <!--3.dbcp2连接池相关 druid-->
    <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
    <commons.pool2.version>2.4.3</commons.pool2.version>
    <!--4.log日志相关-->
    <log4j2.version>2.9.1</log4j2.version>
    <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
    <slf4j.version>1.7.13</slf4j.version>
    <!--5.其他-->
    <junit.version>4.12</junit.version>
    <servlet.version>4.0.0</servlet.version>
    <lombok.version>1.18.2</lombok.version>
    <mybatis.ehcache.version>1.1.0</mybatis.ehcache.version>
    <ehcache.version>2.10.0</ehcache.version>
    <redis.version>2.9.0</redis.version>
    <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
    <jackson.version>2.9.3</jackson.version>
    <jstl.version>1.2</jstl.version>
    <standard.version>1.1.2</standard.version>
    <tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
    <commons-fileupload.version>1.3.3</commons-fileupload.version>
    <hibernate-validator.version>5.0.2.Final</hibernate-validator.version>
    <shiro.version>1.3.2</shiro.version>
  </properties>
  <dependencies>
    <!--1.spring相关-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--2.mybatis相关-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!--pagehelper分页插件jar包依赖-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>${pagehelper.version}</version>
    </dependency>
    <!--mybatis与spring集成jar包依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--mybatis与ehcache整合-->
    <dependency>
      <groupId>org.mybatis.caches</groupId>
      <artifactId>mybatis-ehcache</artifactId>
      <version>${mybatis.ehcache.version}</version>
    </dependency>
    <!--ehcache依赖-->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache</artifactId>
      <version>${ehcache.version}</version>
    </dependency>
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>${redis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>${redis.spring.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <!--3.dbcp2连接池相关-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>${commons.dbcp2.version}</version>
      <exclusions>
        <exclusion>
          <artifactId>commons-pool2</artifactId>
          <groupId>org.apache.commons</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>${commons.pool2.version}</version>
    </dependency>
    <!--springmvc依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--4.log日志相关依赖-->
    <!-- log4j2日志相关依赖 -->
    <!-- log配置:Log4j2 + Slf4j -->
    <!-- slf4j核心包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>
    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--用于与slf4j保持桥接-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
      <scope>runtime</scope>
    </dependency>
    <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${log4j2.disruptor.version}</version>
    </dependency>
    <!--5.其他-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <!--      <scope>test</scope>-->
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>${standard.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-jsp-api</artifactId>
      <version>${tomcat-jsp-api.version}</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>${commons-fileupload.version}</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>${hibernate-validator.version}</version>
    </dependency>
    <!--shiro依赖-->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>${shiro.version}</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>zljzyssm</finalName>
    <resources>
      <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
      <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>jdbc.properties</include>
          <include>*.xml</include>
        </includes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <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.generator</groupId>
        <artifactId>mybatis-generator-maven-plugin</artifactId>
        <version>1.3.2</version>
        <dependencies>
          <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
          <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
          </dependency>
        </dependencies>
        <configuration>
          <overwrite>true</overwrite>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
package com.zlj.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.ToString;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@ToString
public class Stu {
        @NotNull(message = "学生编号不能为空")
//    @Size(max = 100,min = 10,message = "大小必须在10至100之间")
        protected Integer sid;
        @NotBlank(message = "学生名不能为空")
        protected String same;
        @NotBlank(message = "学生年龄不能为空")
        protected Integer sage;
        @JsonIgnore
        private String spic="暂无图片";
    public Stu(Integer sid, String same, Integer sage, String spic) {
        this.sid = sid;
        this.same = same;
        this.sage = sage;
        this.spic = spic;
    }
    public Integer getSid() {
        return sid;
    }
    public void setSid(Integer sid) {
        this.sid = sid;
    }
    public String getSame() {
        return same;
    }
    public void setSame(String same) {
        this.same = same;
    }
    public Integer getSage() {
        return sage;
    }
    public void setSage(Integer sage) {
        this.sage = sage;
    }
    public String getSpic() {
        return spic;
    }
    public void setSpic(String spic) {
        this.spic = spic;
    }
    public Stu() {
    }
}

stu类里@JsonIgnore:隐藏信息  

//StuMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zlj.mapper.StuMapper" >
  <resultMap id="BaseResultMap" type="com.zlj.model.Stu" >
    <constructor >
      <idArg column="sid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="same" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="sage" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="spic" jdbcType="VARCHAR" javaType="java.lang.String" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    sid, same, sage, spic
  </sql>
  <select id="selectByCon" resultType="com.zlj.model.Stu" parameterType="com.zlj.model.Stu">
    select
    <include refid="Base_Column_List" />
    from student
    <where>
      <if test="same != null">
        and same like concat('%',#{same},'%')
      </if>
    </where>
  </select>
<!--  mapListPager-->
  <select id="mapListPager" resultType="java.util.Map" parameterType="com.zlj.model.Stu">
    select
    <include refid="Base_Column_List" />
    from student
    <where>
      <if test="same != null">
        and same like concat('%',#{same},'%')
      </if>
    </where>
  </select>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select
    <include refid="Base_Column_List" />
    from student
    where sid = #{sid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from student
    where sid = #{sid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.zlj.model.Stu" >
    insert into student (sid, same, sage,
      spic)
    values (#{sid,jdbcType=INTEGER}, #{same,jdbcType=VARCHAR}, #{sage,jdbcType=INTEGER},
      #{spic,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.zlj.model.Stu" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="sid != null" >
        sid,
      </if>
      <if test="same != null" >
        same,
      </if>
      <if test="sage != null" >
        sage,
      </if>
      <if test="spic != null" >
        spic,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="sid != null" >
        #{sid,jdbcType=INTEGER},
      </if>
      <if test="same != null" >
        #{same,jdbcType=VARCHAR},
      </if>
      <if test="sage != null" >
        #{sage,jdbcType=INTEGER},
      </if>
      <if test="spic != null" >
        #{spic,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zlj.model.Stu" >
    update student
    <set >
      <if test="same != null" >
        same = #{same,jdbcType=VARCHAR},
      </if>
      <if test="sage != null" >
        sage = #{sage,jdbcType=INTEGER},
      </if>
      <if test="spic != null" >
        spic = #{spic,jdbcType=VARCHAR},
      </if>
    </set>
    where sid = #{sid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zlj.model.Stu" >
    update student
    set same = #{same,jdbcType=VARCHAR},
      sage = #{sage,jdbcType=INTEGER},
      spic = #{spic,jdbcType=VARCHAR}
    where sid = #{sid,jdbcType=INTEGER}
  </update>
</mapper>
package com.zlj.mapper;
import com.zlj.model.Stu;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
public interface StuMapper {
    int deleteByPrimaryKey(Integer sid);
    int insert(Stu record);
    int insertSelective(Stu record);
    Stu selectByPrimaryKey(Integer sid);
    int updateByPrimaryKeySelective(Stu record);
    int updateByPrimaryKey(Stu record);
    List<Stu> selectByCon(Stu stu);
    List<Map> mapListPager(Stu stu, Object o);
}
package com.zlj.biz;
import com.zlj.model.Stu;
import com.zlj.util.PageBean;
import java.util.List;
import java.util.Map;
/**
 * @author zlj
 * @create 2023-09-07 17:09
 */
public interface StuBiz {
    int deleteByPrimaryKey(Integer sid);
    int insert(Stu record);
    int insertSelective(Stu record);
    Stu selectByPrimaryKey(Integer sid);
    int updateByPrimaryKeySelective(Stu record);
    int updateByPrimaryKey(Stu record);
    List<Stu> ListPager(Stu stu, PageBean PageBean);
    List<Map> mapListPager(Stu stu, Object o);
}
package com.zlj.biz.Impl;
import com.zlj.biz.StuBiz;
import com.zlj.mapper.StuMapper;
import com.zlj.model.Stu;
import com.zlj.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
 * @author zlj
 * @create 2023-09-08 14:52
 */
@Service
public class StuBizImpl implements StuBiz {
@Autowired
private StuMapper stuMapper;
    @Override
    public int deleteByPrimaryKey(Integer sid) {
        return stuMapper.deleteByPrimaryKey(sid);
    }
    @Override
    public int insert(Stu record) {
        return stuMapper.insert(record);
    }
    @Override
    public int insertSelective(Stu record) {
        return stuMapper.insertSelective(record);
    }
    @Override
    public Stu selectByPrimaryKey(Integer sid) {
        return stuMapper.selectByPrimaryKey(sid);
    }
    @Override
    public int updateByPrimaryKeySelective(Stu record) {
        return stuMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    public int updateByPrimaryKey(Stu record) {
        return stuMapper.updateByPrimaryKey(record);
    }
    @Override
    public List<Stu> ListPager(Stu stu, PageBean pageBean) {
        return stuMapper.selectByCon(stu);
    }
    @Override
    public List<Map> mapListPager(Stu stu, Object o) {
        return stuMapper.mapListPager(stu,o);
    }
}
package com.zlj.web;
import com.zlj.biz.StuBiz;
import com.zlj.model.Stu;
import com.zlj.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;
//@ResponseBody
//@Controller
@RestController  //@RestController=@ResponseBody+@Controller
@RequestMapping("/stu/json")
public class JsonController {
    @Autowired
    private StuBiz stuBiz;
    /**
     * 返回List<T>
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/list")
    public List<Stu> list(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Stu> lst = this.stuBiz.ListPager(stu, pageBean);
        return lst;
    }
    /**
     * 返回T
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/load")
    public Stu load(HttpServletRequest req, Stu stu){
        if(stu.getSid() != null){
            List<Stu> lst = this.stuBiz.ListPager(stu, null);
            return lst.get(0);
        }
        return null;
    }
    /**
     * 返回List<Map>
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/mapList")
    public List<Map> mapList(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Map> lst = this.stuBiz.mapListPager(stu, pageBean);
        return lst;
    }
    /**
     * 返回Map
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/mapLoad")
    public Map mapLoad(HttpServletRequest req, Stu stu){
        if(stu.getSid() != null){
            List<Map> lst = this.stuBiz.mapListPager(stu, null);
            return lst.get(0);
        }
        return null;
    }
//    @ResponseBody
    @RequestMapping("/all")
    public Map all(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Stu> lst = this.stuBiz.ListPager(stu, pageBean);
        Map map = new HashMap();
        map.put("lst",lst);
        map.put("pageBean",pageBean);
        return map;
    }
//    @ResponseBody  //返回单个字符串,而不是页面
    @RequestMapping("/jsonStr")
    public String jsonStr(HttpServletRequest req, Stu stu){
        System.out.println("333.....");
        return "stuEdit";
    }
}

@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页面,分别报两个错


package com.zlj.biz.Impl;
import com.zlj.biz.StuBiz;
import com.zlj.mapper.StuMapper;
import com.zlj.model.Stu;
import com.zlj.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
 * @author zlj
 * @create 2023-09-08 14:52
 */
@Service
public class StuBizImpl implements StuBiz {
@Autowired
private StuMapper stuMapper;
    @Override
    public int deleteByPrimaryKey(Integer sid) {
        return stuMapper.deleteByPrimaryKey(sid);
    }
    @Override
    public int insert(Stu record) {
        return stuMapper.insert(record);
    }
    @Override
    public int insertSelective(Stu record) {
        return stuMapper.insertSelective(record);
    }
    @Override
    public Stu selectByPrimaryKey(Integer sid) {
        return stuMapper.selectByPrimaryKey(sid);
    }
    @Override
    public int updateByPrimaryKeySelective(Stu record) {
        return stuMapper.updateByPrimaryKeySelective(record);
    }
    @Override
    public int updateByPrimaryKey(Stu record) {
        return stuMapper.updateByPrimaryKey(record);
    }
    @Override
    public List<Stu> ListPager(Stu stu, PageBean pageBean) {
        return stuMapper.selectByCon(stu);
    }
    @Override
    public List<Map> mapListPager(Stu stu, Object o) {
        stu=null;
        System.out.println(stu.getSame());
        return stuMapper.mapListPager(stu,o);
    }
}
package com.zlj.web;
import com.zlj.biz.StuBiz;
import com.zlj.model.Stu;
import com.zlj.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;
//@ResponseBody
//@Controller
@RestController  //@RestController=@ResponseBody+@Controller
@RequestMapping("/stu/json")
public class JsonController {
    @Autowired
    private StuBiz stuBiz;
    /**
     * 返回List<T>
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/list")
    public List<Stu> list(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Stu> lst = this.stuBiz.ListPager(stu, pageBean);
        System.out.println(1 / 0);
        return lst;
    }
    /**
     * 返回T
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/load")
    public Stu load(HttpServletRequest req, Stu stu){
        if(stu.getSid() != null){
            List<Stu> lst = this.stuBiz.ListPager(stu, null);
            return lst.get(0);
        }
        return null;
    }
    /**
     * 返回List<Map>
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/mapList")
    public List<Map> mapList(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Map> lst = this.stuBiz.mapListPager(stu, pageBean);
        return lst;
    }
    /**
     * 返回Map
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/mapLoad")
    public Map mapLoad(HttpServletRequest req, Stu stu){
        if(stu.getSid() != null){
            List<Map> lst = this.stuBiz.mapListPager(stu, null);
            return lst.get(0);
        }
        return null;
    }
//    @ResponseBody
    @RequestMapping("/all")
    public Map all(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List<Stu> lst = this.stuBiz.ListPager(stu, pageBean);
        Map map = new HashMap();
        map.put("lst",lst);
        map.put("pageBean",pageBean);
        return map;
    }
//    @ResponseBody  //返回单个字符串,而不是页面
    @RequestMapping("/jsonStr")
    public String jsonStr(HttpServletRequest req, Stu stu){
        System.out.println("333.....");
        return "stuEdit";
    }
}
//spring-mvc.xml
<?xml version="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:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
   <!--1) 扫描com.zking.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
    <context:component-scan base-package="com.zlj"/>
    <!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven />
    <!--3) 创建ViewResolver视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--4) 单独处理图片、样式、js等资源 -->
<!--     <mvc:resources location="/css/" mapping="/css/**"/>-->
<!--     <mvc:resources location="/js/" mapping="/js/**"/>-->
<!--     <mvc:resources location="WEB-INF/images/" mapping="/images/**"/>  -->
    <mvc:resources location="/static/" mapping="/static/**"/>
    <!--    处理文件上传下载问题-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>
<!--    配置拦截器-->
    <mvc:interceptors>
        <bean class="com.zlj.interceptor.LoginInterceptor"></bean>
    </mvc:interceptors>
<!--单拦截器-->
<!--    <mvc:interceptors>-->
<!--        <bean class="com.zlj.interceptor.OneInterceptor"></bean>-->
<!--    </mvc:interceptors>-->
<!--    <mvc:interceptors>-->
<!--        &lt;!&ndash;2) 多拦截器(拦截器链)&ndash;&gt;-->
<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/**"/>-->
<!--            <bean class="com.zlj.interceptor.OneInterceptor"/>-->
<!--        </mvc:interceptor>-->
<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/stu/**"/>-->
<!--            <bean class="com.zlj.interceptor.TwoInterceptor"/>-->
<!--        </mvc:interceptor>-->
<!--    </mvc:interceptors>-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJackson2HttpMessageConverter"/>
            </list>
        </property>
    </bean>
    <bean id="mappingJackson2HttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <!--处理中文乱码以及避免IE执行AJAX时,返回JSON出现下载文件-->
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
                <value>text/json;charset=UTF-8</value>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- springmvc提供的简单异常处理器 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <!-- 定义默认的异常处理页面 -->
        <property name="defaultErrorView" value="error"/>
        <!-- 定义异常处理页面用来获取异常信息的变量名,也可不定义,默认名为exception -->
        <property name="exceptionAttribute" value="ex"/>
        <!-- 定义需要特殊处理的异常,这是重要点 -->
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.RuntimeException">error</prop>
            </props>
            <!-- 还可以定义其他的自定义异常 -->
        </property>
    </bean>
    <!--    处理controller层发送请求到biz,会经过切面拦截处理-->
    <aop:aspectj-autoproxy/>
</beans>
package com.zlj.exception;
public class GlobalException extends RuntimeException {
    public GlobalException() {
    }
    public GlobalException(String message) {
        super(message);
    }
    public GlobalException(String message, Throwable cause) {
        super(message, cause);
    }
    public GlobalException(Throwable cause) {
        super(cause);
    }
    public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

处理方式二,GobalHandler

package com.zlj.component;
import com.zlj.exception.GlobalException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                         HttpServletResponse httpServletResponse,
                                         Object o, Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");//WEB-INF/jsp/error.jsp
        if (e instanceof GlobalException){
            GlobalException globalException = (GlobalException) e;
            mv.addObject("ex",globalException.getMessage());
            mv.addObject("msg","全局异常....");
        }else if (e instanceof RuntimeException){
            RuntimeException runtimeException = (RuntimeException) e;
            mv.addObject("ex",runtimeException.getMessage());
            mv.addObject("msg","运行时异常....");
        }else{
            mv.addObject("ex",e.getMessage());
            mv.addObject("msg","其他异常....");
        }
        return mv;
    }
}

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

<%--
  Created by IntelliJ IDEA.
  User: 朱
  Date: 2023/9/13
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
错误信息界面。。。
<hr>
${ex}
</hr>
<hr>
${msg}
</hr>
</body>
</html>

方式三

package com.zlj.component;
import com.zlj.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalExceptionResolver {
//    跳转错误页面
//    @ExceptionHandler
//    public ModelAndView handler(Exception e){
//        ModelAndView mv = new ModelAndView();
//        mv.setViewName("error");
//        if (e instanceof GlobalException){
//            GlobalException globalException = (GlobalException) e;
//            mv.addObject("ex",globalException.getMessage());
//            mv.addObject("msg","全局异常....");
//        }else if (e instanceof RuntimeException){
//            RuntimeException runtimeException = (RuntimeException) e;
//            mv.addObject("ex",runtimeException.getMessage());
//            mv.addObject("msg","运行时异常....");
//        }
//        return mv;
//    }
// 返回错误json数据
    @ResponseBody
    @ExceptionHandler
    public Map handler(Exception e){
        Map map = new HashMap();
        if (e instanceof GlobalException){
            GlobalException globalException = (GlobalException) e;
            map.put("ex",globalException.getMessage());
            map.put("msg","全局异常....");
        }else if (e instanceof RuntimeException){
            RuntimeException runtimeException = (RuntimeException) e;
            map.put("ex",runtimeException.getMessage());
            map.put("msg","运行时异常....");
        }else {
            map.put("ex",e.getMessage());
            map.put("msg","其它异常....");
        }
        return map;
    }
}

package com.zlj.component;
import com.zlj.exception.GlobalException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class GlobalExceptionResolver {
//    跳转错误页面
    @ExceptionHandler
    public ModelAndView handler(Exception e){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("error");
        if (e instanceof GlobalException){
            GlobalException globalException = (GlobalException) e;
            mv.addObject("ex",globalException.getMessage());
            mv.addObject("msg","全局异常....");
        }else if (e instanceof RuntimeException){
            RuntimeException runtimeException = (RuntimeException) e;
            mv.addObject("ex",runtimeException.getMessage());
            mv.addObject("msg","运行时异常....");
        }
        return mv;
    }
// 返回错误json数据
//    @ResponseBody
//    @ExceptionHandler
//    public Map handler(Exception e){
//        Map map = new HashMap();
//        if (e instanceof GlobalException){
//            GlobalException globalException = (GlobalException) e;
//            map.put("ex",globalException.getMessage());
//            map.put("msg","全局异常....");
//        }else if (e instanceof RuntimeException){
//            RuntimeException runtimeException = (RuntimeException) e;
//            map.put("ex",runtimeException.getMessage());
//            map.put("msg","运行时异常....");
//        }else {
//            map.put("ex",e.getMessage());
//            map.put("msg","其它异常....");
//        }
//        return map;
//    }
}

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
1月前
|
JSON 前端开发 Java
SSM:SpringMVC
本文介绍了SpringMVC的依赖配置、请求参数处理、注解开发、JSON处理、拦截器、文件上传下载以及相关注意事项。首先,需要在`pom.xml`中添加必要的依赖,包括Servlet、JSTL、Spring Web MVC等。接着,在`web.xml`中配置DispatcherServlet,并设置Spring MVC的相关配置,如组件扫描、默认Servlet处理器等。然后,通过`@RequestMapping`等注解处理请求参数,使用`@ResponseBody`返回JSON数据。此外,还介绍了如何创建和配置拦截器、文件上传下载的功能,并强调了JSP文件的放置位置,避免404错误。
|
1月前
|
前端开发 Java 应用服务中间件
【Spring】Spring MVC的项目准备和连接建立
【Spring】Spring MVC的项目准备和连接建立
53 2
|
2月前
|
缓存 前端开发 Java
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
Soring Boot的起步依赖、启动流程、自动装配、常用的注解、Spring MVC的执行流程、对MVC的理解、RestFull风格、为什么service层要写接口、MyBatis的缓存机制、$和#有什么区别、resultType和resultMap区别、cookie和session的区别是什么?session的工作原理
【Java面试题汇总】Spring,SpringBoot,SpringMVC,Mybatis,JavaWeb篇(2023版)
|
1月前
|
XML 前端开发 Java
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
本文阐述了Spring、Spring Boot和Spring MVC的关系与区别,指出Spring是一个轻量级、一站式、模块化的应用程序开发框架,Spring MVC是Spring的一个子框架,专注于Web应用和网络接口开发,而Spring Boot则是对Spring的封装,用于简化Spring应用的开发。
108 0
Spring,SpringBoot和SpringMVC的关系以及区别 —— 超准确,可当面试题!!!也可供零基础学习
|
2月前
|
XML 缓存 前端开发
springMVC02,restful风格,请求转发和重定向
文章介绍了RESTful风格的基本概念和特点,并展示了如何使用SpringMVC实现RESTful风格的请求处理。同时,文章还讨论了SpringMVC中的请求转发和重定向的实现方式,并通过具体代码示例进行了说明。
springMVC02,restful风格,请求转发和重定向
|
1月前
|
XML 存储 前端开发
手动开发-实现SpringMVC底层机制--小试牛刀
手动开发-实现SpringMVC底层机制--小试牛刀
13 0
|
3月前
|
Java 数据库连接 Spring
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
文章是关于Spring、SpringMVC、Mybatis三个后端框架的超详细入门教程,包括基础知识讲解、代码案例及SSM框架整合的实战应用,旨在帮助读者全面理解并掌握这些框架的使用。
后端框架入门超详细 三部曲 Spring 、SpringMVC、Mybatis、SSM框架整合案例 【爆肝整理五万字】
|
3月前
|
XML JSON 数据库
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
这篇文章详细介绍了RESTful的概念、实现方式,以及如何在SpringMVC中使用HiddenHttpMethodFilter来处理PUT和DELETE请求,并通过具体代码案例分析了RESTful的使用。
SpringMVC入门到实战------七、RESTful的详细介绍和使用 具体代码案例分析(一)
|
3月前
|
前端开发 应用服务中间件 数据库
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
这篇文章通过一个具体的项目案例,详细讲解了如何使用SpringMVC、Thymeleaf、Bootstrap以及RESTful风格接口来实现员工信息的增删改查功能。文章提供了项目结构、配置文件、控制器、数据访问对象、实体类和前端页面的完整源码,并展示了实现效果的截图。项目的目的是锻炼使用RESTful风格的接口开发,虽然数据是假数据并未连接数据库,但提供了一个很好的实践机会。文章最后强调了这一章节主要是为了练习RESTful,其他方面暂不考虑。
SpringMVC入门到实战------八、RESTful案例。SpringMVC+thymeleaf+BootStrap+RestFul实现员工信息的增删改查
|
3月前
|
JSON 前端开发 Java
Spring MVC返回JSON数据
综上所述,Spring MVC提供了灵活、强大的方式来支持返回JSON数据,从直接使用 `@ResponseBody`及 `@RestController`注解,到通过配置消息转换器和异常处理器,开发人员可以根据具体需求选择合适的实现方式。
157 4