解决方式
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);
}
}