三、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"> <!--定义异常处理页面来获取异常信息的变量名,默认为exception--> <property name="exceptionAttribute" value="ex"/> <property name="exceptionMappings"> <props> <!--如果出现运行时异常,就返回到error页面--> <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>
-
局部异常
/** * 运行时异常--局部异常处理 * @param re * @param request * @return */ @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>