React中使用Axios调用getAuditData.jsp无法获取请求参数的问题咨询
Hey there! I totally get why you're stuck here—let's break down the issue and fix it step by step.
为什么request.getParameter()拿不到数据?
When you send data with Axios using axios.post(url, {name: 'john', class: '8'}), Axios automatically sends the data as a JSON payload with the Content-Type: application/json header. But request.getParameter() only works for data sent in the application/x-www-form-urlencoded format (the default for HTML form submissions). That's why your current code isn't picking up the params!
办法1:修改Axios请求,发送表单格式的数据
If you want to keep using request.getParameter() in your JSP, adjust your Axios code to send data in form-encoded format. You can use URLSearchParams (built into modern browsers) for this:
// 创建表单参数对象 const formData = new URLSearchParams(); formData.append('name', 'john'); formData.append('class', '8'); axios.post('ajax/parserAudit/getAuditData.jsp', formData) .then(response => { // 处理成功响应 }) .catch(error => { // 错误处理 });
Now in your JSP, you can grab the params like you originally tried:
<% String name = request.getParameter("name"); // 会拿到"john" String className = request.getParameter("class"); // 会拿到"8"(注意class是Java关键字,别用它当变量名) %>
办法2:在JSP中直接解析JSON请求体
If you prefer to keep sending JSON from the frontend (no changes to Axios), you can read and parse the raw request body in your JSP. Here's how to do it with Jackson (a popular JSON library—make sure you have jackson-databind.jar in your project's WEB-INF/lib folder):
<%@ page import="com.fasterxml.jackson.databind.ObjectMapper" %> <%@ page import="java.io.BufferedReader" %> <%@ page import="java.util.Map" %> <% // 读取请求体中的JSON字符串 BufferedReader reader = request.getReader(); StringBuilder jsonBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonBuilder.append(line); } String jsonPayload = jsonBuilder.toString(); // 解析JSON为Map ObjectMapper objectMapper = new ObjectMapper(); Map<String, Object> params = objectMapper.readValue(jsonPayload, Map.class); // 获取参数 String name = (String) params.get("name"); String className = (String) params.get("class"); %> <!-- 测试输出 --> Name: <%= name %><br> Class: <%= className %>
注意事项:
- Make sure the
Content-Typeheader of your Axios request isapplication/json(Axios sets this by default when sending a JSON object, so you don't need to add it manually). - Avoid using
classas a variable name in Java—it's a reserved keyword, so use something likeclassNameinstead.
内容的提问来源于stack exchange,提问作者Amulya

