前端传递数值到后端(控制器)主要有三种方式,分别是请求行传值、请求头传值、请求体传值,下面将根据不同的传值方式分别进行梳理与讲解
目录
一、请求行:
1.1 请求行传值
1.2 控制器接受数据 (请求行)
1.3 响应请求并传递
二、请求头:
2.1 请求头传值
2.2 控制器接受数据 (请求头)
三、请求体:
3.1 请求体传值
3.2 控制器接受数据 (请求体)
四、异步请求控制器响应数据:
一、请求行:
1.1 请求行传值
请求行传值包括form表单提交、URL提交、$ajax()请求的url传值、$.post()/$.get()传值,下面以表单为例,进行模拟“表单提交到控制器,控制器处理请求,将数据响应到页面”
前端jsp页面中写了一个表单,提交到/book/add;代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<form method="get" action="/book/add">
图书名称:<input type="text" name="bookname"><br>
图书作者:<input type="text" name="authorname"><br>
图书价格:<input type="text" name="bookPrice"><br>
<input type="submit">
</form>
</body>
</html>
1.2 控制器接受数据 (请求行)
此控制器类为BookController ,在类上添加@Controller注解声明此类为Springmvc的控制器,在类上添加@RequestMapping(“URL”)声明此控制器的请求url,在一个控制器中可以定义多个方法去处理请求,在每个方法上添加@RequestMapping(“URL”)用于声明当前方法的url。在参数前使用@RequestParam注解用于接收请求行中传递的数据
package com.xgsm.Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Description: SpringMvc-demo01
* Created by WuHuaSen .
* Created Date: 2022/4/26 14:42
* Version: V1.0
*/
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/add")
public void add(@RequestParam String bookname, @RequestParam String authorname, @RequestParam int bookPrice) {
}
}
注意事项:如果控制器中参数名与请求行提交的数据的“key”一致,则可省略@RequestParam。比如此示例中就可省略
1.3 响应请求并传递
请求行响应的方式有两种,第一种是将方法的类型定义为“String”,返回值设置为需要转发的路径、第二种是将方法参数类型定义为“ModeAndView”,在实例ModeAndView的时候设置需要转发的路径,并返回。请求行页面转发并传递数据也有两种方式;第一种是在参数值添加“Model”类型的参数,第二种是添加“HttpServletRequest”类型的参数;具体如下
第一种返回参数是“String”的
package com.xgsm.Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
/**
* Description: SpringMvc-demo01
* Created by WuHuaSen .
* Created Date: 2022/4/26 14:42
* Version: V1.0
*/
@Controller
@RequestMapping("/book")
public class BookController {
// 第一种方式
@RequestMapping("/add")
public String add(@RequestParam String bookname, @RequestParam String authorname, @RequestParam int bookPrice, Model model) {
// 将获取到的bookname传给tips.jsp页面
model.addAttribute("key1",bookname);
return "/tips.jsp";
}
}
第一种返回参数是“ModelAndView”的
package com.xgsm.Controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/book")
public class BookController {
// 第二种
@RequestMapping("/add")
public ModelAndView add(@RequestParam String bookname, @RequestParam String authorname, @RequestParam int bookPrice, HttpServletRequest resp) {
//实例一个ModelAndView
ModelAndView model = new ModelAndView("/tips.jsp");
// 将获取到的bookname传给tips.jsp页面
resp.setAttribute("key1", bookname);
return model;
}
}
二、请求头:
2.1 请求头传值
请求头传值,用的是ajax中的headers属性,进行传值,本示例为向控制器传递一个“token,书写格式如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<input id="button01" type="button" value="Ajax" >
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$("#button01").click(function(){
alert("zhegjkglkjasg");
$.ajax({
url:"book/update1",
type:"post",
contentType:"application/json",
dataType:"json",
headers:{
'token':'wahahah'
},
success:function (res) {
console.log(res);
}
});
});
</script>
</body>
</html>
2.2 控制器接受数据(请求头)
控制器接收请求头传值,在方法参数前添加@RequestHeader注解,即可以接收到请求头传递的数据
package com.xgsm.Controllers;
import com.xgsm.pojo.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* Description: SpringMvc-demo01
* Created by WuHuaSen .
* Created Date: 2022/4/26 14:42
* Version: V1.0
*/
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/update")
public void update(@RequestHeader("token") String token) {
System.out.println(token);
}
}
三 、请求体:
3.1 请求体传值
请求体传值,使用的ajax的data属性,定义contentType,告诉服务器,发送数据的类型,使用JSON.stringify()将对象转化成json类型,具体代码如下;
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<input id="button01" type="button" value="Ajax" >
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$("#button01").click(function(){
alert("zhegjkglkjasg");
var obj={};
obj.bookName="java";
obj.bookAuthor="张珊";
obj.bookPrice=3.33;
$.ajax({
url:"book/list",
type:"post",
contentType:"application/json",
dataType:"json",
headers:{
'token':'wahahah'
},
data:JSON.stringify(obj),
success:function (res) {
console.log(res);
alert(res);
}
});
});
</script>
</body>
</html>
3.2 控制器接受数据(请求体)
控制器接收数据的方式有两种,第一种是使用response的输入流来接收数据、另一种是使用@RequestBody注解,代码如下:
package com.xgsm.Controllers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xgsm.pojo.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.Servlet;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Description: SpringMvc-demo01
* Created by WuHuaSen .
* Created Date: 2022/4/26 14:42
* Version: V1.0
*/
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/list")
public void list(@RequestBody Book book) {
System.out.println("list---");
System.out.println(book);
}
@RequestMapping("/list2")
public void list2(HttpServletRequest res) throws IOException {
System.out.println("list22222---");
ServletInputStream is = res.getInputStream();
StringBuffer buffer = new StringBuffer();
byte[] bs = new byte[100];
int len =-1;
while ((len =is.read(bs))!=-1){
String s= new String(bs,0,len);
buffer.append(s);
}
System.out.println(buffer.toString());
}
}
注!!!!!!!使用@RequestBody注解接收请求体传值的时候,一定要注意自己属性名的规范,也就是驼峰命名法,要不然会出现部分属性接收不到值的情况;例如上例“ obj.bookName="java";”,如果写成“ obj.BookName="java";”,控制器就接收不到值
四、异步请求控制器响应数据
异步请求控制器响应数据返回给前端方式也有两种,第一种是无返回值类型(void),使用response输出流进行响应,第二种是控制器方法的返回类型设置为ajax请求类的对象类型,在控制器方法前使用@ResponseBody注解,将返回的对象转换json响应给ajax请求。
第一种:
package com.xgsm.Controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xgsm.pojo.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.Servlet;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Description: SpringMvc-demo01
* Created by WuHuaSen .
* Created Date: 2022/4/26 14:42
* Version: V1.0
*/
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/update2")
public void update2(@RequestBody Book book,HttpServletResponse response) throws IOException {
System.out.println("update2---");
System.out.println(book);
// 使用ObjectMapper将对象转换成Json格式字符串
String s = new ObjectMapper().writeValueAsString(book);
response.setCharacterEncoding("utf-8");
response.setContentType("application/json");
PrintWriter writer = response.getWriter();
writer.println(s);
writer.flush();
writer.close();
}
}
第二种:
package com.xgsm.Controllers;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xgsm.pojo.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.Servlet;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Description: SpringMvc-demo01
* Created by WuHuaSen .
* Created Date: 2022/4/26 14:42
* Version: V1.0
*/
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/update1")
@ResponseBody
public List<Book> bookList() {
List<Book> books = new ArrayList<>();
books.add(new Book("java", "zhangsan", 1.1));
books.add(new Book("c", "lisi", 1.1));
return books;
}
}