`

java annotation 之Spring mvc参数检查

阅读更多

实现Spring mvc参数检查之前,我们先来大概了解一下java annotation:

java.lang.annotation提供了四种元注解,专门注解其他的注解(在自定义注解的时候,需要使用到元注解):

   @Documented –注解是否将包含在JavaDoc中

   @Retention –什么时候使用该注解

   @Target –注解用于什么地方

   @Inherited – 是否允许子类继承该注解

 

  1.)@Retention– 定义该注解的生命周期

  ●   RetentionPolicy.SOURCE : 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。

  ●   RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式

  ●   RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

 

  2.)Target – 表示该注解用于什么地方。默认值为任何元素,表示该注解用于什么地方。可用的ElementType参数包括

  ● ElementType.CONSTRUCTOR:用于描述构造器

  ● ElementType.FIELD:成员变量、对象、属性(包括enum实例)

  ● ElementType.LOCAL_VARIABLE:用于描述局部变量

  ● ElementType.METHOD:用于描述方法

  ● ElementType.PACKAGE:用于描述包

  ● ElementType.PARAMETER:用于描述参数

  ● ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明

 

 3.)@Documented–一个简单的Annotations标记注解,表示是否将注解信息添加在java文档中。

 

 4.)@Inherited – 定义该注释和子类的关系

     @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了         @Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

 

好了,有了以上的介绍,现在开始进入正题:

1.先自定义一个注解类:

 

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IsNotNull {
	String value() default "";
}

 2. 再写一个解析注解的工具类:

 

 

import java.lang.reflect.Field;

public class MyAnnotationUtil {
	 public static String getIsNotNullInfo(Object obj){
		 try {
			 Class<?> clazz = obj.getClass();
			//获得私有的成员属性
	         Field[] fields = clazz.getDeclaredFields();
	         if(fields!=null && fields.length>0){
	             for(Field f : fields){
	                 f.setAccessible(true);
	                 System.out.println(f.getName());
	                 //判断IsNotNull注解是否存在
	                 if(!f.isAnnotationPresent(IsNotNull.class)){
	                	 System.out.println(f.getName()+">>>>>"+f.isAnnotationPresent(IsNotNull.class));
	                     continue;
	                 }else {
	                	 System.out.println(f.getName()+">>>>>"+f.isAnnotationPresent(IsNotNull.class));
	                	 IsNotNull isNotNull = f.getAnnotation(IsNotNull.class);
	                     if(f.get(obj)==null || "".equals(f.get(obj))){
	                    	 System.out.println(isNotNull.value());
	                         return isNotNull.value();
	                     }
	                 }
	             }
	         }
		 }catch (Exception e){
	            return null;
	        }
		 return null;
	 }

 3.好了,最后进行Spring mvc参数检查的实现:

 

    3.1 定义一个view,加入定义注解

     

public class Item implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8663198447200449568L;

	@IsNotNull("名字不能为空")
	private String name;
	
	@IsNotNull("密码不能为空")
	private String pwd;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	
}

   3.1 实现Controller

 

   

@RestController
public class MemberController {

	@RequestMapping(value="/getUserList",method=RequestMethod.POST)
	public List<String> getUserList(@RequestBody Item item) {
		String string = MyAnnotationUtil.getIsNotNullInfo(item);
                System.out.println(string);
		if(string!=null){ //如果参数错误,直接返回
			List<String> listUser = new ArrayList<String>();
			listUser.add(string);
			return listUser;
		}
		System.out.println(item.getName() );
		List<String> listUser = new ArrayList<String>();
		listUser.add("zhangsan");
		listUser.add("lisi");
		listUser.add("yushengjun");
		System.out.println("你调用了一次>>>>>>>");
		return listUser;
	}

	
}

 

 

好了,以上就是java annotation 之Spring mvc参数检查的简单实现。。。。。

大家还可以自定义更多的注解来检查参数,比如:对邮箱,对手机号,对身份证等等。。。。。

分享到:
评论

相关推荐

    Spring.MVC.A.Tutorial.2nd.Edition.1771970316

    Table of Contents Introduction Chapter 1: The Spring Framework Chapter 2: Model 2 and the MVC Pattern Chapter 3: Introduction to Spring MVC Chapter 4: Annotation-Based Controllers Chapter 5: Data ...

    Spring MVC Beginner-s Guide.pdf

    With the power of annotation-based configuration, Spring MVC makes web application development easy for developers. This book is a great companion for beginners who want to learn Spring MVC. With ...

    SpingMVC:使用Annotation使用Spring MVC的演示应用程序

    SpingMVC 使用Annotation使用Spring MVC的演示应用程序

    spring_MVC源码

    14. &lt;bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /&gt; 15. 16. &lt;!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --&gt; 17. &lt;bean class="org....

    springweb3.0MVC注解(附实例)

    &lt;display-name&gt;Spring Annotation MVC Sample &lt;!-- Spring 服务层的配置文件 --&gt; &lt;param-name&gt;contextConfigLocation &lt;param-value&gt;classpath:applicationContext.xml &lt;!-- Spring 容器启动监听器 --&gt; ...

    将dwr集成到spring mvc(dwr的配置是基于xml)

    将dwr集成到spring mvc(dwr的配置是基于xml)

    轻量级java web MVC框架

    一个非常简单的MVC框架,实现了类似Spring MVC的基本功能。 1、包括自动扫描绑定映射路径,只要在web.xml中指定扫描包,系统启动后会将请求url绑定到指定的处理方法上。如: 在web.xml中定义如下: &lt;param-name&gt;...

    Spring攻略(第三版)源代码

    3. Spring Annotation Driven Core Tasks 4. Spring @MVC 5. Spring REST 6. Spring Deployment to the Cloud 7. Spring Social 8. Spring Security 9. Spring Mobile 10. Spring with other Web Frameworks 11. ...

    我如何在Spring MVC中创建动态表,每行都包含一个下拉列表

    大家好,我有一个Spring MVC应用程序,我想做两个步骤。首先从数据库中读取日期,并将其显示在jsp文件的表中,对于表中的每一行,都有一个下拉列表。 jsp文件。下一步是提交表中的数据,但是问题是...

    spring练习项目.7z

    资料包含spring-iocdi-annotation-document,iocdi-annotation-mvc,iocdi-xml-extend,iocdi-annotation-extend proxy,jdkproxy-transaction,jdkproxy-salary,day02-itheima11-spring-08-cglibproxy,day02-itheima11-...

    java sring mvc 及页面提交传参

    import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * ...

    java微信公众号MVC开发框架

    jwx是开源的java公众号开发MVC框架,基于spring配置文件和微信消息或事件注解,通过微信上下文处理一个或多个微信公众号服务请求。目的主要有两个,其一生封装微信请求xml消息为java实体对象,将返回对象转换为xml...

    Getting.started.with.Spring.Framework.2nd.Edition1491011912.epub

    This book is meant for Java developers with little or no knowledge of Spring Framework. All the examples shown in this book use Spring 4. You can download the examples (consisting of 60 sample ...

    spring-boot-annotation-list:Spring Boot应用程序中常用注解的精选列表

    注释的类标记为包含请求处理程序的Spring MVC的Bean @RestController -标记注释类为@Controller豆,并增加了@ResponseBody序列化返回的结果信息 @ Configuration-将带注释的类标记为定义bean的Java配置 @Service-...

    spring-3-mvc-hello-world-example-annotation

    在本地运行该项目$ git clone https://github.com/mkyong/spring3-mvc-maven-annotation-hello-world$ mvn jetty:run 访问http://localhost:8080/spring3 ### 3。 将此项目导入Eclipse IDE $ mvn eclipse:eclipse ...

    Spring中文帮助文档

    2.5.1. Spring MVC合理的默认值 2.5.2. Portlet 框架 2.5.3. 基于Annotation的控制器 2.5.4. Spring MVC的表单标签库 2.5.5. 对Tiles 2 支持 2.5.6. 对JSF 1.2支持 2.5.7. JAX-WS支持 2.6. 其他 2.6.1. 动态...

    spring-boot-annotation

    spring-boot-annotation 演示spring boot的使用,结合supervisor运行 该项目使用Gradle进行构建项目,并且简单使用了testNG做单元测试 项目说明 在配置freemarker作为模版时,使用xml作为mvc配置文件,目前用testng...

    Spring API

    2.5.1. Spring MVC合理的默认值 2.5.2. Portlet 框架 2.5.3. 基于Annotation的控制器 2.5.4. Spring MVC的表单标签库 2.5.5. 对Tiles 2 支持 2.5.6. 对JSF 1.2支持 2.5.7. JAX-WS支持 2.6. 其他 2.6.1. 动态...

    Aspectj in Action: Enterprise AOP with Spring Applications (2nd Edition)

    Building on familiar technologies such as JDBC, Hibernate, JPA, Spring Security, Spring MVC, and Swing, you'll apply AOP to common problems encountered in enterprise applications. This book requires...

    spring-boot-reference.pdf

    Auto-configured Spring REST Docs Tests with Mock MVC Auto-configured Spring REST Docs Tests with REST Assured 43.3.20. User Configuration and Slicing 43.3.21. Using Spock to Test Spring Boot ...

Global site tag (gtag.js) - Google Analytics