So I have this servlet :
#WebServlet(name = "StudentRegistrationUsn", urlPatterns = {"/university/student/registration"})
#MultipartConfig(maxFileSize = 10*1024*1024,maxRequestSize = 20*1024*1024,fileSizeThreshold = 5*1024*1024)
public class ActionRegistrationServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//handle file upload
}
Everything works fine, files are uploading.
Then I try to override the fileSize and Threshold in web.xml:
<servlet>
<servlet-name>StudentRegistrationUsn</servlet-name>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>20971520</max-request-size>
<file-size-threshold>5242880</file-size-threshold>
</multipart-config>
</servlet>
When I do that, tomcat crashes and whenever I try to access that servlet it gives the following exception:
The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
java.lang.ClassLoader.loadClass(ClassLoader.java:356)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1629)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:461)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1813)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
The <servlet-class> is missing in web.xml. This exception is basically caused because the name of the to-be-loaded class is null.
In fact, you need to redefine everything, including the URL patterns.
<servlet>
<servlet-name>StudentRegistrationUsn</servlet-name>
<servlet-class>com.example.StudentRegistrationUsn</servlet-class>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>20971520</max-request-size>
<file-size-threshold>5242880</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>StudentRegistrationUsn</servlet-name>
<url-pattern>/university/student/registration</url-pattern>
</servlet-mapping>
Related
This question already has answers here:
HTTP Status 405 - HTTP method is not supported by this URL
(2 answers)
Closed 1 year ago.
I am encountering HTTP Status 405 – Method Not Allowed error in my Java Backend.
I am using Apache Tomcat Server
Type Status Report
Message HTTP method GET is not supported by this URL
Description The method received in the request-line is known by the origin server but not supported by the target resource.
Here is the screenshot:
My Web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Backend</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>
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>BatchDisplay</servlet-name>
<servlet-class>com.hello.BatchDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BatchDisplay</servlet-name>
<url-pattern>/BatchDisplay.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>AddServlet</servlet-name>
<servlet-class>com.hello.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddServlet</servlet-name>
<url-pattern>/AddServlet.do</url-pattern>
</servlet-mapping>
</web-app>
When I am executing Post request from Postman, I am getting this error.
My Java backend code:
package com.hello;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class AddServelet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,HttpServletRequest response) throws ServletException
{
try {
String custNumber=request.getParameter("cust_number");
String nameCustomer=request.getParameter("name_customer");
String invoiceID=request.getParameter("invoice_id");
Double TotalOpenAmount=Double.parseDouble(request.getParameter("total_open_amount"));
String dueinDATE=request.getParameter("due_in_date");
String Notes=request.getParameter("notes");
System.out.print("Acquiring Connection");
Connection connection = DriverManager.getConnection("com.mysql.jdbc.Driver", "root", "abcd");
System.out.print("Connected Successfully");
String sql="INSERT INTO invoice
invoice_details(cust_number,name_customer,invoice_id,total_open_amount,due_in_date,notes)
VALUES (?,?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, nameCustomer);
statement.setString(2, custNumber);
statement.setString(3, invoiceID);
statement.setDouble(4, TotalOpenAmount);
statement.setString(5, dueinDATE);
statement.setString(6, Notes);
statement.executeUpdate();
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
}
}
}
I really don't know why is it giving such an error.
Please suggest me a way to debug it.
You need to override doGet method if u wanna call by GET method;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String custNumber=request.getParameter("cust_number");
String nameCustomer=request.getParameter("name_customer");
String invoiceID=request.getParameter("invoice_id");
Double TotalOpenAmount=Double.parseDouble(request.getParameter("total_open_amount"));
String dueinDATE=request.getParameter("due_in_date");
String Notes=request.getParameter("notes");
System.out.print("Acquiring Connection");
Connection connection = DriverManager.getConnection("com.mysql.jdbc.Driver", "root", "abcd");
System.out.print("Connected Successfully");
String sql="INSERT INTO invoice
invoice_details(cust_number,name_customer,invoice_id,total_open_amount,due_in_date,notes)
VALUES (?,?,?,?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, nameCustomer);
statement.setString(2, custNumber);
statement.setString(3, invoiceID);
statement.setDouble(4, TotalOpenAmount);
statement.setString(5, dueinDATE);
statement.setString(6, Notes);
statement.executeUpdate();
}
catch(SQLException e){
e.printStackTrace();
}
finally
{
}
}
When you need to use GET method: override doGet(HttpServletRequest request, HttpServletResponse response), POST- doPost(HttpServletRequest request, HttpServletResponse response), both - doGet and doPost
this is my code . Please help me solve this problem . I m new to servlet and i m trying my best to solve it but i m unable .
public class InsertData extends GenericServlet{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
PrintWriter pw = null ;
ServletConfig conf = getServletConfig(); // This is giving null everytime i m checked it in webpage
String str = cont.getInitParameter("username");
pw = response.getWriter();
pw.println("<html><body><b>conf</b></body><html>");
}
}
and this is my web.xml file :
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>InsertData</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>mydb</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/InsertData</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
I'm getting a lot of errors in my spring MVC app caused by some clients requesting HTTP PROPFIND:
16:59:39,402 ERROR [foo.bar.controllers.ExceptionHandlingController] (default task-12) Uncaught Error: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PROPFIND' not supported
How can I filter this requests so that they don't generate an error in each controller ?
Thanks!
You can use Spring's HandlerInterceptor as below to allow & process the required requests.
RequestMethodInterceptor class:
package com.myproject.RequestMethodInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RequestMethodInterceptor implements HandlerInterceptor {
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//Added PROPFIND method, add any other types NOT allowed
if(request.getMethod().equals("PROPFIND") ) {
//Log or Ignore upon your requirement & return false
return false;
} else {
return true;
}
}
}
XML Configuration:
<mvc:interceptors>
<bean class="com.myproject.RequestMethodInterceptor" />
</mvc:interceptors>
You have to configure the spring org.springframework.web.servlet.DispatcherServlet in managing OPTIONS
In the web.xml you should add something like this
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
This question already has answers here:
java.lang.IllegalArgumentException: The servlets named [X] and [Y] are both mapped to the url-pattern [/url] which is not permitted
(7 answers)
Closed 7 years ago.
I wrote very simple dynamic web application in eclipse Mars(4.5.1) but i cannot start the tomcat server from eclipse. Below is the root cause of the error:
Caused by: java.lang.IllegalArgumentException: The servlets named [myservlet] and [MyServlet] are both mapped to the url-pattern [/MyServlet] which is not permitted
at org.apache.tomcat.util.descriptor.web.WebXml.addServletMapping(WebXml.java:308)
at org.apache.catalina.startup.ContextConfig.processAnnotationWebServlet(ContextConfig.java:2342)
at org.apache.catalina.startup.ContextConfig.processAnnotationsStream(ContextConfig.java:2024)
at org.apache.catalina.startup.ContextConfig.processAnnotationsWebResource(ContextConfig.java:1918)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1139)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:771)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:305)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5154)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
... 6 more
I followed this steps- addeding libraries in Properties -> Java Build Path -> Add Libraries -> Server runtime -> Apache. After that i added Windows -> Preferences -> Serevr -> Runtime Environments -> Apache. Tomcat v8.0 Server is perfectly starting from **C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin **.
My web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>2J2EEProcessingFromData</display-name>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>Testing</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<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>
MyServlrt.java
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html;charset=ISO-8859-1");
PrintWriter pw = response.getWriter();
try{
String username = request.getParameter("username");
String password = request.getParameter("pass");
pw.write("Hello "+username);
pw.write("Your password is:"+password);
} catch(Exception e){
e.printStackTrace();
} finally {
pw.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
pw.write("doGet called");
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
pw.write("doPost called");
processRequest(request, response);
}
#Override
public String getServletInfo(){
return "Shord description";
}
}
Click on Servers Tab double-click on Tomcat then change HTTP port in Ports section to any others .
or Open Server.xml file and change Connector Port . Restart the Server and then Check
It's funny because i'm answering my own question i replaced url-pattern with (.java) extension as below.
<url-pattern>/MyServlet.java</url-pattern>
<url-pattern>/MyServlet</url-pattern>
In my web.xml I've done the following error-page mappings, but when they are invoked those invoked requests are not passing through the filter definitions specified in web.xml file.
<error-page>
<error-code>403</error-code>
<location>/error.vm?id=403</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/error.vm?id=400</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error.vm?id=404</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/servlet-exception.vm</location>
</error-page>
My application is using spring-mvc and I want to handle the handler not found condition from spring mvc. My application is an multi tenant application where some filters are responsible for setting some information related to the schema.
The requests are reaching in my error.vm controller but since they are passing through the filter I'm not able to determine the theme and SecurityContext etc.
How to solve this problem?
Thank you.
Instead of using web.xml's error pages you could use a servlet filter. The servlet filter could be used to catch all exceptions, or just a particular exception such as org.springframework.web.portlet.NoHandlerFoundException. (Is that what you mean by "handler not found" exception?)
The filter would look something like this:
package com.example;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.web.portlet.NoHandlerFoundException;
public class ErrorHandlingFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void destroy() { }
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
try {
chain.doFilter(request, response);
} catch (NoHandlerFoundException e) {
// Or you could catch Exception, Error, Throwable...
// You probably want to add exception logging code here.
// Putting the exception into request scope so it can be used by the error handling page
request.setAttribute("exception", e);
// You probably want to add exception logging code here.
request.getRequestDispatcher("/WEB-INF/view/servlet-exception.vm").forward(request, response);
}
}
}
Then, set this up in web.xml with the help of Spring's DelegatingFilterProxy:
<filter>
<filter-name>errorHandlingFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>errorHandlingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
And then finally, turn the filter into a spring bean inside your spring context xml:
<bean id="errorHandlingFilter" class="com.example.ErrorHandlingFilter" />
You might have to experiment with the order of the filter in the filter chain so that failed requests still go through the other filters you mentioned. If you're having trouble with that, a variation would be to do an HTTP redirect instead of a forward, like this:
try {
chain.doFilter(request, response);
} catch (NoHandlerFoundException e) {
request.getSession().setAttribute("exception", e);
response.sendRedirect("/servlet-exception.vm");
}
That would force the browser to request your error handling page as a new http request, which might make it easier to ensure it goes through all of the right filters first. If you need the original exception object, then you could put it in the session instead of the request.
maybe
<filter-mapping>
<filter-name>SomeFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>