Skip to content

Commit 1b0d8e0

Browse files
committed
spring notes
1 parent 6d02ebc commit 1b0d8e0

File tree

6 files changed

+291
-0
lines changed

6 files changed

+291
-0
lines changed

Notes/浮点数表示.png

66.8 KB
Loading
Lines changed: 160 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
package com.web.spring.databind;
2+
3+
import com.web.spring.databind.domain.ResponseError;
4+
import com.web.spring.databind.domain.SimpleUser;
5+
import com.web.spring.databind.domain.ComplexUser;
6+
import java.text.SimpleDateFormat;
7+
import java.util.Date;
8+
import javax.validation.Valid;
9+
import org.springframework.beans.propertyeditors.CustomDateEditor;
10+
import org.springframework.http.HttpStatus;
11+
import org.springframework.http.MediaType;
12+
import org.springframework.http.ResponseEntity;
13+
import org.springframework.stereotype.Controller;
14+
import org.springframework.validation.BindingResult;
15+
import org.springframework.web.bind.WebDataBinder;
16+
import org.springframework.web.bind.annotation.GetMapping;
17+
import org.springframework.web.bind.annotation.InitBinder;
18+
import org.springframework.web.bind.annotation.PostMapping;
19+
import org.springframework.web.bind.annotation.RequestBody;
20+
import org.springframework.web.bind.annotation.RequestMapping;
21+
import org.springframework.web.bind.annotation.ResponseBody;
22+
23+
/**
24+
* Created by Administrator on 2017/7/9.
25+
*/
26+
@Controller
27+
@RequestMapping(value = "/databind")
28+
public class DataBind {
29+
30+
// 返回带有http status code的响应体
31+
32+
/**
33+
* TODO http://localhost:18080/databind/simpleObject?name=sun&age=27
34+
* 简单对象映射成对象中的字段,字段从url中的参数中读取
35+
*/
36+
@GetMapping(value = "/simpleObject", produces = "application/json")
37+
public ResponseEntity getSimpleObject(@Valid SimpleUser user, BindingResult result) {
38+
if (result.hasErrors()) {
39+
ResponseError error = new ResponseError(result.getFieldError().getDefaultMessage());
40+
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
41+
}
42+
return new ResponseEntity(user, HttpStatus.OK);
43+
}
44+
45+
/**
46+
* TODO http://localhost:18080/databind/simpleObject?name=sun&age=27&contactInfo.phone=8888888
47+
* 复杂对象映射,成第一级对象的字段加第二级字段的{属性名.字段}
48+
*/
49+
@GetMapping(value = "complexObject")
50+
public ResponseEntity getComplexObject(@Valid ComplexUser user, BindingResult result) {
51+
if (result.hasErrors()) {
52+
ResponseError error = new ResponseError(result.getFieldError().getDefaultMessage());
53+
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
54+
}
55+
return new ResponseEntity(user, HttpStatus.OK);
56+
}
57+
58+
// 指定responseBody的返回格式
59+
60+
/**
61+
* TODO http://localhost:18080/databind/json?name=sunu&age=0015
62+
* 返回json数据
63+
*/
64+
@GetMapping(value = "/json", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
65+
@ResponseBody
66+
public SimpleUser writeJson(@Valid SimpleUser user, BindingResult result) {
67+
return new SimpleUser(user.getName(), user.getAge());
68+
}
69+
70+
/**
71+
* TODO http://localhost:18080/databind/json
72+
* 请求体, 解析json请求体
73+
* {
74+
* "name": "sun",
75+
* "age": 15
76+
* }
77+
*/
78+
@PostMapping(value = "/json", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
79+
@ResponseBody
80+
public SimpleUser readJson(@Valid @RequestBody SimpleUser user, BindingResult result) {
81+
return new SimpleUser(user.getName(), user.getAge());
82+
}
83+
84+
/**
85+
* 生成xml数据的模型, 需要使用注解去定义
86+
*/
87+
@GetMapping(value = "/xml", produces = MediaType.APPLICATION_XML_VALUE)
88+
@ResponseBody
89+
public SimpleUser writeXml(@Valid SimpleUser user, BindingResult result) {
90+
return user;
91+
}
92+
93+
@PostMapping(value = "/xml", produces = MediaType.APPLICATION_XML_VALUE)
94+
@ResponseBody
95+
public SimpleUser readXml(@Valid @RequestBody SimpleUser user, BindingResult result) {
96+
return user;
97+
}
98+
99+
// 不指定responseBody的返回形式, 由客户端决定
100+
101+
/**
102+
* Ref: http://www.baeldung.com/spring-httpmessageconverter-rest
103+
* TODO http://localhost:18080/databind/typeByClient?name=sunu&age=0015
104+
* TODO responseBody返回形式由client上报的header中的Accept决定
105+
* Spring 4中会默认开启注解进行httpMessageConverter
106+
*/
107+
@GetMapping(value = "/typeByClient")
108+
@ResponseBody
109+
public SimpleUser writeByClient(@Valid SimpleUser user, BindingResult result) {
110+
return new SimpleUser(user.getName(), user.getAge());
111+
}
112+
113+
// PropertyEditor 应用: 局部, 使用WebDataBinder绑定
114+
115+
/**
116+
* TODO http://localhost:18080/databind/date?date=2017-07-09
117+
*/
118+
@GetMapping(value = "/date")
119+
@ResponseBody
120+
public String getDate(Date date) {
121+
return date.toString();
122+
}
123+
124+
// @InitBinder("date")
125+
// public void initDate(WebDataBinder binder) {
126+
// binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
127+
// }
128+
129+
130+
// Formatter 应用: 全局/局部 可扩展, 可实现注解配置
131+
// spring 全局配置
132+
// <annotation-driven conversion-service="myDateFormatter">
133+
// </annotation-driven>
134+
//
135+
// <beans:bean id="myDateFormatter"
136+
// class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
137+
// <beans:property name="formatters">
138+
// <beans:set>
139+
// <beans:bean class="com.web.spring.databind.common.MyDateFormatter"></beans:bean>
140+
// </beans:set>
141+
// </beans:property>
142+
// </beans:bean>
143+
// TODO http://localhost:18080/databind/dateFormatter?date2=2017-07-09
144+
// 注意: 传入的参数只能为date2 与方法参数保持一致
145+
@GetMapping(value = "dateFormatter")
146+
@ResponseBody
147+
public String getFormatterDate(Date date2) {
148+
return date2.toString();
149+
}
150+
151+
152+
// Converter 应用:全局/局部 可扩展
153+
// TODO http://localhost:18080/databind/dateConverter?date=2017-07-09
154+
// 注意: 传入的参数只能为date2 与方法参数保持一致
155+
@GetMapping(value = "dateConverter")
156+
@ResponseBody
157+
public String getConverterDate(Date date) {
158+
return date.toString();
159+
}
160+
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package com.web.spring.databind.domain;
2+
3+
import javax.validation.constraints.NotNull;
4+
import javax.validation.constraints.Size;
5+
import javax.xml.bind.annotation.XmlRootElement;
6+
import org.hibernate.validator.constraints.Length;
7+
import org.hibernate.validator.constraints.NotEmpty;
8+
import org.hibernate.validator.constraints.Range;
9+
10+
/**
11+
* Created by Administrator on 2017/6/27.
12+
*/
13+
@XmlRootElement
14+
public class User {
15+
16+
@NotEmpty(message = "name can not be null.")
17+
@Length(min = 2, max = 20)
18+
private String name;
19+
20+
@NotNull(message = "age can not be null")
21+
@Range(min = 12, max = 99, message = "age is between 12 to 99")
22+
private Integer age;
23+
24+
public User() {
25+
}
26+
27+
public User(String name, Integer age) {
28+
this.name = name;
29+
this.age = age;
30+
}
31+
32+
public String getName() {
33+
return name;
34+
}
35+
36+
public void setName(String name) {
37+
this.name = name;
38+
}
39+
40+
public Integer getAge() {
41+
return age;
42+
}
43+
44+
public void setAge(Integer age) {
45+
this.age = age;
46+
}
47+
48+
// @Override
49+
// public boolean equals(Object o) {
50+
// if (this == o) return true;
51+
// if (o == null || getClass() != o.getClass()) return false;
52+
//
53+
// User user = (User) o;
54+
//
55+
// if (!name.equals(user.name)) return false;
56+
// return age.equals(user.age);
57+
// }
58+
//
59+
// @Override
60+
// public int hashCode() {
61+
// int result = name.hashCode();
62+
// result = 31 * result + age.hashCode();
63+
// return result;
64+
// }
65+
66+
// @Override
67+
// public String toString() {
68+
// return "User{" +
69+
// "name='" + name + '\'' +
70+
// ", age=" + age +
71+
// '}';
72+
// }
73+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.web.spring.databind.common;
2+
3+
import java.text.ParseException;
4+
import java.text.SimpleDateFormat;
5+
import java.util.Date;
6+
import org.springframework.core.convert.converter.Converter;
7+
8+
/**
9+
* Created by Administrator on 2017/7/9.
10+
*/
11+
public class MyDateConverter implements Converter<String, Date> {
12+
private static final String pattern = "yyyy-MM-dd";
13+
14+
@Override
15+
public Date convert(String source) {
16+
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
17+
try {
18+
return simpleDateFormat.parse(source);
19+
} catch (ParseException e) {
20+
System.out.println(e.getMessage());
21+
}
22+
return null;
23+
}
24+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.web.spring.databind.common;
2+
3+
import java.text.ParseException;
4+
import java.text.SimpleDateFormat;
5+
import java.util.Date;
6+
import java.util.Locale;
7+
import org.springframework.format.Formatter;
8+
9+
/**
10+
* 相对于Converter,source默认为String,converter接口中的Source可以为任意类型,更加灵活
11+
* Created by Administrator on 2017/7/9.
12+
*/
13+
public class MyDateFormatter implements Formatter<Date>{
14+
private static final String pattern = "yyyy-MM-dd";
15+
16+
@Override
17+
public Date parse(String text, Locale locale) throws ParseException {
18+
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
19+
return simpleDateFormat.parse(text);
20+
}
21+
22+
@Override
23+
public String print(Date object, Locale locale) {
24+
return null;
25+
}
26+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
### `PropertityEditor`
2+
内置的 可扩展, 局部使用`WebDataBinder`
3+
4+
### `Formatter`
5+
内置的 可扩展, 全局, 局部均可使用
6+
7+
### `Converter`
8+
内置的 不可扩展, 全局 局部均可使用

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy