request.getParameter 在 jsp/servlet 中返回 null

问题描述 投票:0回答:1

request.getParameter 在 servlet dopost 方法中返回 null。我已经检查了 http 请求其发送的正确值。我已经在 chrome 网络选项卡中验证了这一点,但在 servlet 中验证了 request.getParameter("UserQuery"); 的值即将为空,不是问题是什么,尝试了谷歌的一些解决方案,但似乎没有任何效果

Jsp代码:

<!DOCTYPE html>
<html>
 <head>
    <title>Chatbot</title>
    <style>
        /* Add responsive CSS styling for the chat interface */
        body {
            font-family: Arial, sans-serif;
            padding: 10px;
        }
        #chat-container {
            border: 1px solid #ccc;
            padding: 10px;
            width: 50%;
            margin: auto;
            height: 400px;
            overflow-y: scroll;
        }
        #chat-input {
            width: 100%;
            padding: 5px;
            box-sizing: border-box;
        }
        #chat-submit {
            padding: 5px;
            cursor: pointer;
        }
        .chat-message {
            margin: 5px 0;
        }
        .user-message {
            text-align: right;
        }
        .bot-message {
            text-align: left;
        }
    </style>
</head>
<body>
    <h2>Chatbot</h2>
    <div id="chat-container">
        <!-- Chat history will be displayed here -->
        <div id="chat-history"></div>
    </div>
    <form   id="chat-form"  method="post"  >
        <input type="text" id="chat-input" name="userQuery" required placeholder="Type your message here..." />
        <input type="button" id="chat-submit" value="Send" onclick="return submitChatForm(event);" />
    </form>

    <script>
        // JavaScript to handle form submission and display chat history
        function submitChatForm(event) {
             event.preventDefault();
            var userQuery = document.getElementById("chat-input").value;
             
            // Create a chat message element for the user's message
            var chatHistory = document.getElementById("chat-history");
            var userMessageElement = document.createElement("div");
            userMessageElement.className = "chat-message user-message";
            userMessageElement.innerText = "You: " + userQuery;
            chatHistory.appendChild(userMessageElement);

            // Send the form data using AJAX
            var formData = new FormData();
            formData.append("UserQuery", userQuery);

            fetch("chatbotServlet", {
                method: "POST",
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Create a chat message element for the bot's response
                var botMessageElement = document.createElement("div");
                botMessageElement.className = "chat-message bot-message";
                botMessageElement.innerText = "Bot: " + data;
                chatHistory.appendChild(botMessageElement);

                // Clear the chat input field
                document.getElementById("chat-input").value = "";

                // Scroll to the bottom of the chat history
                chatHistory.scrollTop = chatHistory.scrollHeight;
            })
            .catch(error => {
                console.error("Error:", error);
            });

            return false; // Prevent form from submitting the traditional way
        }
    </script>
</body>
</html>

Servlet -

package com.java.chatbot;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;



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

// Servlet implementation class ChatbotServlet
 
 
public class ChatbotServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChatbotServlet() {
        super();
    
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
           log("get method called");
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
         
           response.setContentType("text/plain;charset=UTF-8");
     
            String userQuery1 = request.getParameter("UserQuery");
           
            log("userQuery" + userQuery1);
            String botResponse = getBotResponse(userQuery1);

            PrintWriter out = response.getWriter();
            out.print(botResponse);
            out.flush();
    }
    private String getBotResponse(String userQuery) {
        String botResponse = "";

        // Database connection setup
        try {
            // Replace with your database connection details
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chatbot_responses", "root", "");

            // Query to get random response based on user's query
            String query = "SELECT answer FROM chatbot_responses WHERE question = ? ORDER BY RAND() LIMIT 1";
            PreparedStatement stmt = conn.prepareStatement(query);
            stmt.setString(1, userQuery);
           
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                botResponse = rs.getString("answer");
            }
            log("BOTRES" + botResponse);

            // Close resources
            rs.close();
            stmt.close();
            conn.close();
        } 
        
        catch (Exception e) {
            e.printStackTrace();
            botResponse = "Sorry, there was an error processing your request.";
        }
        

        return botResponse;
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://jakarta.ee/xml/ns/jakartaee" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0">
  <servlet>
    <description></description>
    <display-name>ChatbotServlet</display-name>
    <servlet-name>ChatbotServlet</servlet-name>
    <servlet-class>com.java.chatbot.ChatbotServlet</servlet-class>
   
  </servlet>
  <servlet-mapping>
    <servlet-name>ChatbotServlet</servlet-name>
    <url-pattern>/chatbotServlet</url-pattern>
  </servlet-mapping>
  <display-name>chatbot</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>

在尝试 stackoverflow 之前我已经用 google 搜索过了,但没有任何效果

eclipse servlets
1个回答
0
投票

由于您将

FormData
对象与
fetch
API 一起使用,内容被编码为
multipart:form-data
并且参数无法正确解析。如果您尝试获取请求参数,您总是会得到
null

您需要将内容类型标头更改为

x-www-form-urlencoded
并转换表单数据对象。您可以使用
UrlSearchParam
来完成。

fetch("chatbotServlet", {
                method: "POST",
                body: new URLSearchParams(formData)
            })

© www.soinside.com 2019 - 2024. All rights reserved.