三、Spring MVC中静态资源的引用和异常处理
3.1 静态资源的引用
在Spring MVC的web.xml文件中配置前端控制器映射时,会限定拦截的页面,这些显示的页面一般都是动态的,要想让静态页面的资源也可以使用,我们就不得不配置静态资源的引用,在引用时只需在Spring MVC核心配置文件中配置即可:
<mvc:resources mapping="/css/*" location="/css/"/>
<mvc:resources mapping="/images/*" location="/images/"/>
<mvc:resources mapping="/js/*" location="/js/"/>
<mvc:resources mapping="/resource/**/" location="/resource/"/>

3.2 Spring MVC中的异常处理
-
全局异常
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionAttribute" value="ex"/>
<property name="exceptionMappings">
<props>
<prop key="java.lang.RuntimeException">error</prop>
</props>
</property>
</bean>
@RequestMapping(method = RequestMethod.GET,value = {"/toLogin"})
public String toLogin(){
System.out.println(1/0);
return "login";
}
<%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2021/7/22
Time: 11:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误界面</title>
</head>
<body>
${ex}
</body>
</html>
  -
局部异常
@ExceptionHandler(value = RuntimeException.class)
public String expection(RuntimeException re,HttpServletRequest request){
request.setAttribute("MSG",re.getMessage());
return "error";
}
@RequestMapping(method = RequestMethod.GET,value = {"/toLogin"})
public String toLogin(){
System.out.println(1/0);
return "login";
}
<%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2021/7/22
Time: 11:13
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>错误界面</title>
</head>
<body>
这是错误界面-----${requestScope.MSG}
</body>
</html>
 
|