Springmvc中,接收页面提交的数据是通过方法形参来接收:
处理器适配器调用springmvc使用反射将前端提交的参数传递给controller方法的形参
springmvc接收的参数都是String类型,所以spirngmvc提供了很多converter(转换器)在特殊情况下需要自定义converter,如对日期数据
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount5")
public String findAccount5(String username,Model model){
model.addAttribute("msg", username);
return "success";
}
@RequestMapping("/findAccount6")
public String findAccount6(String username,Integer age,Model model){
model.addAttribute("msg", username+" "+age);
return "success";
}
}
在index.jsp里面定义超链接
<a href="/account/findAccount5?username=eric">参数接收-基本数据类型a>
<a href="/account/findAccount6?username=eric&age=22">参数接收-多个基本数据类型a>
编写pojo
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
private Address address;
//省略get set toString方法
}
public class Address implements Serializable {
private String provinceName;
private String cityName;
//省略get set toString方法
}
编写controller
package com.wt.controller;
import com.wt.pojo.Account;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/saveAccount")
public String saveAccount(Account account, Model model){
model.addAttribute("msg", account);
return "success";
}
}
在index.jsp里面添加表单
<form action="account/saveAccount" method="post">
账户名称:<input type="text" name="name"><br/>
账户金额:<input type="text" name="money"><br/>
账户省份:<input type="text" name="address.provinceName"><br/>
账户城市:<input type="text" name="address.cityName"><br/>
<input type="submit" value="保存">
form>
(Representational State Transfer,表现层状态转移):URL定位资源时,用HTTP动词(GET,POST,DELETE,PUT)描述操作
在Restful之前的操作:
http://127.0.0.1/user/query?id=1 根据用户id查询用户数据
http://127.0.0.1/user/save 新增用户
http://127.0.0.1/user/update?id=1 修改用户信息
http://127.0.0.1/user/delete?id=1 删除用户信息
RESTful用法:
http://127.0.0.1/user/1 GET 根据用户id查询用户数据
http://127.0.0.1/user POST 新增用户
http://127.0.0.1/user PUT 修改用户信息
http://127.0.0.1/user/1 DELETE 删除用户信息
RESTful总结:
Restful风格就是请求url统一,根据不同的请求方式,请求不同的后台方法。如果需要携带参数,在url上使用/{}占位符。
作用
用于绑定url中的占位符。例如:/account/{id},这个{id}就是url占位符
url支持占位符是spring3.0之后加入的,是springmvc支持rest风格url的重要标志。
描述需要使用指定的请求方式来请求该方法
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping(value="/findAccount7/{id}")
public String findAccount11(@PathVariable Integer id, Model model){
model.addAttribute("msg", id);
return "success";
}
}
测试:在index.jsp里面定义超链接
<a href="/account/findAccount7/123">restful传参a><br>
在web.xml里面设置编码过滤器
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
filter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
测试
tomcat对GET和POST请求处理方式是不同的,GET请求的编码问题,要改tomcat的 配置信息,如下:
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<port>8080port>
<path>/path>
<uriEncoding>UTF-8uriEncoding>
configuration>
plugin>
在index.jsp里面添加日期类型
<form action="account/saveAccount" method="post">
账户名称:<input type="text" name="name"><br/>
账户金额:<input type="text" name="money"><br/>
账户省份:<input type="text" name="address.provinceName"><br/>
账户城市:<input type="text" name="address.cityName"><br/>
开户日期:<input type="text" name="date"><br/>
<input type="submit" value="保存">
form>
在pojo里面添加日期类型
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
private Address address;
//添加日期类型
private Date date;
//省略get set toString方法
}
测试
原因
我们前台传递的是字符串类型的参数,但是后台使用的是Date类型接收的。我们期望springmvc可以帮我们做数据类型的自动转换,显然没有做,所以我们需要自己自定义类型转换器。
Converter接口说明:
定义一个类,实现Converter接口
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
在 springmvc.xml配置文件中配置类型转换器
<mvc:annotation-driven conversion-service="cs">mvc:annotation-driven>
<bean id="cs"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.wt.converter.DateConverter">bean>
set>
property>
bean>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount8")
public String findAccount8(HttpServletRequest request,
HttpServletResponse response){
String username = request.getParameter("name");
String age = request.getParameter("age");
request.setAttribute("msg",username+" "+age);
return "success";
}
}
在index.jsp里面定义超链接
<a href="/account/findAccount8?username=eric&age=19">Servlet接收参数a>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
//也可以不创建ModelAndView,直接在参数中指定
@RequestMapping(value = "/findAccount9")
public ModelAndView findAccount9(ModelAndView mv) {
mv.addObject("msg", "欢迎你 springmvc");
mv.setViewName("success");
return mv;
}
}
在index.jsp里面定义超链接
<a href="/account/findAccount9">ModelAndView参数传递a>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping(value = "/findAccount10")
public String findAccount10(Model model) {
model.addAttribute("msg", "欢迎你 springmvc");
return "success";
}
}
在index.jsp里面定义超链接
<a href="/account/findAccount10">Model参数传递a>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAccount11")
public String findAccount11(HttpServletRequest request,
HttpServletResponse response){
request.setAttribute("msg","欢迎你 springmvc");
return "success";
}
}
在index.jsp里面定义超链接
<a href="/account/findAccount11">ServletAPI传递a>
springmvc 默认使用jackson作为json类库,不需要修改applicationContext-servlet.xml任何配置,只需引入以下类库springmvc就可以处理json数据:
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/saveAccount2")
@ResponseBody
public Map saveAccount2(@RequestBody Account account){
Map<String, Object> map = new HashMap<String, Object>();
map.put("status",200);
map.put("msg",account);
return map;
}
}
在index.jsp里面定义ajax请求
添加按钮
<input type="button" value="测试ajax请求json和响应json" id="testJson"/>
引入js库文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js">script>
编写ajax代码
<script type="text/javascript">
$(function(){
$("#testJson").click(function(){
$.ajax({
type:"post",
url:"/account/saveAccount2",
contentType:"application/json;charset=UTF-8",
data:'{"id":1,"name":"张二狗","money":999.0}',
success:function(data){
if(data.status == 200){
alert(data.msg.name);
alert(data.msg.money);
}
}
})
});
})
script>
测试