异常处理
- index.jsp
<a href="${pageContext.request.contextPath}/GoTry">1/0=?</a>
- ExceptionController
@Controller
public class ExceptionController {
@RequestMapping("GoTry")
public String test1(){
int i = 1/0;
return "/result.jsp";
}
/**
* 异常优先级:
* ArithmeticException => RuntimeException => Exception
* 如果Exception也没有,就会去找一个类:
*/
@ExceptionHandler(value = ArithmeticException.class)
public String doException(Exception e){
System.out.println(e.getMessage());
return "/error.jsp";
}
@ExceptionHandler(value = RuntimeException.class)
public String doException2(Exception e){
System.out.println(e.getMessage());
return "/error.jsp";
}
@ExceptionHandler(value = Exception.class)
public String doException3(Exception e){
System.out.println(e.getMessage());
return "/error.jsp";
}
}
- error.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>服务器回家过年了!</h1>
</body>
</html>
如果Exception也没有,就会去找一个类
@ControllerAdvice
public class ExceptionHander {
@ExceptionHandler(value = Exception.class)
public String doExcption(Exception e){
System.out.println(e.getMessage());
return "/error.jsp";
}
}
国际化
- 创建国际化的资源文件
message_zh_CN.properties
welcome=欢迎
name=撩课
message_en_US.properties
welcome=welcome
name=itlike
- 配置
springmvc.xml
<!--国际化-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message"/>
</bean>
- 导入
jstl
的两个Jar包 - index.jsp
<a href="${pageContext.request.contextPath}/local">测试国际化</a>
- LocalController
@Controller
public class LocalController {
@RequestMapping("local")
public String local(){
return "/local.jsp";
}
}
中英文切换
- index.jsp
<a href="${pageContext.request.contextPath}/local">测试国际化</a>
- LocalController
@Controller
public class LocalController {
@RequestMapping("local")
public String local(){
return "/local.jsp";
}
}
- local.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>local</h1>
<a href="?language=zh_CN"><fmt:message key="language.cn" /></a>
<a href="?language=en_US"><fmt:message key="language.en" /></a>
<hr>
<fmt:message key="welcome"/>
<fmt:message key="name"/>
</body>
</html>
springmvc.xml
<!--国际化-->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="message"/>
</bean>
<!--session本地解析器-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"/>
<!--拦截器-->
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language"/>
</bean>
</mvc:interceptors>
- 资源文件
message_en_US.properties
和message_zh_CN.properties
同上。
一定要打开这里: