Servlet throwing exception on deploying on tomcat - java

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>

Related

Jersey Client API - authentication error using jersey rest api

I have created one authorization filter before calling rest API but i am getting 404 error message. Below is classes which I have created.
--RestAuthenticationFilter
package com.sms.Security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RestAuthenticationFilter implements javax.servlet.Filter {
public static final String AUTHENTICATION_HEADER = "Authorization";
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String authCredentials = httpServletRequest
.getHeader(AUTHENTICATION_HEADER);
// better injected
AuthenticationService authenticationService = new AuthenticationService();
boolean authenticationStatus = authenticationService
.authenticate(authCredentials);
if (authenticationStatus) {
filter.doFilter(request, response);
} else {
if (response instanceof HttpServletResponse) {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse
.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
}
--AuthenticationService
package com.sms.Security;
import java.io.IOException;
import java.util.Base64;
import java.util.StringTokenizer;
public class AuthenticationService {
public boolean authenticate(String authCredentials) {
if (null == authCredentials)
return false;
// header value format will be "Basic encodedstring" for Basic
// authentication. Example "Basic YWRtaW46YWRtaW4="
final String encodedUserPassword = authCredentials.replaceFirst("Basic"
+ " ", "");
String usernameAndPassword = null;
try {
byte[] decodedBytes = Base64.getDecoder().decode(
encodedUserPassword);
usernameAndPassword = new String(decodedBytes, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
final StringTokenizer tokenizer = new StringTokenizer(
usernameAndPassword, ":");
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
// we have fixed the userid and password as admin
// call some UserService/LDAP here
boolean authenticationStatus = "admin".equals(username)
&& "admin".equals(password);
return authenticationStatus;
}
}
--Web.xml file
<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.sms.presentationT</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-serlvet</servlet-name>
<url-pattern>/pages/rest/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>com.sms.Security.RestAuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/pages/rest/*</url-pattern>
</filter-mapping>
</web-app>
--Login API
package com.sms.presentationT;
import java.io.Serializable;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import com.sms.userServices.*;
import com.sms.Registrations.Regitration;
import com.sms.persistenceT.*;
import com.sms.persistenceT.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.sms.Security.*;
#Path("/user-servicesLogincheck1")
public class Check implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#POST
#Path("/LoginPagecheck1")
//#Consumes("application/json")
//#Produces("application/json")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Regitration loginUserInfo(#FormParam("logusertype") String logUserType,
#FormParam("userNAME") String UserNAME,
#FormParam("PassWORD") String PAssWORD) throws ParseException
{
System.out.println(logUserType+UserNAME+PAssWORD);
CustomApplication CA = new CustomApplication();
CA.getApplication();
LoginUserServiceCheck LUS = new LoginUserServiceCheck();
JSONObject jobj2 = new JSONObject();
jobj2 = LUS.LoginInputDatacheck(logUserType,UserNAME, PAssWORD);
System.out.println("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
System.out.println("Presentation jobj"+jobj2);
String jsonText = jobj2.toJSONString();
System.out.println(jsonText);
JSONParser parser = new JSONParser();
JSONObject newJObject = null;
try {
newJObject = (JSONObject) parser.parse(jsonText);
} catch (ParseException e) {
e.printStackTrace();
}
//System.out.println(LUS.loginresponse);
//System.out.println(LUS.resultStatus);
/*
if(LUS.resultStatus)
{
System.out.println(LUS.loginresponse);
return LUS.loginresponse;
//return "UserName is valid";
}
else
{
return LUS.loginresponse;
}
*/
System.out.println(newJObject.get("Name"));
System.out.println(newJObject.get("Email"));
Regitration rg = new Regitration();
rg.setUserType(logUserType);
rg.setName((String)newJObject.get("Name"));
rg.setEmail((String)newJObject.get("Email"));
rg.setUserName((String)newJObject.get("userName"));
rg.setPassword((String)newJObject.get("password"));
rg.setConfirmPasssword((String)newJObject.get("password"));
rg.setBirthDay((String)newJObject.get("birthday"));
rg.setGender((String)newJObject.get("Gender"));
rg.setMobileNo((String)newJObject.get("mobileNo"));
rg.setCurrentAddress((String)newJObject.get("currentAddress"));
rg.setPermenantAddress((String)newJObject.get("PermenantAddress"));
rg.setCountry((String)newJObject.get("Country"));
rg.setState((String)newJObject.get("state"));
rg.setCity((String)newJObject.get("City"));
rg.setLandmark((String)newJObject.get("Landmark"));
rg.setZipCode((String)newJObject.get("ZipCode"));
return rg;
}
}
-- Error message
Mar 27, 2017 1:44:58 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2836 ms
Mar 27, 2017 1:44:58 PM org.apache.catalina.core.StandardService start
INFO: Starting service Catalina
Mar 27, 2017 1:44:58 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.37
Mar 27, 2017 1:44:59 PM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter AuthenticationFilter
java.lang.ClassNotFoundException: com.sms.Security.RestAuthenticationFilter
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:269)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:424)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4072)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4726)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
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:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
It looks like the RestAuthenticationFilter is not available in the classpath, hence the ClassNotFoundException. Please double check if you are compiling it and putting it in the classpath.

Error in web.xml file when I add context-parameters to it

I am getting an error in web.xml file while adding context parameters to it.
Here is web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<pram-name>ADMIN_PATH</param-name>
<param-value>AdminChatServlet</param-value>
</context-param>
<context-param>
<param-name>ROOMLIST_PATH</param-name>
<param-value>/RoomListServlet</param-value>
</context-param>
<context-param>
<param-name>CHROOM_PATH</param-name>
<param-value>/ChRoomServlet</param-value>
</context-param>
<servlet>
<servlet-name>MainChatServlet</servlet-name>
<servlet-class>MainChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>AdminChatServlet</servlet-name>
<servlet-class>AdminChatServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>RoomListServlet</servlet-name>
<servlet-class>RoomListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ChRoomServlet</servlet-name>
<servlet-class>ChRoomServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MainChatServlet</servlet-name>
<url-pattern>/MainChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AdminChatServlet</servlet-name>
<url-pattern>/AdminChatServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RoomListServlet</servlet-name>
<url-pattern>/RoomListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ChRoomServlet</servlet-name>
<url-pattern>/ChRoomServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
and here is the servlet(MainChatServlet) using those context-parameters:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import com.amir.*;
public class MainChatServlet extends HttpServlet {
String chRoomPath;//="ChRoomServlet.java";
String roomListPath;//="RoomListServlet.java";
String adminChatPath;//="AdminChatServlet.java";
public void init()
{
ServletContext context = getServletConfig().getServletContext();
context.setAttribute("chRoomPath",context.getInitParameter("CHROOM_PATH"));
context.setAttribute("roomListPath",context.getInitParameter("ROOMLIST_PATH"));
context.setAttribute("adminChatPath",context.getInitParameter("ADMINCHAT_PATH"));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
chRoomPath = (String)getServletContext().getAttribute("chRoomPath");
roomListPath = (String)getServletContext().getAttribute("roomListpath");
adminChatPath = (String)getServletContext().getAttribute("adminChatPath");
session.setAttribute("chRoomPath",chRoomPath);
session.setAttribute("roomListPath", roomListPath);
session.setAttribute("adminChatPath",adminChatPath);
HashMap hashmap = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chat","root","mysql");
synchronized(getServletContext())
{
hashmap = (HashMap)getServletContext().getAttribute("chatList");
if(hashmap == null)
{
hashmap =new HashMap();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from chatrooms");
while(rs.next())
{
hashmap.put(rs.getString(1),new ChatRoom(rs.getString(1),rs.getString(2),4));
}
rs.close();
getServletContext().setAttribute("roomList", hashmap);
}
}
conn.close();
}
catch(ClassNotFoundException e)
{
System.out.print("Error(Class)");
e.printStackTrace();
}
catch(SQLException e)
{
System.out.print("Error(SQL)");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("chat.jsp");
view.forward(request, response);
}
}
and here is the default-package in which all the .java files(servlets are kept)
Screenshot#1
Why am I getting the error in the web.xml file?
Screenshot#2
EDIT: OR Suggest me any alternate idea if possible.

