Request Too Large in apache tomcat 8.5

Viewed 321

I am having the error 'request too large' when submitting a post to the backend. When I add the attribute maxPostSize="4194304" in the connector inside the file server.xml the problem goes away. But I don't want to change the server.xml file, I want to change the file web.xml in WebContent/WEB-INF.

I tried using the following in the web.xml file:

<multipart-config>
  <file-size-threshold>0</file-size-threshold>
  <max-file-size>209715200</max-file-size>
  <max-request-size>209715200</max-request-size>
</multipart-config>

But it does not solve the problem.

Can someone tell me how to solve this by altering the web.xml file please?

I am using java servlet.

2 Answers

Case 1. When you setting Servlet with <servlet> tag in web.xml

You can write the configuration code in <servlet> tag.

For example :

<servlet>
  <servlet-name>TestServlet</servlet-name>
  <servlet-class>com.foo.bar.FileUpload</servlet-class>
  <multipart-config>
    <max-file-size>209715200</max-file-size>
    <max-request-size>209715200</max-request-size>
    <file-size-threshold>0</file-size-threshold>
  </multipart-config>
</servlet>

<servlet-mapping>
  <servlet-name>TestServlet</servlet-name>
  <url-pattern>/test/files/*</url-pattern>
</servlet-mapping>

Case 2. When you setting Servlet with @WebServlet Annotation

You can use @MultipartConfig Annotation on your Servlet Class.

For example :

@MultipartConfig(
  maxFileSize = 209715200,
  maxRequestSize = 209715200,
  fileSizeThreshold = 0
)

The <multipart-config> only applies to forms posted as multipart/form-data, i.e. you need a form like this in your HTML:

<form action="/your-uri" method="post" enctype="multipart/form-data">
  ...
</form>

If you don't specify the enctype attribute explicitly, then the request is posted using application/x-www-form-urlencoded and the connector's maxPostSize applies.

Edit: If you don't expect Tomcat to parse the POST request (i.e. you don't call HttpServletRequest#getParameter nor HttpServletRequest#getPart or similar), there is actually no limit on the size of the request. E.g. you can test with:

public class TestServlet extends HttpServlet {

   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      try (final InputStream is = req.getInputStream()) {
         final long length = is.skip(Long.MAX_VALUE);
         try (final PrintWriter writer = resp.getWriter()) {
            writer.append("Number of bytes read: ");
            writer.println(length);
         }
      }
   }
}

and then use curl --request POST --data-binary @<file_name> <servlet_URI> to send data to the servlet.

Related