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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值