javax.servlet.UnavailableException: SRVE0200E - Maven webapp

I am trying to deploy a single maven webapp on a Websphere Liberty Server.
My code (XCCQuery.java):
package TTAQuery;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
#WebServlet(name="XCCQuery", urlPatterns={"/hello"})
public class XCCQuery extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String simpleParam = getServletConfig().getInitParameter("simpleParam");
out.println("Hello World "+simpleParam);
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
My web.xml looks like this:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>XCCQuery</servlet-name>
<display-name>XCCQuery</display-name>
<description></description>
<servlet-class>XCCQuery</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XCCQuery</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I try to access:
http://localhost:9087/XCCQueryServlet/rest/hello
but always get:
Error 404: javax.servlet.UnavailableException: SRVE0200E: Servlet [XCCQuery]: Could not find required class - XCCQuery
Seems to be a deployment mistake for me.
What's wrong here?

embedded jetty server in a exploded war

After successfully able to run a WAR through jetty, I am trying to embed jetty server into my web-application. It is a normal java application consisting servlet. I have used exploded WAR directory (WARless).
But I get the following exception.
2014-02-22 16:27:08.271:INFO:oejw.StandardDescriptorProcessor:NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
2014-02-22 16:27:08.319:WARN:oejs.Holder:
java.lang.ClassNotFoundException: ClientServlet
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:421)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:383)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:100)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:79)
at org.eclipse.jetty.servlet.Holder.doStart(Holder.java:107)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:298)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:791)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.Server.doStart(Server.java:282)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at com.jetty.RunJetty.main(RunJetty.java:24)
2014-02-22 16:27:08.321:WARN:/:unavailable
Embedded jetty Server code
package com.jetty;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class RunJetty {
public RunJetty() {
}
public static void main(String[] args) {
Server server=new Server(8080);
WebAppContext wac = new WebAppContext();
wac.setResourceBase("C:/Users/User/j2ee/workspace/CLient1");
wac.setDescriptor("C:/Users/User/j2ee/workspace/CLient1/WebContent/WEB-INF/web.xml");
wac.setContextPath("/");
wac.setParentLoaderPriority(true);
server.setHandler(wac);
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Servlet Code
package com.jetty;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.CORBA.RepositoryIdHelper;
public class ClientServlet extends HttpServlet {
private static final long serialVersionUID = 8120079003868426157L;
private String greeting="Hello World";
public ClientServlet(){}
public ClientServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>"+greeting+"</h1>");
}
}
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>kajh</display-name>
<servlet>
<description></description>
<display-name>ClientServlet</display-name>
<servlet-name>ClientServlet</servlet-name>
<servlet-class>ClientServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientServlet</servlet-name>
<url-pattern>/ClientServlet</url-pattern>
</servlet-mapping>
</web-app>
Additionally, I want to use response.sendRedirect in my servlet. Something like,
public class ClientServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8120079003868426157L;
private String greeting="Hello World";
public ClientServlet(){}
public ClientServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.sendRedirect("http://localhost:8080/CLient1/index.html");
}
}
Please help! I am stuck on this like forever.
Thank you in advance!
Also I am adding the folder structure of my application to have a better understanding
I think the servlet-class should be
<servlet-class>com.jetty.ClientServlet</servlet-class>
Edit: Made it show the codeformat also.

Running Jersey with built in HTTP server

