IllegalArgumentException: The servlets named [myservlet] and [MyServlet] are both mapped to the url-pattern [/MyServlet] which is not permitted [duplicate] - servlets

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>

Related

HTTP Status 405 – Method Not Allowed in Apache Tomcat Server [duplicate]

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

Eclipse: ServletConfig object returns NULL on calling getServletConfig()

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>

Jetty 9.3.6 and Servlet WebAppContext getServletContext() returns null

I am missing something with this I am sure. But I have spent the last few days searching and unfortunately I have not found an answer that seems to fit.
I have a Servlet that extents HttpServlet and overrides init() "not init(ContextConfig)" and in the init() function getServletContext is always returning null. This was not the case while I was using Springs 4.0.x and Jetty 8.1.x I would guess I am doing something wrong but at a loss as to what it is. I have generally removed Springs from the test code, but it still gets null.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<display-name>MyServlet</display-name>
<servlet-name>MyServlet</servlet-name>
<servlet-class>servlet.MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
JavaConfig Starter partial:
WebAppContext root = new WebAppContext();
root.setDescriptor("./WEB-INF/web.xml");
root.setDisplayName("Root Context");
root.setSessionHandler(sesh); //Persist Session across restarts of context
root.setHandler(csh);
root.setMaxFormContentSize(10000000);
// Cron Servlet
System.out.println("Checking root ServletContext ");
if (root.getServletContext() == null)
System.out.println("ServletContext is null");
//ServletHolder test = new ServletHolder(new MyServlet());
//test.setDisplayName("test");
//test.setName("test");
//root.addServlet(test, "/the");
root.setResourceBase(new File("./jsp").getPath());
server.setHandler(root);
//Start the server
server.start();
server.join();
And the servlet:
package servlet;
import java.io.*;
import org.apache.log4j.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
static Logger log = Logger.getLogger(MyServlet.class);
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
// Initialization code...
log.info("MyServlet init()");
super.init();
ServletContext sc = getServletContext();
if (sc == null)
log.info("54: Conext returned null");
}
public void destroy() {
log.info("MyServlet destroy()");
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setHeader("Server", "GoAway");
doProcess(req, resp);
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setHeader("Server", "GoAway");
doProcess(req, resp);
}
private void doProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
// setup no cache
resp.setContentType("text/html");
resp.getWriter().println("<html><head><META HTTP-EQUIV=\"refresh\" content=\"0;URL=/\"></head><body>\n</body>\n</html>");
resp.getWriter().close();
out.close();
return;
}
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setHeader("Server", "GoAway");
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
So this is something I stripped out of a larger application to figure out what I was doing wrong. so somethings might still be un-needed. You can see in the Javaconfig I have tried creating the servlet container there as well, but the results are the same.
So from inside the Start code the servletContext is not null.
but from inside the MyServlet init() code it is always returning null.
I really am not sure what I am doing wrong.
Thanks for your help.
o FYI included Jar's
commons-beanutils-1.9.2.jar
commons-codec-1.9.jar
commons-io-2.2.jar
commons-logging-1.2.jar
javax.el-2.2.6.jar
javax.el-api-2.2.5.jar
javax.mail-1.5.3.jar
javax.servlet-api-3.1.0.jar
jetty-http-9.3.6.v20151106.jar
jetty-io-9.3.6.v20151106.jar
jetty-security-9.3.6.v20151106.jar
jetty-server-9.3.6.v20151106.jar
jetty-servlet-9.3.6.v20151106.jar
jetty-util-9.3.6.v20151106.jar
jetty-webapp-9.3.6.v20151106.jar
jetty-xml-9.3.6.v20151106.jar
log4j-1.2.17.jar
org.apache.jasper.glassfish-2.2.2.v201112011158.jar
slf4 j-api-1.7.13.jar
spring-aop-4.2.3.RELEASE.jar
spring-beans-4.2.3.RELEASE.jar
spring-context-4.2.3.RELEASE.jar
spring-context-support-4.2.3.RELEASE.jar
spring-core-4.2.3.RELEASE.jar
spring-expression-4.2.3.RELEASE.jar
spring-tx-4.2.3.RELEASE.jar
spring-web-4.2.3.RELEASE.jar
Update 2015.12.10:
So I played around a bit with different Jetty Versions. The original code was using 8.1.17 and I decided to upgrade it to 9.3.6. So I downgraded it to 9.3.5, but had the same results. Then I downgraded to 9.2.14 and the problem was resolved. So Either this is a bug in Jetty 9.3.x ( which would seem unlikely as someone would be using this) or with 9.3 their is a different way to configure it. I looked for documentation about it be it all shows the same way that I am doing it.

Getting ClassNotFoundException when trying to implement web filter in my JSF app

i have a JSF app and for some reasons i need to refresh the page on browser back button.I tried implementing the solution given in Force JSF to refresh page / view / form when opened via link or back button by BalusC ,the only difference is that my app runs with servlet version 2.5 so i did the mapping in web.xml as below
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
javax.faces.STATE_SAVING_METHOD
client
javax.faces.CONFIG_FILES
/WEB-INF/faces-config.xml
com.sun.faces.config.ConfigureListener
javax.faces.PROJECT_STAGE
Production
javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE
true
login.xhtml
FacesServlet
javax.faces.webapp.FacesServlet
1
FacesServlet
/faces/
FacesServlet
.jsf
FacesServlet
.faces
FacesServlet
.xhtml
SessionUtil
SessionUtil
com.gaic.lpsr.utilclasses.SessionUtil
SessionUtil
/SessionUtil
<filter>
<filter-name>cacheFilter</filter-name>
<filter-class>com.gaic.lpsr.utilclasses.NoCacheFilter.java</filter-class>
</filter>
<filter-mapping>
<filter-name>cacheFilter</filter-name>
<servlet-name>FacesServlet</servlet-name>
</filter-mapping>
My filter class is
public class NoCacheFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!request.getRequestURI().startsWith(request.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(req, res);
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
// ...
}
I have included the jar servlet-api-2.5.jar.When i try to deploy app in tomcat server(version 6.0.29) i am getting the below error.
SEVERE: Exception starting filter cacheFilter
java.lang.ClassNotFoundException: com.gaic.lpsr.utilclasses.NoCacheFilter.java
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:269)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:422)
at org.apache.catalina.core.ApplicationFilterConfig.(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4001)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4651)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
at org.apache.catalina.core.StandardService.start(StandardService.java:519)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Please guide me how to fix this problem.
Did silly mistake in web.xml :).Solved by removing .java extension in filter mapping
<filter-class>com.gaic.lpsr.utilclasses.NoCacheFilter</filter-class>

#MultipartConfig override in web.xml

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>

Resources