SpringBoot常用注解
2019-03-19 11:01
363 查看
SpringBoot常用注解目录
一@Controller和@RestController
@Controller中的方法一般返回HTML的名字,跳转到HTML页面 @RestController中的方法一般返回 String串或者Json串 返回的是数据 @RestController相当于是 @Controller + @ResponseBody
如果想要返回到某个页面并且要携带Json数据则只能用@Controller 并在方法上面加@ResponseBody
二@RequestParam和@RequestBody
1 RequestParam将请求中URL的参数绑定到方法的形参中
http://localhost:8080/hello?name=你好
@Controller public class HelloController { @RequestMapping("/hello") public String hello(Model model, @RequestParam(value="name", required=false, defaultValue="World") String cxname) { model.addAttribute("name", cxname); return "hello"; } }
2 RequestBody用于获取post提交中的参数,把提交的json转化为实体类
三@PathVariable
@PathVariable从restful风格的URL中获取请求参数
@RequestMapping("/rest/{name}") public String resthello(Model model, @PathVariable String name) { model.addAttribute("name", name); return "hello"; }
从浏览器访问
@Valid和Validated
@Valid是使用hibernate validation的时候使用
@Validated 是只用spring Validator 校验机制使用
用于验证表单提交的数据
@Validated @Valid 和BindingResult bindingResult是配对出现,并且形参顺序是固定的(一前一后)。
controller
@PostMapping public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); } message = this.messageRepository.save(message); redirect.addFlashAttribute("globalMessage", "Successfully created a new message"); return new ModelAndView("redirect:/{message.id}", "message.id", message.getId()); }
前台表单
<form id="messageForm" th:action="@{/(form)}" th:object="${message}" action="#" method="post"> <div th:if="${#fields.hasErrors('*')}" class="alert alert-danger" role="alert"> <p th:each="error : ${#fields.errors('*')}" class="m-0" th:text="${error}">Validation error</p> </div> <input type="hidden" th:field="*{id}" th:class="${'form-control' + (#fields.hasErrors('id') ? ' is-invalid' : '')}"/> <div class="form-group"> <label for="summary">Summary</label> <input type="text" th:field="*{summary}" th:class="${'form-control' + (#fields.hasErrors('summary') ? ' is-invalid' : '')}"> </div> <div class="form-group"> <label for="text">Message</label> <textarea th:field="*{text}" th:class="${'form-control' + (#fields.hasErrors('text') ? ' is-invalid' : '')}"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
实体类需要加相应的限制 有哪些注解请查看
valid验证实体类中字段
public class Message { private Long id; @NotEmpty(message = "Text is required.") private String text; @NotEmpty(message = "Summary is required.") private String summary;
相关文章推荐
- Springboot 常用注解
- springboot常用注解
- springboot常用注解
- Spring Boot常用注解汇总
- spring boot之常用注解(二)
- SpringBoot+SpringDataJpa后台常用注解
- SpringBoot 常用注解的通俗解释
- spring boot 常用注解解析
- Springboot 常用注解
- spring boot常用注解详解
- springBoot Restfull 常用注解
- Spring boot 常用注解
- SpringBoot常用注解@Configuration
- Springboot 常用注解
- Spring Boot常用注解(一) - 声明Bean的注解
- SpringBoot | 第六章:常用注解介绍及简单使用
- spring boot 常用注解
- SpringBoot中常用注解
- Spring boot 中常用的注解
- Spring Boot常用注解总结