解决拦截器抛出异常处理类的500状态码Html默认格式响应 !

解决方式

XML 复制代码
<mvc:annotation-driven>
        <mvc:message-converters>
            <!-- 配置JSON消息转换器 -->
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

将Java对象转换为JSON格式的响应,使用spring-mvc.xml配置适当的消息转换器。

问题出处的相关类如下

interceptor如下

java 复制代码
package com.ekgc.interceptor;

import com.ekgc.exception.UnLoginException;
import com.ekgc.pojo.SysUser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 * 1.实现 HandlerInterceptor接口
 * 2.实现接口方法
 * 3.在springmvc.xml中配置拦截器
 * @author Magic
 * @version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		System.out.println("preHandle...");
		// 记录请求处理开始时间
		request.setAttribute("startTime", System.currentTimeMillis());

		// 检查用户是否已经登录
		if (!isLoggedIn(request)) {
			//抛出未登录异常
			throw new UnLoginException("您还没有登录!!!");
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle...");
		// 计算请求处理时间
		long startTime = (long) request.getAttribute("startTime");
		long endTime = System.currentTimeMillis();
		long executionTime = endTime - startTime;

		System.out.println("Request execution time: " + executionTime + " ms");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		System.out.println("afterCompletion...");
	}

	private boolean isLoggedIn(HttpServletRequest request) {
		// 检查用户是否已登录的逻辑
		HttpSession session = request.getSession();
		SysUser user = (SysUser) session.getAttribute("user");
		// 返回true表示已登录,false表示未登录
		if (user == null) {
			return false;
		}
		return true;
	}
}

自定义异常类

java 复制代码
package com.ekgc.exception;

/**
 * @author Magic
 * @version 1.0
 */
public class UnLoginException extends RuntimeException{
    public UnLoginException(String message) {
        super(message);
    }
}

异常处理类

java 复制代码
package com.ekgc.exception;

import com.ekgc.response.RespBody;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * 登录异常处理类
 * @author Magic
 * @version 1.0
 */
@ControllerAdvice
public class LoginExceptionHandler {

    @ExceptionHandler(UnLoginException.class)
    @ResponseBody
    public RespBody<String> loginExceptionHandler(UnLoginException e) {
        String message = e.getMessage();
        System.out.println(message);
        return new RespBody<String>(-1,message,message);
    }
}
相关推荐
java1234_小锋1 小时前
Java高频面试题:Redis的Key和Value的设计原则有哪些?
java·redis·面试
iPadiPhone1 小时前
流量洪峰下的数据守护者:InnoDB MVCC 全实现深度解析
java·数据库·mysql·面试
Nuopiane1 小时前
关于C#/Unity中单例的探讨
java·jvm·c#
win x1 小时前
JVM类加载及双亲委派模型
java·jvm
YDS8291 小时前
SpringCloud —— Elasticsearch入门详解
spring·elasticsearch·spring cloud
毕设源码-赖学姐2 小时前
【开题答辩全过程】以 滑雪场租赁管理系统的设计与实现为例,包含答辩的问题和答案
java
Javatutouhouduan2 小时前
SpringBoot整合reids:JSON序列化文件夹操作实录
java·数据库·redis·html·springboot·java编程·java程序员
wen__xvn2 小时前
模拟题刷题3
java·数据结构·算法
bug攻城狮2 小时前
Spring Boot应用内存占用分析与优化
java·jvm·spring boot·后端
xiaodaidai丶2 小时前
解决Sa-Token在 Spring MVC + WebFlux 混合架构中流式接口报错SaTokenContext 上下文尚未初始化的问题
spring·架构·mvc