Location>code7788 >text

If you write too many words in the form text box, you will get 404? The reasons and solutions are here!

Popularity:975 ℃/2025-02-17 13:59:35

Table of contents
  • 1. Enctype property of the form
  • 2. 404 Analysis of the cause of error
    • (1) Path segment truncation
    • (2) Backend path resolution logic
  • 3. Causes of the problem due to the number of characters
    • (1) The reason why it is normal when there are fewer words
    • (2) Causes of problems when there are too many words
  • 4. Compatibility issues between POST requests and multipart/form-data
  • 5. Impact of form submission method
    • (1) Automatic form submission ($("#applyaddfm").submit();)
    • (2) Manual submission (httpPost function)
  • 6. Solution
    • (1) Remove enctype="multipart/form-data" (for file-free upload)
    • (2) Submit data using fetch or XMLHttpRequest
    • (3) Adjust the backend parsing logic
  • 6. Backend (JVAV) sets the method to handle multipart/form-data requests:
    • Using Servlet 3.0: Configure MultipartConfig in:
    • Sample code:
    • Key points:
  • 7. Summary

1. Formenctypeproperty

enctypeAttributes are used to specify how form data is encoded when submitted, which determines how the browser encapsulates and sends data.

  1. application/x-www-form-urlencoded
    • not specifiedenctypeThe browser uses this value when .
    • Coding method: The form data will be encoded asName/value pair, special characters are converted to ASCII hexadecimal values. For example, spaces will be converted to+Number.
    • Applicable scenarios: Applicable to regular form submissions, which do not include file uploads.
  2. multipart/form-data
    • Coding method: Form dataBinary form encoding, allows text and binary files to be sent.
    • Data segmentationmultipart/form-dataThe form data will be divided into multiple parts (part), each part has its own boundaries (boundary)。
    • Boundary generation: The browser will automatically generate boundary strings that may take up additional bytes.
    • Browser default behavior:whenenctypeSet asmultipart/form-dataWhen the browser willAutomatic processingSplit and boundary generation of form data.
    • Data formatmultipart/form-dataThe data format is relatively complex, which may cause backend parsing failure or path matching errors.
    • Applicable scenarios: Used for file upload. When the form contains<input type="file">When theenctypeSet asmultipart/form-data
  3. text/plain
    • Coding method: Form data is sent in plain text and is not encoded with special characters. Spaces will be converted to+but special characters will not be encoded.
    • Applicable scenarios: Usually used to send plain text information, such as emails, etc. This format is not commonly used because it does not provide data escape or protection.

Notice:

  • GET method: If the form is usedGETMethod to send data,enctypeInvalid attribute. The data will be sent as a query string of the URL.
  • Server-side processing: In usemultipart/form-dataWhen the backend needs to process to parse this type of data. This is usually achieved by parsing the uploaded file stream.

2. 404 Analysis of the cause of error

404 Errors are usually caused by the requested path not found, rather than being directly caused by character restriction or encoding issues. It may be related to the form data volume or encoding method. Here are some possible path-related issues:

(1) Path segment truncation

When usingmultipart/form-dataWhen submitting a large amount of data, some middleware or servers may have restrictions on the size of the request body, resulting in path information or request parameters being truncated, making the backend unable to correctly match the path.

(2) Backend path resolution logic

If the backend ismultipart/form-dataThe requested path resolution logic is different from that of a normal form and may cause path matching to fail.

3. Causes of the problem due to the number of characters

(1) The reason why it is normal when there are fewer words
  • Small data volume: When the number of words entered is small, the generatedboundaryThere are fewer and divided parts, the data format is relatively simple, and the backend can parse correctly.
  • The path is not truncated: A smaller amount of data will not cause paths or parameters to be truncated, so the request can reach the backend normally.
