springmvc之自定义注解(annotation)
Posted code.world
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springmvc之自定义注解(annotation)相关的知识,希望对你有一定的参考价值。
参考:日志处理 三:Filter+自定义注解实现 系统日志跟踪功能
1、项目结构
2、pom.xml,添加需要依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>test.com</groupId> <artifactId>test-com</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>test-com Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- spring begin --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- spring end --> <!-- Spring AOP + AspectJ by shipengzhi --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.11</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.11</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_3</version> </dependency> <!-- end --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>test-com</finalName> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.1.2.RELEASE</spring.version> </properties> </project>
3、dispartch-servlet.xml
<?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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" default-lazy-init="true"> <!-- 通过mvc:resources设置静态资源,这样servlet就会处理这些静态资源,而不通过控制器 --> <!-- 设置不过滤内容,比如:css,jquery,img 等资源文件 --> <mvc:resources location="/*.html" mapping="/**.html" /> <mvc:resources location="/css/*" mapping="/css/**" /> <mvc:resources location="/js/*" mapping="/js/**" /> <mvc:resources location="/images/*" mapping="/images/**" /> <!-- 添加注解驱动 --> <mvc:annotation-driven /> <!-- 默认扫描的包路径 --> <context:component-scan base-package="com.*" /> <!-- mvc:view-controller可以在不需要Controller处理request的情况,转向到设置的View --> <!-- 像下面这样设置,如果请求为/,则不通过controller,而直接解析为/index.jsp --> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <!-- Log自定义注解拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.log.SystemLogAspect"></bean> </mvc:interceptor> </mvc:interceptors> </beans>
3、web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>Archetype Created Web Application</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <!-- 设置dispatchservlet的匹配模式,通过把dispatchservlet映射到/,默认servlet会处理所有的请求,包括静态资源 --> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 字符集过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
4、Log.java,定义自定义注解
package com.log; /** * Created by Administrator on 2016/6/26. */ import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Log { String desc() default "没有标准描述"; boolean view() default true; String operationDesc() default "没有默认描述"; }
5、SystemLogAspect.java,自定义注解拦截器,实现对自定义注解的处理
package com.log; import java.lang.reflect.Method; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.core.NamedThreadLocal; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; public class SystemLogAspect extends HandlerInterceptorAdapter{ private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-StartTime"); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long beginTime = System.currentTimeMillis(); startTimeThreadLocal.set(beginTime); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("hander = "+handler); if (!(handler instanceof HandlerMethod)) { return; } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); final Log log = method.getAnnotation(Log.class); System.out.println("输出日志描述"+log.desc()); if (log != null) { String desc = log.desc(); boolean view = log.view(); String opeDesc = log.operationDesc(); if (view) { long endTime = System.currentTimeMillis(); long beginTime = startTimeThreadLocal.get(); long consumeTime = endTime - beginTime; System.out.println("view = " + view + " : opeDesc = "+opeDesc+" : beginTime = "+beginTime + " : endTime = "+endTime + " : consumeTime = "+consumeTime);
}
}
}
}
注:遇到未解决问题
System.out.println("hander = "+handler); if (!(handler instanceof HandlerMethod)) { return; }
在myeclipse中执行到此处会进入if判断,方法无法执行if后面的语句(在myeclipse中hander之返回到类);而在IDEA中会跳过if判断,执行if后面的语句(IDEA中hander返回到加注解@Log的方法test1)。也就是说在myeclipse中不能用此拦截器,目前未找到原因,看到的朋友又知道的帮忙评论告知一下。
6、index.jsp
<html> <body> <h2>Hello World!</h2> <form action="test1" method="post"> <input type="submit" name="submit"> </form> </body> </html>
7、success.jsp
<html> <body> <h2>Hello Success!</h2> </body> </html>
8、结果
hander = public java.lang.String com.controller.TestController.test1() 输出日志描述:你好孙建飞 view = true : opeDesc = 没有默认描述 : beginTime = 1466949053156endTime = 1466949053265 consumeTime = 109
以上是关于springmvc之自定义注解(annotation)的主要内容,如果未能解决你的问题,请参考以下文章
springmvc之RequestMapping注解既可以修饰类也可以修饰方法
Spring CloudSpring Cloud之自定义@SpringCloudProfile注解实现@Profile注解的功能