#WebServlet annotation doesn't work - java

I checked the following possible answers but not found fix for my problem
1. #WebServlet annotation with Tomcat 7
2. #WebServlet annotation not recognized; init doesn't run
3. #WebServlet annotation doesn't work with Tomcat 8
Here is my servlet-api.jar info:
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.4
Created-By: 1.6.0_37-b06 (Sun Microsystems Inc.)
X-Compile-Source-JDK: 1.6
X-Compile-Target-JDK: 1.6
Name: javax/servlet/
Specification-Title: Java API for Servlets
Specification-Version: 3.0
Specification-Vendor: Sun Microsystems, Inc.
Implementation-Title: javax.servlet
Implementation-Version: 3.0.FR
Implementation-Vendor: Apache Software Foundation
My example class code:
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/ProcessPayment")
public class ProcessPayment extends javax.servlet.http.HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
res.setContentType("text/html; charset=UTF-8");
StringWriter sWriter = new StringWriter();
PrintWriter out = new PrintWriter(sWriter);
try{
SiteTemplate st = new SiteTemplate();
PaymentDecorator pd = new PaymentDecorator();
out.print(
st.header(req)+st.headerButtons(req)+
"<tr><td>"+
pd.ccform(300,"6",1)+
"</td></tr>"+
st.footer());
}catch(Exception ee){
ErrorCheck ec = new ErrorCheck();
ec.errorMsg("ERROR: GSW.ProcessPayment.java", ee);
}
res.getWriter().print(sWriter.toString());
}
}
My web.xml:
<web-app
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"
version="3.0">
When I access it like: http://127.0.0.1:7070/ProcessPayment then following message appears:
HTTP Status 404 - /ProcessPayment
type Status report
message /ProcessPayment
description The requested resource (/ProcessPayment) is not available.
Apache Tomcat/6.0.18
I updated servlet-api but my Tomcat version in Release Note file is:
Apache Tomcat Version 6.0.18
Please advise as to why #WebServlet annotation is not working?`

Related

No processor claimed any of these annotations: javax.servlet.annotation.MultipartConfig

Why isn't a MultipartConfig annotation processor working on the annotated class? When I build my Java project with Gradle I get this warning:
No processor claimed any of these annotations: javax.servlet.annotation.MultipartConfig,javax.servlet.annotation.WebServlet
And when I send a file to that servlet from a form I get
HTTP ERROR 500
Problem accessing /historyUpload/upload. Reason:
Server Error
Caused by:
java.lang.IllegalStateException: No multipart config for servlet
at org.eclipse.jetty.server.Request.getParts(Request.java:2303)
at org.eclipse.jetty.server.Request.getParts(Request.java:2290)
at org.eclipse.jetty.server.Request.getPart(Request.java:2279)
at javax.servlet.http.HttpServletRequestWrapper.getPart(HttpServletRequestWrapper.java:386)
at com.mycom.UploadServlet.doPost(UploadServlet.java:32)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
[...]
But I have javax.servlet-api-3.1.0.jar in my build.gradle - my project module includes several other HttpServlet classes that build and execute OK against it. That JAR does include javax.servlet.annotation.MultipartConfig .
UploadServlet.java :
package com.mycom.uploadservlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#SuppressWarnings("serial")
#MultipartConfig(location="/tmp/upload", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*50)
public class UploadServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
out.printf("Got part: name=%s, size=%d%n",req.getPart("file").getName(), req.getPart("file").getSize());
int i=0;
for(Part part: req.getParts())
{
out.printf("Got part: name=%s, size=%d%n",part.getName(), part.getSize());
part.write(String.format("part-%02d.dat",i++));
}
}
}
The problem was that I defined a <servlet> configuration in web.xml , that overrides the #WebServlet() annotation on the class UploadServlet. I didn't use an #WebServlet annotation, because I had the <servlet> configuration in web.xml. But that overriding also overrides any #MultipartConfig annotation on the class UploadServlet, even if no <multipart-config> block is included in the <servlet> block. So to process a form of enctype="multipart/form-data" either the <servlet> block in web.xml must include a <multipart-config> block, or no <servlet> block in web.xml and instead annotate the class with #MultipartConfig() (and so also #WebServlet).
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.mycom.UploadServlet</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>

java and httpclient java.lang.NoClassDefFoundError