(2) Causes of problems when there are too many words
  • Too large data volume: When the number of words entered is large, the generatedboundaryand the number of segmented parts increases, the data format becomes complicated, which may lead to failure of back-end parsing.
  • The path or parameter is truncated: A large amount of data may cause the path or parameters to be truncated, causing the request to fail to correctly match the backend path, thus returning a 404 error.
  • Backend restrictions: The backend may be correctmultipart/form-dataThere is a limit on the size of the request body, which will cause resolution failure or path matching errors when exceeding the limit.

4. POSTRequest andmultipart/form-dataCompatibility issues

When usingPOSTRequest andenctype="multipart/form-data"When the following factors may cause problems:

  • boundaryGenerate a question: Automatically generated by the browserboundaryIt may not match the parsing logic of the backend.
  • Field format issues: Some fields may not be included correctly inmultipart/form-datain the request body.

5. Impact of form submission method

$("#applyaddfm").submit();The default submission behavior of the form is used, andhttpPostThe function manually builds a new form and submits it. The difference between the two can cause problems.

(1) Automatic form submission ($("#applyaddfm").submit();
  • If the form isenctypeyesmultipart/form-data, the browser will send the request body in a specific format, but for some reasons (e.g.boundaryIncorrectly generated or the field format is not standardized), which may cause the backend to fail to correctly parse the path or parameters, and then return 404.
(2) Manual submission (httpPostfunction
  • Manually created forms may not be setenctype="multipart/form-data"The browser will use the defaultapplication/x-www-form-urlencodedSubmit data in format, and the backend can parse more stably.

6. Solution

(1) Removeenctype="multipart/form-data"(Applicable for upload without files)

If the form does not require file upload function, removeenctype, let the browser use the defaultapplication/x-www-form-urlencodedCoding method:

<form name="fm" method="post" onsubmit="queryWait()">
   <!-- Form content -->
 </form>
(2) UsefetchorXMLHttpRequestSubmit data

Use modern AJAX methods (e.g.fetch) Submit data and flexibly control the request format:

fetch('${ctx}/lossAndDuty/car_query.do', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams($("#applyaddfm").serialize())
})
.then(response => ())
.then(data => (data));
(3) Adjust the backend parsing logic
  • Increase request body size limit: Ensure that the backend can handle largermultipart/form-dataask.
  • Optimize path matching logic: Ensure that path matching is not affected by the amount of data.

6. Backend (JVAV) settings processingmultipart/form-dataRequest method:

Using Servlet 3.0:Medium configurationMultipartConfig
<web-app>
   <servlet-mapping>
     <servlet-name>default</servlet-name>
     <url-pattern>/</url-pattern>
   </servlet-mapping>

   <multipart-config>
     <max-file-size>10485760</max-file-size> <!-- Maximum file size, unit bytes -->
     <max-request-size>10485760</max-request-size>
     <file-size-threshold>0</file-size-threshold>
   </multipart-config>
 </web-app>
Sample code:
import .*;
 import .*;
 import .*;

 public class FileUploadServlet extends HttpServlet {
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         // Check if it is a multi-part request
         if ((request)) {
             // Configuration file upload
             DiskFileItemFactory factory = new DiskFileItemFactory();
             ServletFileUpload upload = new ServletFileUpload(factory);

             // parse request
             List<FileItem> items = (request);

             for (FileItem item : items) {
                 if (()) {
                     // Process ordinary form fields
                     String fieldName = ();
                     String fieldValue = ();
                     (fieldName + ": " + fieldValue);
                 } else {
                     // Process file fields
                     String fileName = ();
                     (new File("uploads/" + fileName));
                     ("File uploaded: " + fileName);
                 }
             }
         }
     }
 }
Key points:
  • ServletFileUpload: used for parsingmultipart/form-dataask.
  • (): Save the file to the specified path.

7. Summary

Too much content in the form text box causes a 404 error, usually due tomultipart/form-dataComplexity triggers path truncation or backend parsing failure. By removingenctype, using modern AJAX methods or adjusting backend logic can effectively solve this problem.