java接收前端参数

目录

  • 前端请求类型
  • 前端传递数据的提交方式
  • 后端接收数据
  • 使用注解

前端请求类型:

1、在前端开发中,有把八种请求,分别为:GET,POST,PUT,DELETE,TRACE,HEAD,OPTIONS,CONNECT,但是最为常用的只有GET请求和POST请求。

  • GET:会将传递的参数以地址栏的形式进行传递,如:http://baidu.com?name=xxx&param=xxx
  • POST:而post请求相反,不会将数据以地址栏的方式传递,这样传递的数据量更大。

前端传递数据的提交方式

1、在前端访问后端接口时,都会设置一个属性Content-Type的值,这个表示设置数据的提交方式,

  • Content-Type:application/x-www-form-urlencoded:默认的提交方式,传递的参数以key-value的形式进行传递。
  • Content-Type:multipart/form-data:用于文件上传
  • Content-Type:application/json:以JSON的格式进行传递

后端接收数据的方式

1、原始的web开发就是jsp+servlet的方式进行,后端要想取得前端的参数,可以通过request对象提供的方法进行。

  • request.getParameter(String paramName);
  • request.getParameterValues()
  • request.getParameterMap()

以form表单提交为例,form表单提交默认使用的是application/x-www-form-urlencoded的提交方式。
范例:使用request.getParameter()接收参数,这里是前端将要提交的数据写到form表单中,输入框标签的input中必须要有name的属性,以key-value的形式将参数传递到后台,后台通过key获取该参数的值。get请求和post请求都可以。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>【获取参数】</title>
<script type="text/javascript" src="<%=path%>/jquery/jquery-2.0.3.min.js"></script>
</head>
<body>
	<form action="http://localhost:8080/servlet-jsp/get_param_demo" method="get">
		<input type="text" name="name"/>
		<input type="text" name="phone"/>
		<button type="submit">提交</button>
	</form>
</body>
</html>

在这里插入图片描述
在这里插入图片描述
后台接收参数

package cn.txp.learn.param;
import java.io.IOException; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GetParamDemo extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.getParam(req, resp);
	}
	public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		String name = req.getParameter("name");
		String phone = req.getParameter("phone");
		System.out.println(name);
		System.out.println(phone);
		return null;
	}
}

正常接收参数
在这里插入图片描述

范例:request.getParameterValues(),如果说此时form表单中,有多个input框的name属性相同,可以是同此方法获取多个值。如下,有四个name相同。

<form action="http://localhost:8080/servlet-jsp/get_param_demo" method="post">
		<input type="text" name="name"/>
		<input type="text" name="name"/>
		<input type="text" name="name"/>
		<input type="text" name="name"/>
		<input type="text" name="phone"/>
		<button type="submit">提交</button>
</form>

后台通过此方法获取值,是一个String的数组。

package cn.txp.learn.param;
import java.io.IOException; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GetParamDemo extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.getParam(req, resp);
	}
	
	public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.setCharacterEncoding("UTF-8");
			String phone = req.getParameter("phone");
			String names[] = req.getParameterValues("name");
			System.out.println(phone);
			for(String name : names) {
				System.out.println(name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

在这里插入图片描述
在这里插入图片描述

范例:request.getParameterMap(),前端form表单还是一样,

<form action="http://localhost:8080/servlet-jsp/get_param_demo" method="post">
		<input type="text" name="name"/>
		<input type="text" name="name"/>
		<input type="text" name="name"/>
		<input type="text" name="name"/>
		<input type="text" name="phone"/>
		<button type="submit">提交</button>
</form>
package cn.txp.learn.param;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GetParamDemo extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.getParam(req, resp);
	}
	
	public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.setCharacterEncoding("UTF-8");
			Map<String, String[]> maps = req.getParameterMap();
			Iterator<Map.Entry<String, String[]>> entry = maps.entrySet().iterator();
			while(entry.hasNext()) {
				Map.Entry<String, String[]> entryi = entry.next();
				String key = entryi.getKey();
				String value[] = entryi.getValue();
				System.out.println(key);
				for(int x = 0 ; x < value.length ; x ++) {
					System.out.println(value[x]);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

输出结果:
在这里插入图片描述

使用ajax传递请求后台

此时通过jquery封装的ajax访问后台,以application/x-www-form-urlencoded;类型进行访问。依然可以使用request提供的方法进行接收。请求的类型get,post都可以。

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>【获取参数】</title>
<script type="text/javascript" src="<%=path%>/jquery/jquery-2.0.3.min.js"></script>
</head>
<body>
</body>
<script>
	$(function(){
		$.ajax({
			url: "http://localhost:8080/servlet-jsp/get_param_demo",
			contentType: "application/x-www-form-urlencoded;charset:utf-8;",
			type: "get",
			data: {"name": "test", "phone": 123123},
			success: function(){
				console.log("成功");
			}
		})
	})
</script>
</html>
package cn.txp.learn.param;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GetParamDemo extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.getParam(req, resp);
	}
	
	public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		String name = req.getParameter("name");
		String phone = req.getParameter("phone");
		System.out.println(name);
		System.out.println(phone);
		return null;
	}
}

输出结果:
在这里插入图片描述

