异常处理基于注解ExceptionHandler

siye@r480:~/svlution/workspace/springmvc4322$ tree src/
src/
├── main
│   ├── java
│   │   ├── log4j.properties
│   │   └── ocn
│   │       └── site
│   │           └── springmvc
│   │               ├── controller
│   │               │   └── Manicontroller.java
│   │               ├── setup
│   │               │   ├── Appconfig.java
│   │               │   └── Webxmlconfig.java
│   │               └── utils
│   │                   └── ConstraintsUtils.java
│   ├── resources
│   └── webapp
│       ├── index.jsp
│       └── WEB-INF
│           ├── error.jsp
│           └── web.xml
└── test
    ├── java
    │   └── ocn
    │       └── site
    │           └── springmvc
    │               └── controller
    │                   └── Runtest.java
    └── resources
        └── config
            └── application.xml

19 directories, 10 files

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>4.3.22.RELEASEversion>
dependency>

<dependency>
    <groupId>log4jgroupId>
    <artifactId>log4jartifactId>
    <version>1.2.17version>
dependency>

<dependency>
    <groupId>junitgroupId>
    <artifactId>junitartifactId>
    <version>4.12version>
    <scope>testscope>
dependency>

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-testartifactId>
    <version>4.3.22.RELEASEversion>
    <scope>testscope>
dependency>
package ocn.site.springmvc.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

///springmvc4322/src/main/java/ocn/site/springmvc/controller/Manicontroller.java
@Controller
public class Manicontroller {

	private final Logger logger = Logger.getLogger(this.getClass());

	// reference annotation @ControllerAdvice
	@ExceptionHandler(NullPointerException.class)
	public ModelAndView handleException(Exception ex) {
		logger.info(ex);
		ModelAndView mav = new ModelAndView("error");
		mav.addObject("message", ex);
		return mav;
	}

	@GetMapping("/test")
	public void handler() {
		throw new NullPointerException("test annotation @ExceptionHandler");
	}

}
package ocn.site.springmvc.setup;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import ocn.site.springmvc.utils.ConstraintsUtils;

///springmvc4322/src/main/java/ocn/site/springmvc/setup/Appconfig.java
@Configuration
@EnableWebMvc
@ComponentScan({ "ocn.site.springmvc.controller", "ocn.site.springmvc.domain" })
public class Appconfig extends WebMvcConfigurerAdapter {

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		// TODO Auto-generated method stub
//		super.configureDefaultServletHandling(configurer);
		configurer.enable();
	}

	@Bean
	public ViewResolver getViewResolver() {
		return new InternalResourceViewResolver(ConstraintsUtils.PREFIX, ConstraintsUtils.SUFFIX);
	}

}
package ocn.site.springmvc.setup;

import javax.servlet.Filter;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import ocn.site.springmvc.utils.ConstraintsUtils;

// /springmvc4322/src/main/java/ocn/site/springmvc/setup/Webxmlconfig.java
public class Webxmlconfig extends AbstractAnnotationConfigDispatcherServletInitializer {

	@Override
	protected Class<?>[] getRootConfigClasses() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected Class<?>[] getServletConfigClasses() {
		// TODO Auto-generated method stub
		return new Class<?>[] { Appconfig.class };
	}

	@Override
	protected String[] getServletMappings() {
		// TODO Auto-generated method stub
		return new String[] { "/" };
	}

	@Override
	protected Filter[] getServletFilters() {
		// TODO Auto-generated method stub
		return new Filter[] { new CharacterEncodingFilter(ConstraintsUtils.ENCODING, true),
				new HiddenHttpMethodFilter() };
	}

}
package ocn.site.springmvc.utils;

// /springmvc4322/src/main/java/ocn/site/springmvc/utils/ConstraintsUtils.java
public interface ConstraintsUtils {

