异常处理基于注解ResponseStatus

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
│   │                   └── StatusException.java
│   ├── resources
│   └── webapp
│       ├── index.jsp
│       └── WEB-INF
│           └── web.xml
└── test
    ├── java
    │   └── ocn
    │       └── site
    │           └── springmvc
    │               └── controller
    │                   └── Runtest.java
    └── resources
        └── config
            └── application.xml

19 directories, 10 files
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.22.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>4.3.22.RELEASE</version>
    <scope>test</scope>
</dependency>
package ocn.site.springmvc.controller;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

import ocn.site.springmvc.utils.StatusException;

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

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

	// must read doc about `warning`
	@GetMapping("/onmethod")
	@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "test annotation @ResponseStatus")
	public void handler404() {
		logger.info("used on method success");
	}

	@GetMapping("/onclass")
	public void handler() {
		throw new StatusException();
	}

}
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", "ocn.site.springmvc.utils" })
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";

}
package ocn.site.springmvc.utils;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

// /springmvc4322/src/main/java/ocn/site/springmvc/utils/StatusException.java
@ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "annotation used on exception class")
public class StatusException extends RuntimeException {

	private static final long serialVersionUID = 1L;
	private final Logger logger = Logger.getLogger(this.getClass());

	public StatusException() {
		super();
		logger.info("used on exception class success");
		// TODO Auto-generated constructor stub
	}

	public StatusException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

	public StatusException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public StatusException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public StatusException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

}
<?xml version="1.0" encoding="UTF-8"?>
<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>springmvc4322</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- /springmvc4322/src/main/webapp/WEB-INF/web.xml -->
	<jsp-config>
		<jsp-property-group>
			<url-pattern>*.jsp</url-pattern>
			<el-ignored>false</el-ignored>
			<scripting-invalid>true</scripting-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"%>
<!DOCTYPE html>
<html>
<head>
<base href="${pageContext.request.contextPath }/">
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<script src="https://libs.cdnjs.net/jquery/3.4.1/jquery.min.js"></script>
<script src="https://libs.cdnjs.net/json2/20160511/json2.min.js"></script>
<title>Insert title here</title>
</head>
<body>
	<a href="onmethod">onmethod</a>
	<a href="onclass">onclass</a>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<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">
	<!-- /springmvc4322/src/test/resources/config/application.xml -->

	<context:component-scan base-package="ocn.site.springmvc.controller"></context:component-scan>
	<context:component-scan base-package="ocn.site.springmvc.utils"></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.request.MockMvcRequestBuilders;
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();
		build.perform(MockMvcRequestBuilders.get("/onmethod"));
		build.perform(MockMvcRequestBuilders.get("/onclass"));
		logger.info("test finished");
	}

}
19-09-03 16:13:24 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 16:13:24 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 16:13:24 org.springframework.beans.factory.xml.XmlBeanDefinitionReader  =====>>> Loading XML bean definitions from class path resource [config/application.xml]
19-09-03 16:13:25 org.springframework.web.context.support.GenericWebApplicationContext  =====>>> Refreshing org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 16:13:25 CST 2019]; root of context hierarchy
19-09-03 16:13:25 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  =====>>> Mapped "{[/onmethod],methods=[GET]}" onto public void ocn.site.springmvc.controller.Manicontroller.handler404()
19-09-03 16:13:25 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping  =====>>> Mapped "{[/onclass],methods=[GET]}" onto public void ocn.site.springmvc.controller.Manicontroller.handler()
19-09-03 16:13:25 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter  =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 16:13:25 CST 2019]; root of context hierarchy
19-09-03 16:13:25 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter  =====>>> Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 16:13:25 CST 2019]; root of context hierarchy
19-09-03 16:13:25 org.springframework.web.servlet.handler.SimpleUrlHandlerMapping  =====>>> Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
19-09-03 16:13:25 org.springframework.mock.web.MockServletContext  =====>>> Initializing Spring FrameworkServlet ''
19-09-03 16:13:25 org.springframework.test.web.servlet.TestDispatcherServlet  =====>>> FrameworkServlet '': initialization started
19-09-03 16:13:25 org.springframework.test.web.servlet.TestDispatcherServlet  =====>>> FrameworkServlet '': initialization completed in 25 ms
19-09-03 16:13:25 ocn.site.springmvc.controller.Manicontroller  =====>>> used on method success
19-09-03 16:13:25 ocn.site.springmvc.utils.StatusException  =====>>> used on exception class success
19-09-03 16:13:25 ocn.site.springmvc.controller.Runtest  =====>>> test finished
19-09-03 16:13:25 org.springframework.web.context.support.GenericWebApplicationContext  =====>>> Closing org.springframework.web.context.support.GenericWebApplicationContext@343f4d3d: startup date [Tue Sep 03 16:13:25 CST 2019]; root of context hierarchy
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值