如果说使用application/json数据的类型进行参数的传递,如果是get请求可以通过以上进行获取,复杂的json无法获取,而post则无法获取。
范例:get请求

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>【获取参数】</title>
<script type="text/javascript" src="<%=path%>/jquery/jquery-2.0.3.min.js"></script>
</head>
<body>
</body>
<script>
	$(function(){
		$.ajax({
			url: "http://localhost:8080/servlet-jsp/get_param_demo",
			contentType: "application/json;charset:utf-8;",
			type: "get",
			data: {"name": "test", "phone": 123123},
			success: function(){
				console.log("成功");
			}
		})
	})
</script>
</html>
public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		String name = req.getParameter("name");
		String phone = req.getParameter("phone");
		String obj = req.getParameter("obj");
		System.out.println(name);
		System.out.println(phone);
		System.out.println(obj);
		return null;
	}

后台正常输出。
在这里插入图片描述
在这里插入图片描述

范例:POST请求的json格式。可以看到后台无法获取值。

$(function(){
		$.ajax({
			url: "http://localhost:8080/servlet-jsp/get_param_demo",
			contentType: "application/json;charset:utf-8;",
			type: "post",
			data: {"name": "test", "phone": 123123},
			success: function(){
				console.log("成功");
			}
		})
	})
public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		String name = req.getParameter("name");
		String phone = req.getParameter("phone");
		String obj = req.getParameter("obj");
		System.out.println(name);
		System.out.println(phone);
		System.out.println(obj);
		return null;
	}

可以看到post请求后台获取是null
在这里插入图片描述
在这里插入图片描述
request提供的方式获取的值是以key-value的形式获取的,如果以post请求提交json数据的格式,可以通过二进制流的方式进行读取。
范例:

$(function(){
		$.ajax({
			url: "http://localhost:8080/servlet-jsp/get_param_demo",
			contentType: "application/json;charset:utf-8;",
			type: "post",
			data: {"name": "test", "phone": 123123},
			success: function(){
				console.log("成功");
			}
		})
	})
package cn.txp.learn.param;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GetParamDemo extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.getParam(req, resp);
	}
	
	public String getParam(HttpServletRequest req, HttpServletResponse resp) {
		try {
			InputStream input = req.getInputStream();
			String result = "";
			byte [] b = new byte[1024];
			int len = 0; 
			while((len = input.read(b)) != -1) {
				result = new String(b, "utf-8");
			}
			System.out.println(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}

正常获取参数。
在这里插入图片描述

使用注解:

现在开发中,都是使用springmvc作为控制层的开发框架
范例:接收get请求

$(function(){
		$.ajax({
			url: "http://localhost:8080/springmvc/pages/getparam/getparam.action",
			contentType: "application/json;charset:utf-8;",
			type: "get",
			data: {"param": "值值值"},
			success: function(){
				console.log("成功");
			}
		})
	})
package cn.txp.spring.app.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/pages/getparam/*")
public class GetParamAction {
	@GetMapping("/getparam")
	@ResponseBody
	public String getParam(String param) {
		System.out.println(param);
		return "成功";
	}
}

使用springmvc提供的注解,接收前端传递的数据,如果传递数据的名称为字符串 “name” : “值”,并且名称和后台方法接收参数名称相同,可以直接映射到此参数中。
在这里插入图片描述

如果是复杂的json格式,使用@RequestBody可以接收json的数据体

$(function(){
		var data = {"param": ["值","值","值"]};
		$.ajax({
			url: "http://localhost:8080/springmvc/pages/getparam/getparam.action",
			contentType: "application/json;charset:utf-8;",
			type: "post",
			data: JSON.stringify(data),
			success: function(){
				console.log("成功");
			}
		})
	})
package cn.txp.spring.app.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/pages/getparam/*")
public class GetParamAction {
	
	@PostMapping("/getparam")
	@ResponseBody
	public String getParam(@RequestBody String param) {
		System.out.println(param);
		return "成功";
	}
}

在这里插入图片描述

使用@RequestBody注解时,如果想要接收将接收的json数据与后台实体类进行转换,需要配置jackson开发包:

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.11.3</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.11.3</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>2.11.3</version>
</dependency>

使用时需要注意接收的json对象中,key要和实体类中的属性对应。
范例:

$(function(){
		var data = {title:"名称",num: 123};
		$.ajax({
			url: "http://localhost:8080/springmvc/pages/getparam/getparam.action",
			contentType: "application/json;charset:utf-8;",
			type: "post",
			data: JSON.stringify(data),
			success: function(){
				console.log("成功");
			}
		})
	})
public class News {
	private String title;
	private Integer num;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public Integer getNum() {
		return num;
	}
	public void setNum(Integer num) {
		this.num = num;
	}
	@Override
	public String toString() {
		return "News [title=" + title + ", num=" + num + "]";
	}
}
package cn.txp.spring.app.action;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.txp.spring.app.vo.News;
@Controller
@RequestMapping("/pages/getparam/*")
public class GetParamAction {
	@PostMapping("/getparam")
	@ResponseBody
	public String getParam(@RequestBody News news) {
		System.out.println(news);
		return "成功";
	}
}

输出结果
在这里插入图片描述


版权声明:本文为qq_37291829原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。