	String ENCODING = "UTF-8";
	String PREFIX = "/WEB-INF/";
	String SUFFIX = ".jsp";

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>








Insert title here


	

${message }


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
	<display-name>springmvc4322display-name>
	<welcome-file-list>
		<welcome-file>index.htmlwelcome-file>
		<welcome-file>index.htmwelcome-file>
		<welcome-file>index.jspwelcome-file>
		<welcome-file>default.htmlwelcome-file>
		<welcome-file>default.htmwelcome-file>
		<welcome-file>default.jspwelcome-file>
	welcome-file-list>

	
	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.jspurl-pattern>
			<el-ignored>falseel-ignored>
			<scripting-invalid>truescripting-invalid>
		jsp-property-group>
	jsp-config>

web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>







Insert title here


	test



<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	

	<context:component-scan base-package="ocn.site.springmvc.controller">context:component-scan>
	<mvc:annotation-driven>mvc:annotation-driven>
	<mvc:default-servlet-handler />
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/">property>
		<property name="suffix" value=".jsp">property>
	bean>

beans>
package ocn.site.springmvc.controller;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

// /springmvc4322/src/test/java/ocn/site/springmvc/controller/Runtest.java
@RunWith(SpringRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:config/application.xml")
public class Runtest {

	private final Logger logger = Logger.getLogger(this.getClass());
	private @Autowired WebApplicationContext wac;

	@Test
	public void run() throws Exception {
		MockMvc build = MockMvcBuilders.webAppContextSetup(this.wac).build();
		MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/test");
		ResultActions ra = build.perform(requestBuilder);
		ra.andExpect(MockMvcResultMatchers.view().name("error"));
		ra.andExpect(MockMvcResultMatchers.status().isOk());
		logger.info("test finished");
	}

}
19-09-03 15:23:40 org.springframework.test.context.web.WebTestContextBootstrapper  =====>>> Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
19-09-03 15:23:40 org.springframework.test.context.web.WebTestContextBootstrapper  =====>>> Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@1efbd816, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@6a2bcfcb, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@4de8b406, org.springframework.test.context.support.DirtiesContextTestExecutionListener@3c756e4d]
19-09-03 15:23:40 org.springframework.beans.factory.xml.XmlBeanDefinitionReader  =====>>> Loading XML bean definitions from class path resource [config/application.xml]
19-09-03 15:23:40 org.springframework.web.context.support.GenericWebApplicationContext  =====>>> Refreshing org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 15:23:40 CST 2019]; root of context hierarchy
19-09-03 15:23:41 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  =====>>> Mapped "{[/test],methods=[GET]}" onto public void ocn.site.springmvc.controller.Manicontroller.handler()
19-09-03 15:23:41 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter  =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 15:23:40 CST 2019]; root of context hierarchy
19-09-03 15:23:41 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter  =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 15:23:40 CST 2019]; root of context hierarchy
19-09-03 15:23:41 org.springframework.web.servlet.handler.SimpleUrlHandlerMapping  =====>>> Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
19-09-03 15:23:41 org.springframework.mock.web.MockServletContext  =====>>> Initializing Spring FrameworkServlet ''
19-09-03 15:23:41 org.springframework.test.web.servlet.TestDispatcherServlet  =====>>> FrameworkServlet '': initialization started
19-09-03 15:23:41 org.springframework.test.web.servlet.TestDispatcherServlet  =====>>> FrameworkServlet '': initialization completed in 22 ms
19-09-03 15:23:41 ocn.site.springmvc.controller.Manicontroller  =====>>> java.lang.NullPointerException: test annotation @ExceptionHandler
19-09-03 15:23:41 ocn.site.springmvc.controller.Runtest  =====>>> test finished
19-09-03 15:23:41 org.springframework.web.context.support.GenericWebApplicationContext  =====>>> Closing org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 15:23:40 CST 2019]; root of context hierarchy
// reference==> /org/springframework/web/servlet/DispatcherServlet.properties

// reference==> org.springframework.web.servlet.DispatcherServlet

// read annotation @EnableWebMvc doc

// reference==> org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.handlerExceptionResolver()

你可能感兴趣的:(springmvc)