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

  • json处理
  • 统一异常处理

1.json处理

//pom.xml



  4.0.0

  org.example
  zljzyssm
  1.0-SNAPSHOT
  war

  zljzyssm Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
    3.7.0

    
    
    5.0.2.RELEASE
    
    3.4.5
    
    5.1.44
    
    5.1.2
    
    1.3.1
    
    2.1.1
    2.4.3
    
    2.9.1
    3.2.0
    1.7.13
    
    4.12
    4.0.0
    1.18.2

    1.1.0
    2.10.0

    2.9.0
    1.7.1.RELEASE
    2.9.3
    1.2
    1.1.2
    8.0.47
    1.3.3
    5.0.2.Final

    1.3.2
  


  
    
    
      org.springframework
      spring-core
      ${spring.version}
    
    
      org.springframework
      spring-beans
      ${spring.version}
    
    
      org.springframework
      spring-context
      ${spring.version}
    
    
      org.springframework
      spring-orm
      ${spring.version}
    
    
      org.springframework
      spring-tx
      ${spring.version}
    
    
      org.springframework
      spring-aspects
      ${spring.version}
    
    
      org.springframework
      spring-web
      ${spring.version}
    

    
      org.springframework
      spring-test
      ${spring.version}
    


    
    
      org.mybatis
      mybatis
      ${mybatis.version}
    
    
    
      mysql
      mysql-connector-java
      ${mysql.version}
    
    
    
      com.github.pagehelper
      pagehelper
      ${pagehelper.version}
    
    
    
      org.mybatis
      mybatis-spring
      ${mybatis.spring.version}
    

    
      org.springframework
      spring-context-support
      ${spring.version}
    

    
    
      org.mybatis.caches
      mybatis-ehcache
      ${mybatis.ehcache.version}
    
    
    
      net.sf.ehcache
      ehcache
      ${ehcache.version}
    

    
      redis.clients
      jedis
      ${redis.version}
    
    
      org.springframework.data
      spring-data-redis
      ${redis.spring.version}
    
    
      com.fasterxml.jackson.core
      jackson-databind
      ${jackson.version}
    
    
      com.fasterxml.jackson.core
      jackson-core
      ${jackson.version}
    
    
      com.fasterxml.jackson.core
      jackson-annotations
      ${jackson.version}
    

    
    
      org.apache.commons
      commons-dbcp2
      ${commons.dbcp2.version}
      
        
          commons-pool2
          org.apache.commons
        
      
    
    
      org.apache.commons
      commons-pool2
      ${commons.pool2.version}
    

    
    
      org.springframework
      spring-webmvc
      ${spring.version}
    

    

    
    
    
    
      org.slf4j
      slf4j-api
      ${slf4j.version}
    
    
      org.slf4j
      jcl-over-slf4j
      ${slf4j.version}
      runtime
    

    
    
      org.apache.logging.log4j
      log4j-api
      ${log4j2.version}
    
    
      org.apache.logging.log4j
      log4j-core
      ${log4j2.version}
    
    
    
      org.apache.logging.log4j
      log4j-slf4j-impl
      ${log4j2.version}
    
    
    
      org.apache.logging.log4j
      log4j-web
      ${log4j2.version}
      runtime
    

    
    
      com.lmax
      disruptor
      ${log4j2.disruptor.version}
    

    
    
      junit
      junit
      ${junit.version}
      
    
    
      javax.servlet
      javax.servlet-api
      ${servlet.version}
      provided
    
    
      org.projectlombok
      lombok
      ${lombok.version}
      provided
    
    
      jstl
      jstl
      ${jstl.version}
    
    
      taglibs
      standard
      ${standard.version}
    
    
      org.apache.tomcat
      tomcat-jsp-api
      ${tomcat-jsp-api.version}
    
    
      commons-fileupload
      commons-fileupload
      ${commons-fileupload.version}
    

    
      org.hibernate
      hibernate-validator
      ${hibernate-validator.version}
    

    
    
      org.apache.shiro
      shiro-core
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-web
      ${shiro.version}
    
    
      org.apache.shiro
      shiro-spring
      ${shiro.version}
    
  

  
    zljzyssm

    
      
      
        src/main/java
        
          **/*.xml
        
      
      
      
        src/main/resources
        
          jdbc.properties
          *.xml
        
      
    

    

      
        org.apache.maven.plugins
        maven-compiler-plugin
        ${maven.compiler.plugin.version}
        
          ${maven.compiler.source}
          ${maven.compiler.target}
          ${project.build.sourceEncoding}
        
      
      
        org.mybatis.generator
        mybatis-generator-maven-plugin
        1.3.2
        
          
          
            mysql
            mysql-connector-java
            ${mysql.version}
          
        
        
          true
        
      

    
  
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



  
    
      
      
      
      
    
  
  
    sid, same, sage, spic
  

  

  

  

  
    delete from student
    where sid = #{sid,jdbcType=INTEGER}
  
  
    insert into student (sid, same, sage,
      spic)
    values (#{sid,jdbcType=INTEGER}, #{same,jdbcType=VARCHAR}, #{sage,jdbcType=INTEGER},
      #{spic,jdbcType=VARCHAR})
  
  
    insert into student
    
      
        sid,
      
      
        same,
      
      
        sage,
      
      
        spic,
      
    
    
      
        #{sid,jdbcType=INTEGER},
      
      
        #{same,jdbcType=VARCHAR},
      
      
        #{sage,jdbcType=INTEGER},
      
      
        #{spic,jdbcType=VARCHAR},
      
    
  
  
    update student
    
      
        same = #{same,jdbcType=VARCHAR},
      
      
        sage = #{sage,jdbcType=INTEGER},
      
      
        spic = #{spic,jdbcType=VARCHAR},
      
    
    where sid = #{sid,jdbcType=INTEGER}
  
  
    update student
    set same = #{same,jdbcType=VARCHAR},
      sage = #{sage,jdbcType=INTEGER},
      spic = #{spic,jdbcType=VARCHAR}
    where sid = #{sid,jdbcType=INTEGER}
  
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 selectByCon(Stu stu);

    List 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 ListPager(Stu stu, PageBean PageBean);

    List 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 ListPager(Stu stu, PageBean pageBean) {
        return stuMapper.selectByCon(stu);
    }

    @Override
    public List 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
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/list")
    public List list(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List 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 lst = this.stuBiz.ListPager(stu, null);
            return lst.get(0);
        }
        return null;
    }


    /**
     * 返回List
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/mapList")
    public List mapList(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List 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 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 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 ListPager(Stu stu, PageBean pageBean) {
        return stuMapper.selectByCon(stu);
    }

    @Override
    public List 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
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/list")
    public List list(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List 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 lst = this.stuBiz.ListPager(stu, null);
            return lst.get(0);
        }
        return null;
    }


    /**
     * 返回List
     * @param req
     * @param stu
     * @return
     */
//    @ResponseBody
    @RequestMapping("/mapList")
    public List mapList(HttpServletRequest req, Stu stu){
        PageBean pageBean = new PageBean();
        pageBean.setRequest(req);
        List 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 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 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


   
    

    
    

    
    
        
        
        
        
    

    



    

    
    
        
        
        
        
        
        
    


    
        
    


















    
        
            
                
            
        
    
    
        
        
            
                text/html;charset=UTF-8
                text/json;charset=UTF-8
                application/json;charset=UTF-8
            
        
    



    
    
        
        
        
        
        
        
            
                error
            
            
        
    

    
    
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);
    }
}

SpringMVC之JSON返回&异常处理机制_第1张图片 

SpringMVC之JSON返回&异常处理机制_第2张图片

处理方式二,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" %>


    Title


错误信息界面。。。

${ex}
${msg}

SpringMVC之JSON返回&异常处理机制_第3张图片

SpringMVC之JSON返回&异常处理机制_第4张图片

SpringMVC之JSON返回&异常处理机制_第5张图片

方式三

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;
    }
}

SpringMVC之JSON返回&异常处理机制_第6张图片

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;
//    }
}

SpringMVC之JSON返回&异常处理机制_第7张图片

你可能感兴趣的:(json,前端,服务器)