springMVC前后端数据及交互部分是最重要的,因为其余部分都被封装好了,我们要做的就是这个部分,我的框架才用SSM,进公司以来在项目组也用到了这些,但是不够全面,系统,脑子里面思路混乱,所以总结下。
交互主要分为三个部分
1.简单参数(比如url带参数,或者ajax传递几个参数(数量不多))(查询)
2.JSON对象(简单,复杂,集合对象)(需要引入jackson的jar包)(保存,更新,批量保存等)
3.数组(批量删除)
废话不说,代码里面有注释,并没有用到和数据库交互(这个demo不需要,那样不利于直接看效果),在此都是模拟的controller返回数据。
前端jsp:
<body>
<p>--------------------------一:URL方式传参数或者传几个基本类型参数 1.HttpServletRequest req 2.@RequestParam注解 3.@PathVariable搭配RESTFul风格URL------------------------</p>
<button type="button" οnclick="sendUrlParam()">点击测试url传参数controller注解方式接收</button>
<p>--------------------------二:返回JSON格式字符串对象参数 @ResponseBody注解演示------------------------------------------------------------------------------------------</p>
<button type="button" οnclick="selectById()">@ResponseBody注解演示</button>
<p>--------------------------三:接收JSON格式字符串对象参数 @RequestBody注解传递json格式对象字符串---------------------------------------------------------------</p>
<button type="button" οnclick="sendJsonStr()">1.点击发送json字符串到后台(单一对象)</button>
<button type="button" οnclick="sendComplexJsonStr()">2.点击发送嵌套json字符串到后台(复杂对象)</button>
<p></p>
<button type="button" οnclick="sendJsonListStr()">3.点击发送json字符串到后台(集合对象)</button>
<p>---------------------------三:传递数组(批量删除)-----------------------------------------------------------------------------------------------------------------</p>
<button type="button" οnclick="sendArrayStr()">点击发送数组到后台</button>
<p>basePath的值是:<span><%=basePath%></span></p></br>
<p>request.getContextPath()的值是:<span><%=path%></span></p>
<script type="text/javascript">
function sendUrlParam() {
$.ajax({
type : 'post',
url : "<%=basePath%>ssm/sendUrlParam?testName=三毛",
dataType : "json",
success : function(data) {
console.log(data);
alert(data.userName);
},
error : function() {
alert("查询失败");
}
});
}
function selectById(){
$.ajax({
type : 'post',
url : "<%=basePath%>ssm/selectUserReturnByJSON",//url的三种写法
// /ssmaven/ssm/selectUserReturnByJSON
// ${pageContext.request.contextPath}/ssm/selectUserReturnByJSON
dataType : "json",
success : function(data) {
console.log(data);
var name = data[1].userName;
alert(name);
},
error : function() {
alert("查询失败");
}
});
}
//
//单个对象User 后台用@RequestBody接受 请求json,输出是json 注意:发送的是JSON对象字符串!!!
function sendJsonStr(){
var jsonData = {
"userId" : "111",
"userName" : "卡丽熙",
"userPassword":"12138",
"userEmail":"888888@gmail.com"
};
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/ssm/sendJsonStr',
contentType:'application/json;charset=utf-8',//指定为json类型,这个属性是配合注解@RequestBody使用的
//数据格式是json串
data:JSON.stringify(jsonData),
success:function(data){//返回json结果
//注意 1条数据不能用data[0].userName的形式取值 因为我们controller返回的不是List<User>
alert(data.userName);
}
});
}
//嵌套对象UserExt 包含一个Goods引用属性 后台用@RequestBody接收 注意:发送的是JSON对象字符串!!!
function sendComplexJsonStr(){
var jsonData = {
"userId" : "666",
"userName" : "卡丽熙",
"userPassword":"12138",
"userEmail":"888888@gmail.com",
"goods":{"name":"商品电视机","price":"2998元"}//注意对象的写法 JS里面 key不加""也可以的{name:"商品电视机",price:"2998元"}
};
$.ajax({
type:'post',
url:'${pageContext.request.contextPath }/ssm/sendComplexJsonStr',
contentType:'application/json;charset=utf-8',//指定为json类型
//数据格式是json串
data:JSON.stringify(jsonData),
success:function(data){//返回json结果
//注意 1条数据不能用data[0].userPassword的形式取值 因为我们controller返回的不是List<User>
alert(data.goods.name);
}
});
}
//List<User>对象
function sendJsonListStr() {
//方式一
/* var jsonData = [ {
"userId" : "111",
"userName" : "卡丽熙",
"userPassword" : "12138",
"userEmail" : "888888@gmail.com",
}, {
"userId" : "222",
"userName" : "瑟太后",
"userPassword" : "23222",
"userEmail" : "7777777@gmail.com",
}, {
"userId" : "333",
"userName" : "三傻",
"userPassword" : "54323",
"userEmail" : "934333@gmail.com",
} ]; */
//方式二
var jsonData=[];
var user1={
"userId" : "111",
"userName" : "卡丽熙",
"userPassword" : "12138",
"userEmail" : "888888@gmail.com",
};
var user2={
"userId" : "222",
"userName" : "瑟太后",
"userPassword" : "23222",
"userEmail" : "7777777@gmail.com",
};
var user3={
"userId" : "333",
"userName" : "三傻",
"userPassword" : "54323",
"userEmail" : "934333@gmail.com",
}
jsonData.push(user1);
jsonData.push(user2);
jsonData.push(user3);
$
.ajax({
type : 'post',
url : '${pageContext.request.contextPath }/ssm/sendJsonListStr',
contentType : 'application/json;charset=utf-8',//指定为json类型
//数据格式是json串,多个对象用[]包装
data : JSON.stringify(jsonData),
success : function(data) {//返回json结果
alert(data[1].userName);
}
});
}
/
//传递数组对象
/**
var ids= new Array();
$("input[class='detailCheck']:checked").each(function(i,k){
var itemId=$(this).attr("itemId");
ids[i]=itemId;
});
*/
function sendArrayStr() {
//1.字面方式定义数组
/* var arrayStr = [];
arrayStr.push("大草原");
arrayStr.push("大白兔");
arrayStr.push("白又白");
arrayStr.push("两只耳朵竖起来"); */
//2.常规方式定义数组
var arrayStr= new Array();
arrayStr[0]="风吹";
arrayStr[1]="草地";
arrayStr[2]="见牛羊";
arrayStr[3]="哗哗哗";
$.ajax({
type : 'post',
url : '${pageContext.request.contextPath }/ssm/sendArrayStr',
traditional : true,//注意,必须要有个设置否则传递数组报400错误。默认为false深度序列化,在此改为true
data : {
"array" : arrayStr
},
success : function(data) {//返回json结果
alert(data.userName);
}
});
}
</script>
</body>
对应controller
/**
* 跳转到springmvc数据交互页面
*/
@RequestMapping(value="/showSpringmvcDataInteractionView")
public ModelAndView showAjaxJSP(){
ModelAndView mv = new ModelAndView();
mv.setViewName("springmvc-data-interaction");
return mv;
}
//第一种方式:url或者简单参数传递
/**
* 测试url传参数controller层接收(3种方法) 1.HttpServletRequest reqquest 2.@RequestParam注解
* 3.@PathVariable搭配RESTFul风格URL
*/
@RequestMapping(value = "/sendUrlParam")
public @ResponseBody
User testURLSendParam(@RequestParam("testName") String name,
HttpServletRequest req) {
// String name=req.getParameter("testName");
User user = new User();
user.setUserName(name);
System.out.println("成功----------------------URL传递的名字是:" + name);
return user;
}
第二种:@ResponseBody注解演示///
/**
* controller层返回JSON方法一:responseBody注解返回JSON
* @requestBody注解ajax需要设置dataType : "json" 以及 contentType : 'application/json;charset=utf-8',
* @return
*/
/*@RequestMapping(value="/selectUserReturnByJSON")
public @ResponseBody User showUser(){
User user = userService.selectUserById(1);
System.out.println("成功----------------------"+user.getUserName());
return user;
}*/
/**
* controller层返回JSON方法二 :ResponseEntity类
* 如果返回的是List<user>------把ResponseEntity<List<User>>泛型换成list<User>即可
* @return
*/
@RequestMapping(value="/selectUserReturnByJSON")
public ResponseEntity<List<User>> showUser(){
List<User> userList=new ArrayList<User>();
User user1=new User();
user1.setUserEmail("23213212@qq.com");
user1.setUserId(11);
user1.setUserName("sam");
user1.setUserPassword("123321");
User user2=new User();
user2.setUserEmail("46432322@qq.com");
user2.setUserId(22);
user2.setUserName("john");
user2.setUserPassword("1234533");
userList.add(user1);
userList.add(user2);
return new ResponseEntity<List<User>>(userList,HttpStatus.OK);
}
///第三种:@RequestBody注解演示///
/**
* 使用@RequestBody注解接受前端发送json格式的字符串对象-------简单对象User
*/
@RequestMapping(value="/sendJsonStr")//
public @ResponseBody User saveUser(@RequestBody User user){
System.out.println(user);
System.out.println("前端发送的json对象字符串的名字是:"+user.getUserName());
return user;
}
/**
* 复杂对象------UserExt
*/
@RequestMapping(value="/sendComplexJsonStr")
public @ResponseBody User sendComplexJsonStr(@RequestBody UserExt userExt){
//String name=req.getParameter("name");
System.out.println(userExt);
System.out.println("前端发送的json对象字符串的名字是:"+userExt.getUserName());
return userExt;
}
/**
* 多个对象list<User>
*/
@RequestMapping(value="/sendJsonListStr")
public @ResponseBody List<User> sendJsonListStr(@RequestBody ArrayList<User> user){
ArrayList<User> userList=user;
for (User u : userList) {
System.out.println(u.toString());
}
//System.out.println("前端获取的JSON对象集合字符串为:------>"+user);
//System.out.println("第三个对象的名字是:------>"+user.get(2).getUserName());
return user;
}
第四种:数组/
/**
* 数组
* 注意:@RequestParam(value="array[]")的话会报错 不可以用[]
*/
@RequestMapping(value="/sendArrayStr")
public @ResponseBody User sendArrsyStr(@RequestParam(value="array") String[] array){
User user=new User();
user.setUserName(array[3]);
System.out.println("数组长度------>"+array.length);
for (String str : array) {
System.out.println("遍历输出数组的值是:------>"+str);
}
return user;
}
界面图示效果:
控制台依次打印:
2017-09-14 13:58:48,663 [http-apr-8080-exec-10] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/ssmmaven/ssm/sendUrlParam]
2017-09-14 13:58:48,664 [http-apr-8080-exec-10] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /ssm/sendUrlParam
2017-09-14 13:58:48,664 [http-apr-8080-exec-10] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public com.lin.domain.User com.lin.controller.UserController.testURLSendParam(java.lang.String,javax.servlet.http.HttpServletRequest)]
2017-09-14 13:58:48,665 [http-apr-8080-exec-10] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'userController'
成功----------------------URL传递的名字是:三毛
2017-09-14 13:58:48,670 [http-apr-8080-exec-10] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Written [User [userId=null, userName=三毛, userPassword=null, userEmail=null]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
2017-09-14 13:58:48,670 [http-apr-8080-exec-10] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-09-14 13:58:48,670 [http-apr-8080-exec-10] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
2017-09-14 13:58:50,493 [http-apr-8080-exec-3] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/ssmmaven/ssm/selectUserReturnByJSON]
2017-09-14 13:58:50,494 [http-apr-8080-exec-3] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /ssm/selectUserReturnByJSON
2017-09-14 13:58:50,495 [http-apr-8080-exec-3] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public org.springframework.http.ResponseEntity<java.util.List<com.lin.domain.User>> com.lin.controller.UserController.showUser()]
2017-09-14 13:58:50,495 [http-apr-8080-exec-3] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'userController'
2017-09-14 13:58:50,500 [http-apr-8080-exec-3] DEBUG [org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor] - Written [[User [userId=11, userName=sam, userPassword=123321, userEmail=23213212@qq.com], User [userId=22, userName=john, userPassword=1234533, userEmail=46432322@qq.com]]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
2017-09-14 13:58:50,501 [http-apr-8080-exec-3] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-09-14 13:58:50,501 [http-apr-8080-exec-3] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
2017-09-14 13:58:52,042 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/ssmmaven/ssm/sendJsonStr]
2017-09-14 13:58:52,043 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /ssm/sendJsonStr
2017-09-14 13:58:52,044 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public com.lin.domain.User com.lin.controller.UserController.saveUser(com.lin.domain.User)]
2017-09-14 13:58:52,045 [http-apr-8080-exec-1] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'userController'
2017-09-14 13:58:52,049 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Reading [class com.lin.domain.User] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
User [userId=111, userName=卡丽熙, userPassword=12138, userEmail=888888@gmail.com]
前端发送的json对象字符串的名字是:卡丽熙
2017-09-14 13:58:52,052 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Written [User [userId=111, userName=卡丽熙, userPassword=12138, userEmail=888888@gmail.com]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
2017-09-14 13:58:52,052 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-09-14 13:58:52,053 [http-apr-8080-exec-1] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
2017-09-14 13:58:53,583 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/ssmmaven/ssm/sendComplexJsonStr]
2017-09-14 13:58:53,583 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /ssm/sendComplexJsonStr
2017-09-14 13:58:53,584 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public com.lin.domain.User com.lin.controller.UserController.sendComplexJsonStr(com.lin.domain.UserExt)]
2017-09-14 13:58:53,584 [http-apr-8080-exec-2] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'userController'
2017-09-14 13:58:53,586 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Reading [class com.lin.domain.UserExt] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
UserExt [goods=Goods [id=null, price=2998元, name=商品电视机], getUserId()=666, getUserName()=卡丽熙, getUserPassword()=12138, getUserEmail()=888888@gmail.com, toString()=User [userId=666, userName=卡丽熙, userPassword=12138, userEmail=888888@gmail.com], getClass()=class com.lin.domain.UserExt, hashCode()=12793969]
前端发送的json对象字符串的名字是:卡丽熙
2017-09-14 13:58:53,591 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Written [UserExt [goods=Goods [id=null, price=2998元, name=商品电视机], getUserId()=666, getUserName()=卡丽熙, getUserPassword()=12138, getUserEmail()=888888@gmail.com, toString()=User [userId=666, userName=卡丽熙, userPassword=12138, userEmail=888888@gmail.com], getClass()=class com.lin.domain.UserExt, hashCode()=12793969]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
2017-09-14 13:58:53,592 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-09-14 13:58:53,592 [http-apr-8080-exec-2] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
2017-09-14 13:58:55,038 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/ssmmaven/ssm/sendJsonListStr]
2017-09-14 13:58:55,039 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /ssm/sendJsonListStr
2017-09-14 13:58:55,040 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public java.util.List<com.lin.domain.User> com.lin.controller.UserController.sendJsonListStr(java.util.ArrayList<com.lin.domain.User>)]
2017-09-14 13:58:55,041 [http-apr-8080-exec-5] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'userController'
2017-09-14 13:58:55,046 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Reading [java.util.ArrayList<com.lin.domain.User>] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
User [userId=111, userName=卡丽熙, userPassword=12138, userEmail=888888@gmail.com]
User [userId=222, userName=瑟太后, userPassword=23222, userEmail=7777777@gmail.com]
User [userId=333, userName=三傻, userPassword=54323, userEmail=934333@gmail.com]
2017-09-14 13:58:55,058 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Written [[User [userId=111, userName=卡丽熙, userPassword=12138, userEmail=888888@gmail.com], User [userId=222, userName=瑟太后, userPassword=23222, userEmail=7777777@gmail.com], User [userId=333, userName=三傻, userPassword=54323, userEmail=934333@gmail.com]]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
2017-09-14 13:58:55,058 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-09-14 13:58:55,058 [http-apr-8080-exec-5] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request
2017-09-14 13:58:56,612 [http-apr-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/ssmmaven/ssm/sendArrayStr]
2017-09-14 13:58:56,613 [http-apr-8080-exec-6] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /ssm/sendArrayStr
2017-09-14 13:58:56,613 [http-apr-8080-exec-6] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public com.lin.domain.User com.lin.controller.UserController.sendArrsyStr(java.lang.String[])]
2017-09-14 13:58:56,613 [http-apr-8080-exec-6] DEBUG [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'userController'
数组长度------>4
遍历输出数组的值是:------>风吹
遍历输出数组的值是:------>草地
遍历输出数组的值是:------>见牛羊
遍历输出数组的值是:------>哗哗哗
2017-09-14 13:58:56,624 [http-apr-8080-exec-6] DEBUG [org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Written [User [userId=null, userName=哗哗哗, userPassword=null, userEmail=null]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@9660915]
2017-09-14 13:58:56,624 [http-apr-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-09-14 13:58:56,624 [http-apr-8080-exec-6] DEBUG [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request