需要了解拦截器
自定义一个类 实现HandlerInterceptor 或 继承HandlerInterceptorAdapter
重写下面三个方法 顺序依次如下
//在 handler执行之前执行 返回值为ture才会执行 拦截器或handler
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setContentType("application/json;charset=utf-8");//设置响应编码
User user = (User) request.getSession().getAttribute("user");
if (user==null){
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();//需要导入jackson依赖
String result = objectMapper.writeValueAsString(new Result(false, "未登录!"));//将对象转换为json字符串
out.write(result);//响应给用户
return false;
}
return true;
}
//在 handler执行之后执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
//在 响应前执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
拦的执行需要在spring-mvc.xml中配置拦截器[因具体情况配置响应编码]
<mvc:interceptors>
<mvc:interceptor>
<!-- 拦截所有请求 -->
<mvc:mapping path="/**"/><!-- Spring MVC 拦截路径 -->
<!-- 使用bean定义一个Interceptor -->
<bean class="自定义类的权限定类名" />
</mvc:interceptor>
</mvc:interceptors>
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>