一、SpringBoot产生的背景
Spring Boot 诞生一方面是因为 Spring 自身发展所遇到的问题,另一方面在微服务思想诞生之际,急需要一款快速开发工具来实现微服务技术落地,在这样的背景下诞生了 Spring Boot。
正是由于 Spring IoC 和 Spring Aop 两个强大的功能才有了 Spring,Spring 生态不断的发展才有了 Spring Boot,使用 Spring Boot 让 Spring 更易用更有生命力,Spring Cloud 是基于 Spring Boot 开发的一套微服务架构下的服务治理方案。
Spring Boot 整体的设计思想是:约定优于配置。依赖此设计思路,Spring Boot 进行了大刀阔斧的改革,让开发、测试、部署更为便捷。众多的 Starters 成就了 Spring Boot 的发展,让使用 Spring Boot 开发项目变得更加简单。
二、SpringBoot模拟发送URL
@RunWith(SpringRunner.class) 代表运行一个 Spring 容器
@SpringBootTest
public class HelloTest {
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
//加载某个Controller资源
mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void getHello() throws Exception {
//模拟一个URL
mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=小明")
//设置JSON数据格式,防止乱码
.accept(MediaType.APPLICATION_JSON_UTF8)).//andDo(print());
//判断服务器返回的JSON数据是否有字符串“微笑”
andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("微笑")));
}
@Test
public void getUser() throws Exception {
//获取JSON数据标准写法
String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/getUser"))
.andReturn().getResponse().getContentAsString();
System.out.println("result : "+responseString);
}
//映射到User实体
@Test
public void saveUsers() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/saveUser")
.param("name","")
.param("age","666")
.param("pass","test")
);
}
}
在测试阶段,如果后台需要的是一个@RequestBody映射的实体,可以将其先暂时去掉,模拟发送表单数据。测试通过后,可以将@RequestBody再添加回去。
三、传参
若不在方法上指明 method = RequestMethod.GET 或者 method = RequestMethod.POST,即如果不进行设置默认两种方式的请求都支持。
(1)我们传入一个属性 name,直接使用对象接收也可以支持。
输入:http://localhost:8080/getUser?name=abc&pass=123
@RequestMapping(name = "/getUser")
public User getUser(User user) {
return user;
}
返回JSON数据:{"name":"abc","age":0,"pass":"123"}
(2)使用 URL 进行传参
输入:http://localhost:8080/get/abc
@RequestMapping(value = "get/{name}", method = RequestMethod.GET)
public String get(@PathVariable String name) {
return name;
}
页面显示:abc
四、校验实体错误信息
Java实体上有部分约束。
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
public class User {
@NotEmpty(message = "姓名不能为空")
private String name;
@Max(value = 100, message = "年龄不能大于100岁")
@Min(value = 18, message = "必须年满18岁!")
private int age;
@NotEmpty(message = "密码不能为空")
@Length(min = 6, message = "密码长度不能小于6位")
private String pass;
...
@Valid 参数前面添加 @Valid 注解,代表此对象使用了参数校验;
BindingResult 参数校验的结果会存储在此对象中,可以根据属性判断是否校验通过,校验不通过可以将错误信息打印出来。 在请求到此方法体的时候,就已经触发校验事件了,校验结果存放在BindingResult对象中。
@RequestMapping("/saveUser")
public void saveUser(@Valid User user, BindingResult result) {
System.out.println("user:" + user);
if (result.hasErrors()) {
List<ObjectError> list = result.getAllErrors();
for (ObjectError error : list) {
System.out.println(error.getCode() + "-" + error.getDefaultMessage());
}
}
}
user:com.neo.hello.model.User@749443e3
NotEmpty-姓名不能为空
Max-年龄不能大于100岁
Length-密码长度不能小于6位
五、自定义 Filter
自定义 Filter 两个步骤:
实现 Filter 接口,实现其中的 doFilter() 方法;
添加 @Configuration 注解,将自定义 Filter 加入过滤链。
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
System.out.println("this is MyFilter,url :" + request.getRequestURI());
filterChain.doFilter(servletRequest, servletResponse);
}
}
@Configuration
public class WebConfiguration {
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
//加入过滤器
registration.setFilter(new MyFilter());
//配置拦截规则
registration.addUrlPatterns("/*");
registration.setName("MyFilter");
//设置拦截器优先级,越小优先级越高
registration.setOrder(6);
return registration;
}
}
六、读取配置文件
同时存在 application.yml 和 application.properties,并且里面配置相同,application.properties 的配置会覆盖 application.yml。
#resources/application.properties
neo.title=标题
neo.description=描述
# 读取多个配置文件 , 匹配配置文件中 neo 开头
@Component
@ConfigurationProperties(prefix="neo")
public class NeoProperties {
private String title;
private String description;
//get set..
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Value("${neo.title}")
private String title;
@Resource
private NeoProperties properties;
@Test
public void testSingle2(){
System.out.println(title);
System.out.println(properties.getTitle());
System.out.println(properties.getDescription());
}
}
标题
标题
描述
七、自定义配置文件
# resources / other.properties
other.title=other title
other.blog=other blog
@Component
@ConfigurationProperties(prefix="other")
@PropertySource("classpath:other.properties")
public class OtherProperties {
private String title;
private String blog;
//get set
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
@Resource
private OtherProperties properties;
@Test
public void test(){
System.out.println(properties.getBlog());
System.out.println(properties.getTitle());
}
}
other blog
other title