I have problem.
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
public class qq {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
HttpClient httpclient = new DefaultHttpClient();
// HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");
System.out.println("aaaa");
}
}
File manifest.mf:
Manifest-version: 1.0
Main-Class: qq
OS debian 8
java version:
java version "1.8.0_111"
Java(TM) SE Runtime Environment (build 1.8.0_111-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)
And:
javac -cp ./lib/httpclient-4.2.5.jar:./lib/httpcore-4.4.5.jar:./lib/httpmime-4.2.5.jar:./lib/commons-logging-1.2.jar qq.java
jar cfm test.jar manifest.mf qq.class
Its ok, no error, exit code - 0.
I try:
# java -jar test.jar
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/impl/client/DefaultHttpClient
at qq.main(qq.java:18)
Caused by: java.lang.ClassNotFoundException: org.apache.http.impl.client.DefaultHttpClient
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
How to fix this ?
I advise you to use Maven or Gradle because the depandances are loaded automatically.
Maven:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
Gradle:
compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.1'

Class not found Apache Tomcat

I'm new to Apache Tomcat and I'm trying to run a simple servlet program but it says class not found.
Java file:
package com.mkyong;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>Hello Servlet Get</h1>");
out.println("</body>");
out.println("</html>");
}
}
Deployment file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.mkyong.ServletDemo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/Demo1</url-pattern>
</servlet-mapping>
</web-app>
Logs:
java.lang.NoClassDefFoundError: com/mkyong/ServletDemo1 (wrong name: ServletDemo1)
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClass(ClassLoader.java:800)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2904)
org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1173)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1681)
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:936)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:745)
Solved it. I needed an additional jar file that was to be added to the classpath i did and it worked thanks so much.
You .class (remember, .class) file must be present in Tomcat's classpath. Check that.
Tomcat startup.bat calls catalina.bat where classpath is set.
Catalina.bat has got a line...
echo Using CLASSPATH: "%CLASSPATH%"
This will print classpath on the command prompt window from which you called startup.bat/.sh. Use this and search for your file.
If it is not found, your IDE project configuration is not setup correctly to generate .class and put it in required location, e.g. in Maven, it should go to target/classes.
If issue is after deploying war, unzip war and check classes folder. If not found, your build tool is not setup correctly.

Wierd NoSuchMethodError for URLEncodedUtils.format

I am having a call to URLBuilder.build which has this call trace:
Servlet.service() for servlet authv0 threw exception:
java.lang.NoSuchMethodError: org.apache.http.client.utils.URLEncodedUtils.format(Ljava/lang/Iterable;Ljava/nio/charset/Charset;)Ljava/lang/String;
at org.apache.http.client.utils.URIBuilder.encodeQuery(URIBuilder.java:176) [httpclient-4.2.5.jar:4.2.5]
at org.apache.http.client.utils.URIBuilder.buildString(URIBuilder.java:140) [httpclient-4.2.5.jar:4.2.5]
at org.apache.http.client.utils.URIBuilder.build(URIBuilder.java:103) [httpclient-4.2.5.jar:4.2.5]
I see this even has been there since 4.2 and still it gives me a NoSuchMethodError. The jar version that is used is 4.2.5 as you see. Can someone point to what I am missing?
Here is my manifest file from 4.2.5 jar
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: oleg
Build-Jdk: 1.5.0_22
Implementation-Build: tags/4.2.5/httpclient#r1469939; 2013-04-19 18:29
:05+0200
Implementation-Title: HttpComponents HttpClient
Implementation-Vendor: The Apache Software Foundation
Implementation-Vendor-Id: org.apache
Implementation-Version: 4.2.5
Specification-Title: HttpComponents HttpClient
Specification-Vendor: The Apache Software Foundation
Specification-Version: 4.2.5
X-Compile-Source-JDK: 1.5
X-Compile-Target-JDK: 1.5
url: http://hc.apache.org/httpcomponents-client

spring boot app works running as an executable jar but not as a war deployed on jboss EAP 6

I am developing a spring-boot application which uses camel and cxf. I also include the spring-boot-starter-actuator. The actuator end points (e.g. /beans, /info, /env) work fine when executing the application as an executable jar or as a war deployed to Tomcat 8. However, when I deploy the same war to JBoss EAP 6 (AS 7) the actuator end points return a http status of 404. I have tried including the following dependencies in my pom.xml as per the documentation without success.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
<scope>provided</scope>
</dependency>
My application class looks like
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.web.WebApplicationInitializer;
import java.util.Arrays;
#SpringBootApplication
public class EsbApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(EsbApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(EsbApplication.class);
}
}
Any ideas on how I can get the actuator end points working in JBoss EAP
Thanks !
It would appear the JBoss EAP 6 servlet mapping works as /* but not with /
To avoid having to add a web.xml, I had to add the following to my SpringBootServletInitializer class
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(context));
registration.setLoadOnStartup(1);
registration.addMapping("/*"); // required JBOSS EAP 6 / AS 7
super.onStartup(container);
}

Categories