I'm trying to run a simple Jersey app from the command line using the built in HTTP server.
Following various tutorials, I've set my app up like this:
src/main/java/net/wjlafrance/jerseyfun/App.java:
package net.wjlafrance.jerseyfun;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.io.IOException;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
/**
* Hello world!
*
*/
#Path("/hello")
public class App {
public static void main(String[] args) {
System.out.println("Starting HTTP server..");
try {
HttpServerFactory.create("http://localhost:9998/").start();
} catch (IOException ex) {
System.err.println(ex);
}
}
#GET
public Response getMessage() {
String output = "It works!";
return Response.status(200).entity(output).build();
}
}
src/main/webapp/WEB-INF/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>net.wjlafrance.jerseyfun</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>
</web-app>
When I run mvn clean package exec:java -Dexec.mainClass=net.wjlafrance.jerseyfun.App, I see this output:
Starting HTTP server..
Apr 29, 2013 9:12:11 AM com.sun.jersey.api.core.ClasspathResourceConfig init
INFO: Scanning for root resource and provider classes in the paths:
C:\cygwin\home\wlafrance\bin\apache-maven-3.0.5/boot/plexus-classworlds-2.4.jar
Apr 29, 2013 9:12:11 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.17 01/17/2013 03:31 PM'
Apr 29, 2013 9:12:11 AM com.sun.jersey.server.impl.application.RootResourceUriRules <init>
SEVERE: The ResourceConfig instance does not contain any root resource classes.
[WARNING]
java.lang.reflect.InvocationTargetException
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.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.sun.jersey.api.container.ContainerException: The ResourceConfig instance does not contain any root resource classes.
at com.sun.jersey.server.impl.application.RootResourceUriRules.<init>(RootResourceUriRules.java:99)
at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1331)
at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:168)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:774)
at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:770)
at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:770)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:172)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:264)
at com.sun.jersey.api.container.ContainerFactory.createContainer(ContainerFactory.java:246)
at com.sun.jersey.api.container.httpserver.HttpServerFactory.create(HttpServerFactory.java:117)
at com.sun.jersey.api.container.httpserver.HttpServerFactory.create(HttpServerFactory.java:92)
at net.wjlafrance.jerseyfun.App.main(App.java:22)
... 6 more
Clearly enough, my server is misconfigured. Can someone point me in the right direction?
With Jersey 1.x, the answer of #pakOverflow points to the right direction. Here the complete code with which I had success. Without any dependency on Grizlly1 or Grizzly2 etc.
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class WineryUsingHttpServer {
public static void main(String[] args) throws IOException {
ResourceConfig packagesResourceConfig = new DefaultResourceConfig();
Application app = new Application() {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> res = new HashSet<>();
res.add(org.example.MainResource.class);
return res;
}
};
packagesResourceConfig.add(app);
HttpServerFactory.create("http://localhost:8080/", packagesResourceConfig).start();
}
}
See this line "The ResourceConfig instance does not contain any root resource classes" in the error message?
You did not set any resource for the http server.
What I will do is use this method:
GrizzlyHttpServerFactory.createHttpServer("http://localhost:9998/", new Application());
The new Application() will create a new ResourceConfig class for the http server. You should check the jersey's documents for that, it`s just a simple class which contains a java package.
My ResourceConfig is likes below:
import org.glassfish.jersey.server.ResourceConfig;
public class Application extends ResourceConfig {
public Application() {
packages("ftp.recourse");
}
}
While the ftp.recourse package contains all the path and operations like GET, PUT, POST.
Check the jersey`s official documents for more detials. Hope this will help
You should do the following:
final com.sun.jersey.api.core.ResourceConfig packagesResourceConfig = new com.sun.jersey.api.core.ResourceConfig("net.wjlafrance.jerseyfun") ;
HttpServerFactory.create("http://localhost:9998/", packagesResourceConfig).start();

Categories

Resources