您的位置:首页 > 编程语言 > Java开发

spring实战-参数传递,表单处理及表单校验

2017-08-15 21:01 411 查看
第三篇:Spring MVC的参数传递,表单处理及表单校验

在处理应用时,客户端不仅仅是被动的接受服务器传过来的信息,还需要与服务器端进行交互,甚至向服务器提交文案或上传文件

本节主要演示SpringMVC的两种参数传递的方式,创建表单form以及将from表单内容提交到服务器,并进行验证

参数传递

/**
* 通过@RequestParam来接受请求的输入
* @param id
* @param model
* @return
*/
@RequestMapping(value = "/queryInterfacesById", method=RequestMethod.GET)
public String queryInterfacesById(@RequestParam("id")int id, Model model){
Interface interfaces = idatService.queryInterfacesById(id);
model.addAttribute("intf",interfaces);
return "interface";
}

/**
* 通过路径占位符和@PathVariable来接受路径参数
* 其中占位符可以在路径的任何位置
* 这种方式通常用在设计restful风格的API
* @param name
* @param model
* @return
*/
@RequestMapping(value = "/queryInterfacesByName/{name}/intf", method=RequestMethod.GET)
public String queryInterfacesByName(@PathVariable("name")String name, Model model){
Interface interfaces = idatService.queryInterfacesByName(name);
model.addAttribute("intf",interfaces);
return "interface";
}
表单创建

@RequestMapping(value = "/createForm", method=RequestMethod.GET)
public String createForm(){
return "createForm";
}
createForm.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<style>
table{ background:#000}
table td{ background:#FFF}
</style>
<body>
<h2>Interface</h2>
<form method="POST" action="create">
<table>
<tr>
<td>名称</td>
<td><input type="text" name="name"></input></td>
</tr>
<tr>
<td>域</td>
<td><input type="text" name="domain"></input></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="url"></input></td>
</tr>
<tr>
<td>描述</td>
<td><input type="text" name="description"></input></td>
</tr>
</table>
<input type="submit" value="create"></input>
</form>
</body>
</html>


表单提交以及校验

/**
* 直接接受对象类型Interface 作为入参
* form表单中input的属性name和Interface的属性一一对应
* 注解@Valid启用校验功能,会按着Interface中属性的校验规则来校验入参
* 需要注意的是后面的Errors参数需要紧跟@Valid注解的变量后面,error返回该校验参数的校验结果
* 但是如果希望Valid生效,还需要hibernate-validator包,或者同类实现Java Validation API的包
* @param intf
* @return
*/
@RequestMapping(value = "/create", method=RequestMethod.POST)
public String create(@Valid Interface intf, Errors error){
// 如果校验不通过的话,返回创建表单页面
if (error.hasErrors()) {
return "createForm";
}
Interface rintf = idatService.save(intf);
// 当视图解析器遇到 redirect:时,把他解析为重定向的规则,还有一个forward:
// 具体redirect 和 forward 的区别 请参考 http://blog.csdn.net/tidu2chengfo/article/details/73801501 return "redirect:queryInterfacesByName/" + rintf.getName() + "/intf";
}

Interface中需要校验的属性

/**
* 接口名称
* 被@NotNull注解的属性不能为空
*/
@NotNull
private String name;

/**
* 域,必须以http或者https开头
* 被@Size注解的属性必须是String,或集合或数组,且长度符合设定
*/
@Size(min=7, max=100)
private String domain;
字段校验注解主要有:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: