解决拦截器抛出异常处理类的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);
    }
}
相关推荐
llwszx1 小时前
深入理解Java锁原理(一):偏向锁的设计原理与性能优化
java·spring··偏向锁
云泽野2 小时前
【Java|集合类】list遍历的6种方式
java·python·list
二进制person2 小时前
Java SE--方法的使用
java·开发语言·算法
小阳拱白菜3 小时前
java异常学习
java
FrankYoou4 小时前
Jenkins 与 GitLab CI/CD 的核心对比
java·docker
麦兜*5 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了5 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
天河归来5 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
weixin_478689765 小时前
十大排序算法汇总
java·算法·排序算法
码荼5 小时前
学习开发之hashmap
java·python·学习·哈希算法·个人开发·小白学开发·不花钱不花时间crud