Java框架学习 -- SpringMVC的学习0

2016-04-15 | 阅读

classpath

classpath 本质上是 jvm的目录,jvm获取资源是从该根路径下找的,一般指向的是编译的跟路径.

  • classpath: : 只在classes路径中查找文件.
  • classpath*: : 在classes路径中查找文件,也会去jar文件中的classes路径查找文件.

springMVC返回json格式对象

<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>application/json;charset=UTF-8</value>
			</list>
		</property>
	</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="mappingJacksonHttpMessageConverter" />
        </list>
    </property>
</bean>

@RequestMapping(value = "/showStudent", produces="application/json")
public @ResponseBody Student toIndex(HttpServletRequest request, Model model){
    int userId = Integer.parseInt(request.getParameter("id"));
    Student user = this.studentService.getStudentById(userId);
    return user;
    }

关于SpringMVC中的统一异常处理

SpringMVC中处理异常,一般来说,有三种方式:

  1. 使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver
  2. 实现Spring的异常处理接口HandlerExceptionResolver 自定义自己的异常处理器;
  3. 使用@ExceptionHandler注解实现异常处理;

使用@ExceptionHandler注解:

//注解表面其要处理的Exception类型
@ExceptionHandler(RuntimeException.class)
public CustomReturnModel runtimeExceptionHandler(RuntimeException runtimeException) {
    CustomReturnModel model = new CustomReturnModel(runtimeException);
    LOGGER.info("handleAllException" + runtimeException);
    return model;
} 这段代码写在`Controller`中,则`Controller`中发生的异常都会在这里进行处理.但是如果设置了全局的`HandlerExceptionResolver`,会被其截获而不执行注解的异常处理.

设置全局的HandlerExceptionResolver:

public class ExceptionHandler implements HandlerExceptionResolver {

    private static Logger LOGGER = LogManager.getLogger(ExceptionHandler.class);

    public @ResponseBody  ModelAndView resolveException(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        LOGGER.error("服务器发生异常,堆栈为 " + ex);
        // 只返回错误信息,不返回完整堆栈了.
        CustomReturnModel model = new CustomReturnModel(ex.toString());
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(JSON.toJSONString(model));
        }catch (Exception e){
            LOGGER.error(e);
        }

        return new ModelAndView();
    }
}

需要实现接口HandlerExceptionResolver,接口只有一个函数,也就是处理异常的resolveException.同时还要在SpringMVC的配置文件中添加配置:

<bean id="handlerExceptionResolver" class="com.lxm.memoplus.utils.ExceptionHandler"/>

Exception的输出

e.getMessage() 是输出简要说明
e.toString() 是名称加简要说明

输出完整堆栈,只能:

StringWriter writer = new StringWriter();
ex.printStackTrace(new PrintWriter(writer));
LOGGER.error(writer.getBuffer().toString());

处理服务器异常

对于这些异常,无法通过前面的统一异常处理抓获,所以要设置,在web.xml文件中修改:

//可以指定Exception类型
<error-page>  
    <exception-type>java.lang.Throwable</exception-type>  
    <location>/500.jsp</location>  
</error-page>  
// 也可以指定网络异常的类型
<error-page>  
    <error-code>500</error-code>  
    <location>/500.jsp</location>  
</error-page>  
<error-page>  
    <error-code>404</error-code>  
    <location>/404.jsp</location>  
</error-page>