标签:
了解Spring mvc
https://github.com/spring-projects/spring-mvc-showcase
1. 自定义注解
// 以下是注解接口
Target(value={ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MaskFormat { String value(); }
// 以下是使用注解
@MaskFormat("(###) ###-####")
private String masked;
2. RequestMapping注解
@Controller @RequestMapping("/data") public class RequestDataController { @RequestMapping(value="param", method=RequestMethod.GET) public @ResponseBody String withParam(@RequestParam String foo) { // 对应url /data/param?foo=bar return "Obtained ‘foo‘ query parameter value ‘" + foo + "‘"; } @RequestMapping(value="path/{var}", method=RequestMethod.GET) public @ResponseBody String withPathVariable(@PathVariable String var) { // 对应url /data/path/bar return "Obtained ‘var‘ path variable value ‘" + var + "‘"; } } @Controller public class MappingController { @RequestMapping("/mapping/path") public @ResponseBody String byPath() { // 最常见的 return "Mapped by path!"; } @RequestMapping(value="/mapping/path/*", method=RequestMethod.GET) public @ResponseBody String byPathPattern(HttpServletRequest request) { // 模式匹配到一组 url return "Mapped by path pattern (‘" + request.getRequestURI() + "‘)"; } }
3. java bean就是基础的对象类,每个属性可通过注解添加限制,也可用于json的转化
@XmlRootElement public class JavaBean { @NotNull private String fruit;
@NotEmpty // 非空 private String name; @Min(21) // 限定取值范围 private int age; @DateTimeFormat(iso=ISO.DATE) @Past // 必须是过去的时间,相反的是 Future private Date birthDate; @MaskFormat("(###) ###-####") // 自定义的格式 private String phone; @NumberFormat(style=Style.PERCENT) private BigDecimal percent; public JavaBean() { // 构造方法1 } public JavaBean(String foo) { // 构造方法2 this.foo = foo; } @Override public String toString() { // java bean作为最基础的对象类,一般会重构toString方法 return "JavaBean {foo=[" + foo + "], fruit=[" + fruit + "]}"; } } // 一些场景下(如调用接口)可通过序列化的对象 根据java bean定义反转义回来 String json = MapUtils.getString(params,"json"); JavaBean aBean = JsonUtil.toObject(json, JavaBean.class);
标签:
原文地址:http://www.cnblogs.com/douzhou/p/5883097.html