I am learning jersey to upload files on server.Got below code from net which is working fine if i am running it through NetBeans but if i deploy the .war file through TomCat then i am getting exception.
<html>
<body>
<h1>File Upload with Jersey</h1>
<form action="rest/file/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
UploadFileService .class
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/"
+ fileDetail.getFileName().substring(2);
System.out.println(uploadedFileLocation+"================="+fileDetail.getFileName());
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
web.xml
<web-app id="WebApp_ID" 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">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.mkyong.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
FileUpload.html
</welcome-file>
</welcome-file-list>
</web-app>
I refered this link and added all the required jar files:
jersey-core-1.18
jersey-multipart-1.18
jersey-server-1.18
jersey-servlet-1.18
asm-3.1
still i am getting below exception
exception
java.lang.IllegalAccessError: tried to access method com.sun.jersey.core.reflection.ReflectionHelper.getContextClassLoader()Ljava/lang/ClassLoader; from class com.sun.jersey.spi.scanning.AnnotationScannerListener
at com.sun.jersey.spi.scanning.AnnotationScannerListener.<init>(AnnotationScannerListener.java:89)
at com.sun.jersey.spi.scanning.PathProviderScannerListener.<init>(PathProviderScannerListener.java:59)
at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:89)
at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:700)
at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:678)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:203)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:825)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:714)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
Jul 14, 2014 8:00:05 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet /rest threw load() exception
java.lang.IllegalAccessError: tried to access method com.sun.jersey.core.reflection.ReflectionHelper.getContextClassLoader()Ljava/lang/ClassLoader; from class com.sun.jersey.spi.scanning.AnnotationScannerListener
at com.sun.jersey.spi.scanning.AnnotationScannerListener.<init>(AnnotationScannerListener.java:89)
at com.sun.jersey.spi.scanning.PathProviderScannerListener.<init>(PathProviderScannerListener.java:59)
at com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
at com.sun.jersey.api.core.PackagesResourceConfig.init(PackagesResourceConfig.java:104)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:78)
at com.sun.jersey.api.core.PackagesResourceConfig.<init>(PackagesResourceConfig.java:89)
at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:700)
at com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:678)
at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:203)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
at javax.servlet.GenericServlet.init(GenericServlet.java:212)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:825)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:714)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:448)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)
I found out that only Glassfish supports Jersey not even JBoss & TomCat
I am using Tomcat and Jetty for Jersey. So it is supported.
The solution for your problem would be to add jersey-bundle from here (http://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle). Choose any one from late releases. I used 1.8 to solve the issue.
Related
Given existing web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<display-name>/</display-name>
<listener><listener-class>m.Web.startup.Listener</listener-class></listener>
<listener><listener-class>m.Store.Listener</listener-class></listener>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<servlet-mapping>
<servlet-name>mmm.com.dispatcher.servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>mmm.com.dispatcher.servlet</servlet-name>
<servlet-class>m.Web.startup.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/Web/config/ConfigWeb.xml
classpath:/Auth/config/ConfigAuth.xml
classpath:/Assets/config/ConfigAssets.xml
classpath:/Accounts/config/ConfigAccounts.xml
classpath:/App/config/ConfigApp.xml
classpath:/Accounts/config/ConfigAccounts.xml
classpath:/Store/config/ConfigStore.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I've added:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.0.48</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>8.0.48</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-logging-juli</artifactId>
<version>8.0.48</version>
</dependency>
and attempted to do:
private static void c() throws LifecycleException {
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir(tmpDir.getAbsolutePath());
tomcat.setPort(8080);
XmlWebApplicationContext context = new XmlWebApplicationContext();
DispatcherServlet servlet = new DispatcherServlet(context);
servlet.setContextConfigLocation("""
classpath:/Web/config/ConfigWeb.xml
classpath:/Auth/config/ConfigAuth.xml
classpath:/Assets/config/ConfigAssets.xml
classpath:/Accounts/config/ConfigAccounts.xml
classpath:/App/config/ConfigApp.xml
classpath:/Accounts/config/ConfigAccounts.xml
classpath:/Store/config/ConfigStore.xml
""");
Tomcat.addServlet(tomcat.addContext(tomcat.getHost(), "/", tmpDir.getAbsolutePath()), "mmm.com.dispatcher.servlet", servlet);
new m.Web.startup.Listener();
new m.Store.Listener();
tomcat.start();
tomcat.getServer().await();
}
But is not working.
The server starts but several things are not working. localhost:8080 results in an error page.
Also tried:
public static void e() throws LifecycleException {
Tomcat tomcat = new Tomcat() {
#Override
public Context addWebapp(String contextPath, String docBase) throws ServletException {
Context context = null;
try {
context = new StandardContext();
context.setName(contextPath);
context.setPath(contextPath);
context.setDocBase(docBase);
context.setRealm(this.getHost().getRealm());
ContextConfig contextConfig = new ContextConfig();
context.addLifecycleListener(contextConfig);
String pathToWebXml = docBase + "Store/web.xml";
if (new File(pathToWebXml).exists()) {
contextConfig.setDefaultWebXml(pathToWebXml);
} else {
contextConfig.setDefaultWebXml("org/apache/catalin/startup/NO_DEFAULT_XML");
}
host.addChild(context);
} catch (Exception e) {
log.error("Error deploying webapp", e);
}
return context;
}
};
tomcat.setPort(8081);
Service service = tomcat.getService();
service.addConnector(sslConnector());
try {
URL resource = TomcatServer.class.getClassLoader().getResource(".");
tomcat.addWebapp("", resource.getPath());
//add others here...
} catch (ServletException e) {
log.error("Problem webapp. Could be fatal?");
}
tomcat.start();
tomcat.getServer().await();
}
But this results in errors such as :
WARNING: Failed to scan
[file:/Users/j/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar] from classloader hierarchy
java.io.IOException: java.lang.reflect.InvocationTargetException
at org.apache.tomcat.util.compat.Jre9Compat.jarFileNewInstance(Jre9Compat.java:185)
at org.apache.tomcat.util.scan.JarFileUrlJar.<init>(JarFileUrlJar.java:65)
at org.apache.tomcat.util.scan.JarFactory.newInstance(JarFactory.java:49)
at org.apache.tomcat.util.scan.StandardJarScanner.process(StandardJarScanner.java:374)
at org.apache.tomcat.util.scan.StandardJarScanner.processURLs(StandardJarScanner.java:309)
at org.apache.tomcat.util.scan.StandardJarScanner.doScanClassPath(StandardJarScanner.java:278)
at org.apache.tomcat.util.scan.StandardJarScanner.scan(StandardJarScanner.java:229)
at org.apache.catalina.startup.ContextConfig.processJarsForWebFragments(ContextConfig.java:1898)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1131)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:783)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
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:5212)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.GeneratedConstructorAccessor6.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.apache.tomcat.util.compat.Jre9Compat.jarFileNewInstance(Jre9Compat.java:182)
... 21 more
Caused by: java.nio.file.NoSuchFileException: /Users/j/.m2/repository/xalan/xalan/2.7.2/xercesImpl.jar
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixFileAttributeViews$Basic.readAttributes(UnixFileAttributeViews.java:55)
at java.base/sun.nio.fs.UnixFileSystemProvider.readAttributes(UnixFileSystemProvider.java:148)
at java.base/java.nio.file.Files.readAttributes(Files.java:1843)
at java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1198)
at java.base/java.util.zip.ZipFile$CleanableResource.<init>(ZipFile.java:701)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:240)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:171)
at java.base/java.util.jar.JarFile.<init>(JarFile.java:347)
... 26 more
Jun 23, 2021 2:57:15 PM org.apache.tomcat.util.scan.StandardJarScanner processURLs
WARNING: Failed to scan [file:/Users/j/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar] from classloader hierarchy
java.io.IOException: java.lang.reflect.InvocationTargetException
at org.apache.tomcat.util.compat.Jre9Compat.jarFileNewInstance(Jre9Compat.java:185)
at org.apache.tomcat.util.scan.JarFileUrlJar.<init>(JarFileUrlJar.java:65)
at org.apache.tomcat.util.scan.JarFactory.newInstance(JarFactory.java:49)
at org.apache.tomcat.util.scan.StandardJarScanner.process(StandardJarScanner.java:374)
at org.apache.tomcat.util.scan.StandardJarScanner.processURLs(StandardJarScanner.java:309)
at org.apache.tomcat.util.scan.StandardJarScanner.doScanClassPath(StandardJarScanner.java:278)
at org.apache.tomcat.util.scan.StandardJarScanner.scan(StandardJarScanner.java:229)
at org.apache.catalina.startup.ContextConfig.processJarsForWebFragments(ContextConfig.java:1898)
at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1131)
at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:783)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
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:5212)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398)
at java.base/java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:264)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.GeneratedConstructorAccessor6.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
at org.apache.tomcat.util.compat.Jre9Compat.jarFileNewInstance(Jre9Compat.java:182)
... 21 more
Caused by: java.nio.file.NoSuchFileException: /Users/j/.m2/repository/xalan/xalan/2.7.2/xml-apis.jar
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:106)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixFileAttributeViews$Basic.readAttributes(UnixFileAttributeViews.java:55)
at java.base/sun.nio.fs.UnixFileSystemProvider.readAttributes(UnixFileSystemProvider.java:148)
at java.base/java.nio.file.Files.readAttributes(Files.java:1843)
at java.base/java.util.zip.ZipFile$Source.get(ZipFile.java:1198)
at java.base/java.util.zip.ZipFile$CleanableResource.<init>(ZipFile.java:701)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:240)
at java.base/java.util.zip.ZipFile.<init>(ZipFile.java:171)
at java.base/java.util.jar.JarFile.<init>(JarFile.java:347)
... 26 more
Note that currently I am starting it from within a static void main from within Intellij.
The method e() here relies on parsing the existing web.xml file, but this is not working and it fails it seems due to lacking classpath stuff.
The first method c() relies on trying to replicate the configuration, but I am missing ways of trying to properly replicating it.
I am unable for instance to add a Listener in the same manner, and I am unable to configure for instance the session-config parameter.
The first one has no classpath issues and starts but I think some things like the listeners are not properly set up, nor their events fired.
EDIT 1:
Perhaps this the way to add listeners, in c():
Context ctx = tomcat.addContext(tomcat.getHost(), "/", tmpDir.getAbsolutePath());
ctx.addApplicationListener(m.Web.startup.Listener.class.getCanonicalName());
ctx.addApplicationListener(m.Store.Listener.class.getCanonicalName());
But again things start up, but still error in tomcat. Unsure if the classpath: ... in original web.xml mimicked in c() are accurately applied as well.
EDIT 2:
Now gotten most things up, however WebSockets (annotated in the code) is not being picked up, as well as HttpSessionListener not being triggered.
In web.xml you could define a listener that implemented several interfaces such as ServletContextListener, HttpSessionListener but with embedded Tomcat this does not seem to work. I am also not able to register them separately either as of now, but that should be possible. Still annoying.
I just wish you could just feed it the web.xml and it could configure itself, just like the standalone one does. I don't get why that has to be so hard.
private static void c() throws LifecycleException, ServletException, URISyntaxException, DeploymentException, IOException {
File tmpDir = new File(System.getProperty("java.io.tmpdir"));
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir(tmpDir.getAbsolutePath());
tomcat.setPort(8080);
Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());
ctx.addApplicationListener(m.Web.startup.Listener.class.getCanonicalName());
ctx.addApplicationListener(m.Store.Listener.class.getCanonicalName());
ctx.addApplicationListener(Listener.class.getCanonicalName());
ctx.setSessionTimeout(30);
Wrapper wrapper = Tomcat.addServlet(ctx, "mmm.com.dispatcher.servlet", m.Web.startup.DispatcherServlet.class.getCanonicalName());
wrapper.addInitParameter("contextClass", org.springframework.web.context.support.XmlWebApplicationContext.class.getCanonicalName());
wrapper.addInitParameter("contextConfigLocation", """
classpath:/Web/config/ConfigWeb.xml
classpath:/Auth/config/ConfigAuth.xml
classpath:/Assets/config/ConfigAssets.xml
classpath:/Accounts/config/ConfigAccounts.xml
classpath:/App/config/ConfigApp.xml
classpath:/Accounts/config/ConfigAccounts.xml
classpath:/Store/config/ConfigStore.xml
""");
wrapper.setLoadOnStartup(1);
if ( true ) {
wrapper.addMapping("/");
}
else if ( false ) {
ctx.addServletMappingDecoded("/", "mmm.com.dispatcher.servlet", true);
}
tomcat.start();
if ( false ) {
ContainerProvider.getWebSocketContainer().connectToServer(Socket.class, new URI("ws://"));
}
tomcat.getServer().await();
}
I am facing MyClass is not a javax.servlet.Servlet warn and application is not going up while deploying in jetty server.
Earlier when running on jdk8 and weblogic it was working fine. i am facing this issue while migrating from jdk8 to openjdk11 and weblogic to jetty.
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SomeName</display-name>
<listener>
<listener-class>StaticQueueConnectionServlet</listener-class>
</listener>
<servlet>
<servlet-name>Soap11HttpPort</servlet-name>
<servlet-class>MyClass</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>SchedulerServlet</servlet-name>
<servlet-class>SchedulerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Soap11HttpPort</servlet-name>
<url-pattern>/Soap11HttpPort</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SchedulerServlet</servlet-name>
<url-pattern>/SchedulerServlet</url-pattern>
</servlet-mapping>
My webservice class
#javax.jws.WebService(serviceName = "XXXXXX",
name = "Soap11HttpPort",
targetNamespace = "xxxxxxx",
endpointInterface = "MyInterface")
public final class MyClass implements MyInterface {
#javax.annotation.Resource
private WebServiceContext context;
public Resp ping(final Request request) throws Exception {
return pesponse;
}
public Response printDocument(
final Request request) throws Exception {
try {
final MessageContext ctx = context.getMessageContext();
final HttpServletRequest request = (HttpServletRequest) ctx.get(MessageContext.SERVLET_REQUEST);
return response;
} catch (Exception exc) {
}
}
}
I am Getting
javax.servlet.UnavailableException: Servlet class MyClass is not a javax.servlet.Servlet
at org.eclipse.jetty.servlet.ServletHolder.checkServletType(ServletHolder.java:547)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:380)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.servlet.ServletHandler.lambda$initialize$0(ServletHandler.java:745)
at java.base/java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:357)
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:739)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:361)
at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1443)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1407)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:821)
at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:276)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:524)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.deploy.bindings.StandardStarter.processBinding(StandardStarter.java:46)
at org.eclipse.jetty.deploy.AppLifeCycle.runBindings(AppLifeCycle.java:188)
at org.eclipse.jetty.deploy.DeploymentManager.requestAppGoal(DeploymentManager.java:513)
at org.eclipse.jetty.deploy.DeploymentManager.addApp(DeploymentManager.java:154)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.fileAdded(ScanningAppProvider.java:172)
at org.eclipse.jetty.deploy.providers.WebAppProvider.fileAdded(WebAppProvider.java:436)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider$1.fileAdded(ScanningAppProvider.java:66)
at org.eclipse.jetty.util.Scanner.reportAddition(Scanner.java:622)
at org.eclipse.jetty.util.Scanner.reportDifferences(Scanner.java:538)
at org.eclipse.jetty.util.Scanner.scan(Scanner.java:402)
at org.eclipse.jetty.util.Scanner.doStart(Scanner.java:318)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.deploy.providers.ScanningAppProvider.doStart(ScanningAppProvider.java:145)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.deploy.DeploymentManager.startAppProvider(DeploymentManager.java:599)
at org.eclipse.jetty.deploy.DeploymentManager.doStart(DeploymentManager.java:249)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:169)
at org.eclipse.jetty.server.Server.start(Server.java:407)
at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:117)
at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:106)
at org.eclipse.jetty.server.Server.doStart(Server.java:371)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:72)
at org.eclipse.jetty.xml.XmlConfiguration.lambda$main$0(XmlConfiguration.java:1824)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at org.eclipse.jetty.xml.XmlConfiguration.main(XmlConfiguration.java:1773)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.eclipse.jetty.start.Main.invokeMain(Main.java:218)
at org.eclipse.jetty.start.Main.start(Main.java:491)
at org.eclipse.jetty.start.Main.main(Main.java:77)
Using Spring, JPA, Restful Web Service and JSon. And Error is here.
Exception Description: No transaction is currently active
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.throwCheckTransactionFailedException(EntityTransactionWrapper.java:87) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionWrapper.checkForTransaction(EntityTransactionWrapper.java:50) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:2041) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush(EntityManagerImpl.java:863) [eclipselink-2.5.1.jar:2.5.1.v20130918-f2b9fc5]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_25]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:365) [spring-orm.jar:3.1.1.RELEASE]
at $Proxy24.flush(Unknown Source) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_25]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_25]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_25]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240) [spring-orm.jar:3.1.1.RELEASE]
at $Proxy24.flush(Unknown Source) at com.hs.rest.springController.user.persistance.UserDAO.insertUser(UserDAO.java:62) [classes:]
at com.hs.rest.springController.user.service.UserService.addNewUser(UserService.java:65) [classes:]
at com.hs.rest.springController.StateController.getDefaultMovie(StateController.java:28) [classes:]
My Restservice Controller class
#Controller
public class StateController {
private static final Logger logger = Logger.getLogger(StateController.class);
#Resource(name = "UserService")
private IUserService userService;
#RequestMapping(value = "/movie", method = RequestMethod.GET)
public #ResponseBody
User getDefaultMovie() {
logger.debug("getDefaultMovie() Method is started !");
System.out.println("getDefaultMovie() Method is started !");
User user = new User();
user.setName("TEST");
userService.addNewUser(user);
logger.debug("getDefaultMovie() Method is finished ! " + user.getName());
System.out.println("getDefaultMovie() Method is finished ! " + user.getName());
return user;
}
}
Services class
#Service("UserService")
public class UserService implements IUserService {
private Logger logger = Logger.getLogger(this.getClass());
#Resource(name = "UserDAO")
private IUserDAO userDAO;
#Transactional(propagation = Propagation.REQUIRED)
public void addNewUser(User user) {
try {
logger.debug("insertUser() method has been started.");
user = userDAO.insertUser(user);
logger.debug("insertUser() method has been finished.");
} catch (DAOException e) {
logger.error("insertUser() method has been failed.");
throw new SystemException(e.getErrorCode(), "Faield to add new User.", e);
}
}
}
Configuration setup is here.
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"
id="WebApp_ID" version="3.0">
<display-name>restful</display-name>
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.hs.rest</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-beans.xml</param-value>
</context-param>
My question is how can i make the transaction active.
pls, help me. And sorry for my eng and question experience. :)
Make sure you have #Transactional on your services.
I have included jar files jersey-archive-1.18 , jersey-multipart.jar and mimepull.jar
This is my class file (UploadFileService.java) inside the package com.mkyong.rest
package com.mkyong.rest;
import javax.ws.rs.Path;
//import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile( #FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
System.out.println("ok");
/* String uploadedFileLocation = "d://upload/" + fileDetail.getFileName();*/
String uploadedFileLocation = "d://upload/" + "abc.pdf";
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This Upload.html
<form action="rest/file/upload" method="post" enctype="multipart/form-data" style="margin-top:20px;margin-bottom:30px;width:100%;height:60px;">
<input type="file" name="file" class="btn btn-info btn-xm" style="float:left;margin-right:6px;margin-bottom:10px;"/>
<p>Target Upload Path : <input type="text" name="path" /></p>
<input type="submit" class="btn btn-warning" value="Upload" style="float:left;" id="Map" value="Map" onclick="showImg()"/>
<img src="image/loading.gif" id="map_img" style="display: none;"/>
<span id="countdown" class="btn btn-danger" style="float:right;"></span>
</form>
And this is the servlet mapping in web.xml config
<display-name>RESTfulWS</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.UploadFileService</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.mkyong.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Can you please tell me where I am wrong, I am getting the following error:
javax.servlet.ServletException: Servlet.init() for servlet Jersey REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1012)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:642)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1555)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:199)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:795)
com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:790)
com.sun.jersey.spi.container.servlet.ServletContainer.initiate(ServletContainer.java:491)
com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:321)
com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:605)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:207)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:376)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:559)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:76)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:934)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:515)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1012)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:642)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1597)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1555)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Add the following code to your.project file in the appropriate location.
<buildCommand>
<name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
<arguments>
</arguments>
</buildCommand>
I was developing an application of counter below is the structure of my application..
first the listener class
package com.saral;
import javax.servlet.*;
public class AppListener implements ServletContextListener
{
ServletContext ctx;
public void contextInitialized(ServletContextEvent e)
{
ctx=e.getServletContext();
ctx.setAttribute("hitCount",new Integer(0));
}
public void contextDestroyed(ServletContextEvent e)
{}
}
then filter class..
package com.saral;
import javax.servlet.*;
public class CounterFilter implements Filter
{
ServletContext ctx;
public void init(FilterConfig config){
ctx=config.getServletContext();
}
public void destroy(){}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)
{
try
{
Integer ct=(Integer)ctx.getAttribute("hitCount");
int c=ct.intValue();
c++;
ctx.setAttribute("hitCount",new Integer(c));
chain.doFilter(request,response);
}catch(Exception e)
{
System.out.println(e);
}
}
}
followed by login servlet..
package com.saral;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
try{
String name=request.getParameter("txtName");
String pass=request.getParameter("txtPass");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe");
PreparedStatement stmt=con.prepareStatement("select * from logininfo where username=? and password=?");
stmt.setString(1,name);
stmt.setString(2,pass);
ResultSet rset=stmt.executeQuery();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
if (rset.next())
{
request.getSession().setAttribute("username",name);
RequestDispatcher rd=request.getRequestDispatcher("aa");
rd.forward(request,response);
}
else
{
System.out.println("in else");
out.println("<b>Invalid user name or password.</b><br>");
RequestDispatcher rd=request.getRequestDispatcher("home.html");
rd.include(request,response);
}
out.close();
con .close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
followed by servlet2..
package com.saral;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTwo extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
HttpSession ses=request.getSession();
String name=(String)ses.getAttribute("username");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("welcome,"+name);
out.println("<br> <a href=viewServlet>View Hit Count</a>");
out.close();
}
}
and finally view servlet..
package com.saral;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ViewServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
ServletContext ctx=getServletContext();
int c=((Integer)ctx.getAttribute("hitCount")).intValue();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("hit count is:"+c);
out.close();
}
}
I have written the web.xml in this way..
<web-app>
<listener>
<listener-class>AppListener</listener-class>
</listener>
<filter>
<filter-name>counter</filter-name>
<filter-class>com.saral.CounterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>counter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.saral.LoginServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>connectionString</param-name>
<param-value>jdbc:oracle:thin:#localhost:1521:xe</param-value>
</init-param>
<init-param>
<param-name>userName</param-name>
<param-value>saral</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>saral</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>two</servlet-name>
<servlet-class>com.saral.ServletTwo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>two</servlet-name>
<url-pattern>/aa</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>three</servlet-name>
<servlet-class>com.saral.ViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>three</servlet-name>
<url-pattern>/viewServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
and my main html is ..
<html>
<head>
<title> A Simple web Application</title>
</head>
<body>
<form method="get" action="loginServlet">
Name<input type="text" name="txtName"/>
Password<input type="password" name="txtPass"/>
<input type="submit" value="Login"/>
</form>
</body>
</html>
But upon deploying this application on tomcat 7 it throws the error..
NFO: Starting Servlet Engine: Apache Tomcat/7.0.27
15 Jul, 2012 12:05:14 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class AppListener
java.lang.ClassNotFoundException: AppListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:525)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:507)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:124)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4715)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
15 Jul, 2012 12:05:14 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)
15 Jul, 2012 12:05:14 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
15 Jul, 2012 12:05:14 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [/Counter] startup failed due to previous errors
Please advise what is wrong in the application
Done this changes as suggested in web.xml
<listener>
<listener-class>com.saral.AppListener</listener-class>
</listener>
but still getting error..
SEVERE: Error configuring application listener of class com.saral.AppListener
java.lang.ClassNotFoundException: com.saral.AppListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:525)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:507)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:124)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4715)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
15 Jul, 2012 12:21:13 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Skipped installing application listeners due to previous error(s)
Please advise
In your web.xml, you have this configuration for listener
<listener>
<listener-class>AppListener</listener-class>
</listener>
The class AppListener can't be found, you have to set the full name (including package name):
<listener>
<listener-class>com.saral.AppListener</listener-class>
</listener>