SpringMVC与ajax数据传递方式

1.springmvc+ajax交互方式:

1.1.text类型数据

$.ajax({
          url:'${pageContext.request.contextPath}/zy/user/existLoginName',//请求地址
          type:'post',//请求类型
          data:{loginName:$("#loginName").val()},//传入后台数据
          dataType:'text',//后台返回数据类型
          success : function(data) {
         alert("成功!");
       },
          error:function(data){
              alert("服务器异常!");
          }
    })
@RequestMapping("/existLoginName")
    public void existLoginName(HttpServletRequest request,HttpServletResponse response){
        String zh = request.getParameter("loginName");
        User u = userService.selectUserByLoginName(zh);
        try {
            if(u!=null){
                response.getWriter().write("exist");
            }else{
                response.getWriter().write("ok");
            }
        } catch (IOException e) {
                e.printStackTrace();
        }    
    }

1.2.json类型数据

后台@ResponseBody传数据到前台

$.ajax({
         url:'${pageContext.request.contextPath}/user/existLname',
         type:'post',
         dataType:'json',
         data:{loginName:$("#loginName").val()},
         success:function(data){
            alert(data.msg);
          }
     //注意:这里不能加下面这行,否则数据会传不到后台
        //contentType:'application/json;charset=UTF-8',
        })
@RequestMapping("/existLname")
 @ResponseBody
 public Map<String, String> searchUser(String loginName){
    User u= userService.selectUserByLoginName(loginName);
     Map<String,String> map = new HashMap<String,String>();
     if(u!=null){
       map.put("msg", "no");
    }else{
      map.put("msg", "ok");
    }
    return map;
 }

@RequestBody接收数据

$.ajax({
                        url:'${pageContext.request.contextPath}/user/existLname',
                        type:'post',
                        contentType:'application/json;charset=UTF-8',//必须有
                        dataType:'json',
                        data:{loginName:$("#loginName").val()},
                        success:function(data){
                            alert(data.msg);
                        }
                    })
@RequestMapping("/existLname")
    @ResponseBody
    public String searchUser(@RequestBody String loginName){
        User u= userService.selectUserByLoginName(loginName);
        JSONObject jo = new JSONObject();
        if(u!=null){
            jo.put("msg", "no");
        }else{
            jo.put("msg", "ok");
        }
        return jo.toString();
    }

2、GET、POST、PUT、DELETE请求方式总结

1、GET

get请求是用来获取数据的,只是用来查询数据,不对服务器的数据做任何的修改,新增,删除等操作。
在这里我们认为get请求是安全的,以及幂等的。安全就是指不影响服务器的数据,幂等是指同一个请求发送多次返回的结果应该相同。
特点:
get请求会把请求的参数附加在URL后面,这样会产生安全问题,如果是系统的登陆接口采用的get请求,需要对请求的参数做一个加密。
get请求其实本身HTTP协议并没有限制它的URL大小,但是不同的浏览器对其有不同的大小长度限制

2、POST
post请求一般是对服务器的数据做改变,常用来数据的提交,新增操作。
特点:
post请求的请求参数都是请求体中
post请求本身HTTP协议也是没有限制大小的,限制它的是服务器的处理能力

3、PUT
put请求与post一样都会改变服务器的数据,但是put的侧重点在于对于数据的修改操作,但是post侧重于对于数据的增加。

4、DELETE
delete请求用来删除服务器的资源。

3、SpringMVC 页面数据传递到后台的几种方式

https://blog.csdn.net/benxiaohai888/article/details/78529295

方式一 通过@RequestParam注解来接收

方式二 直接用同名变量来接收

方式三 通过request来接收

下面我们借用a标签来携带数据传递到后台继续测试,a标签提交的方式为GET提交。

准备一个测试jsp页面index.jsp,内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h3>SpringMV参数传递测试</h3>
	<a href="mfc/showwithparam?msg=welcomespringmvcparam">测试带参数(@RequestParam注解来接收)</a>
	<br />
	<a href="mfc/showwithparam2?msg=welcomespringmvcparam">测试带参数(同名变量来接收)</a>
	<br />
	<a href="mfc/showwithrequest?msg=welcomespringmvcparam">测试带参数(request来接收)</a>
	<br />
</body>
</html>

下面是分别使用三种方式接收数据的方式:

方式一 通过@RequestParam注解来接收

@Controller
@RequestMapping("mfc")
public class MyFirstController {
	/**
	 * 传递参数到控制器的的一种方式(@RequestParam注解来接收)
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "showwithparam")
	public String showWithParam(
			@RequestParam(value = "msg", required = false, defaultValue = "默认值") String str) {
		System.out.println("showwithparam...");
		System.out.println("接收页面传递的参数msg:" + str);
		return "main";
	}	
}

代码解释:通过@RequestParam来接收参数, 表示页面传递参数的名字叫msg,这里定义一个名叫str的变量来接收msg的值,这种方式,要求必须传递过来一个名叫msg的参数,没有传递这个参数的时候就会出现400错误

方式二 直接用同名变量来接收

@Controller
@RequestMapping("mfc")
public class MyFirstController {
 
 
	/**
	 * 传递参数到控制器的的二种方式(同名变量来接收)
	 * 
	 * @param msg
	 * @return
	 */
	@RequestMapping(value = "showwithparam2")
	public String showWithParam2(String msg) {
		System.out.println("showWithParam2...");
		System.out.println("接收页面传递的参数msg:" + msg);
		return "main";
	}
}

代码解释:这里添加了一个参数msg,这个参数和页面提交的数据的名称一致为msg,不管页面是否传递msg参数,都不会报错,传递了,就接收,没有传递,就是null。

方式三 通过request来接收

@Controller
@RequestMapping("mfc")
public class MyFirstController {
 
	/**
	 * 在业务方法中,如果需要使用到内置对象,只需要在方法中,定义对应的形参,即可。
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "showwithrequest")
	public String showWithRequest(HttpServletRequest request) {
		System.out.println("showwithrequest...");
		String msg = request.getParameter("msg");
		System.out.println("通过request接收的msg:" + msg);
		return "show";
	}
}

猜你喜欢

转载自blog.csdn.net/bugle_call/article/details/100019050
今日推荐