HTTP 400 and 500 error messages - java

when I run my application, I'm having a HTTP error:
HTTP Status 404 - /ProjectName/
This is the URL of my project:
localhost:8080/Initiation1/
When I type this string to the address bar:
localhost:8080/Initiation1/CarteIdentite
, I'm having this HTTP 500 error message:
javax.servlet.ServletException: Error instantiating servlet class ca.web.CarteIdentite
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.ClassNotFoundException: ca.web.CarteIdentite
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:269)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:300)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
This is my servlet code:
package ca.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
/**
* Servlet implementation class CarteIdentite
*/
#WebServlet("/CarteIdentite")
public class CarteIdentite extends HttpServlet
{
// paramètres d’instance
private String defaultNom = null;
private String defaultAge = null;
private String defaultCourriel = null;
//init
public void init()
{
// on récupère les paramètres d’initialisation de la servlet
ServletConfig config = getServletConfig();
defaultNom = config.getInitParameter("defaultNom");
if(defaultNom==null)
{
defaultNom="XXXXXXXXXXXXXXXX";
}
defaultAge = config.getInitParameter("defaultAge");
if(defaultAge==null)
{
defaultAge="AAA";
}
defaultCourriel = config.getInitParameter("defaultCourriel");
if(defaultCourriel==null)
{
defaultCourriel="XXXXXX#XXXXXXXX.XX";
}
}
//GET
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
{
// on récupère les paramètres du formulaire
String nom = request.getParameter("txtNom");
if (nom == null)
{
nom = defaultNom;
}
String age = request.getParameter("txtAge");
if (age == null)
{
age = defaultAge;
}
String courriel = request.getParameter("txtCourriel");
if (courriel == null)
{
courriel = defaultCourriel;
}
// on affiche le formulaire
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println
(
"<html>"+
"<head>"+
"<title>Carte d’identité</title>"+
"</head>"+
"<body>"+
"<center>"+
"<h2>Carte d’identité</h2>"+
"<form action=’’ method=’post’>"+
"<table>"+
"<tr>"+
"<td>Nom:</td>"+
"<td><input name=’txtNom’ value=’"+nom+"’ type=’text’ size=’30’></td>"+
"</tr>"+
"<tr>"+
"<td>Age:</td>"+
"<td><input name=’txtAge’ value=’"+ age +"’ type=’text’ size=’3’></td>"+
"</tr>"+
"<tr>"+
"<td>Courriel:</td>"+
"<td><input name=’txtCourriel’ value=’"+courriel+"’ type=’text’ size=’30’></td>"+
"</tr>"+
"</table>"+
"<table>"+
"<tr>"+
"<td><input type=’submit’ value=’Envoyer’></td>"+
"<td><input type=’reset’ value=’Effacer’></td>"+
"</tr>"+
"</table>"+
"</form>"+
"</center>"+
"</body>"+
"</html>"
);
}
/**
* #param request la requête HTTP du client
* #param response la réponse HTTP qu’on va construire
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
//on passe la main au GET
doGet(request, response);
}
}
This is my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app SYSTEM "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>CarteIdentite</servlet-name>
<servlet-class>ca.web.CarteIdentite</servlet-class>
<init-param>
<param-name>defaultNom</param-name>
<param-value>inconnu</param-value>
</init-param>
<init-param>
<param-name>defaultAge</param-name>
<param-value>XXX</param-value>
</init-param>
<init-param>
<param-name>defaultCourriel</param-name>
<param-value>inconnu</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CarteIdentite</servlet-name>
<url-pattern>/CarteIdentite</url-pattern>
</servlet-mapping>
</web-app>
Here is my project structure:

Maybe Eclipse isn't treating src as a source folder. Try right clicking on it and choosing Build Path -> Use as source folder.

Check if the class ca.web.CarteIdentite has compiled correctly and made way into the WAR of your project (under WEB-INF/classes). If not, check/correct the project buildpath settings.

Related

javax.servlet.ServletException: Error instantiating servlet class java.UserScoresServlet

I've been researching similar topics to this, but none of the solutions have worked. I'm trying to map a simple HttpServlet in a Web Application using Eclipse, but have been getting the following error when the form is submitted from the html page that calls get on the servlet.
HTTP Status 500 - Error instantiating servlet class java.UserScoresServlet
type Exception report
message Error instantiating servlet class java.UserScoresServlet
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Error instantiating servlet class java.UserScoresServlet
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
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:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
root cause
java.lang.ClassNotFoundException: java.UserScoresServlet
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
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:312)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
java.lang.Thread.run(Thread.java:748)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
I've tried mapping both with the #WebServlet annotation as well as the Web.xml file to no avail. I was trying to use one or the other, not both at the same time. When using JSP's and HTML pages my mapping works correctly. My XML file mapping is as follows, and is located in the WEB-INF directory.
<display-name>GetUserScores</display-name>
<servlet>
<servlet-name>GetUserScores</servlet-name>
<servlet-class>java.UserScoresServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetUserScores</servlet-name>
<url-pattern>/GetUserScores</url-pattern>
</servlet-mapping>
</web-app>
The server class is as follows. As I mentioned above, I've been doing either the annotation, or the web.xml, not both. Both throw the same exception.
package java;
import java.io.IOException;
import java.score.jpa.Score;
import java.score.jpa.ScoreService;
import java.user.jpa.User;
import java.user.jpa.UserService;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class UserScoresServlet
*/
#WebServlet(name = "GetUserScores", urlPatterns = "/GetUserScores")
public class UserScoresServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserService userService;
private ScoreService scoreService;
/**
* #see HttpServlet#HttpServlet()
*/
public UserScoresServlet() {
super();
userService = new UserService();
scoreService = new ScoreService();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = (String)request.getParameter("firstName");
String lastName = (String)request.getParameter("firstName");
User user = userService.findUserByFirstAndLastName(firstName, lastName);
if (user != null){
List<Score> scoreList = scoreService.findAllScoresByUser(user);
request.setAttribute("scoreList", scoreList);
}
gotoPage("/scores", request, response);
}
private void gotoPage(String address, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
See photo for the file structure: File Structure Image
Any help anyone could provide would be a big help. I've searched this site thoroughly and tried every suggestion of similar issues to no avail. Appreciate the help.
As stated in the JLS, you should not use java as name for your development packages:
Names of packages intended only for local use should have a first identifier that begins with a lowercase letter, but that first identifier specifically should not be the identifier java; package names that start with the identifier java are reserved for package of the Java SE platform
Noted here in your code:
package java;
import java.io.IOException;
import java.score.jpa.Score;
import java.score.jpa.ScoreService;
import java.user.jpa.User;
import java.user.jpa.UserService;
import java.util.List;
//rest of code...
Change the name of your package to something else.

error: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver?

I am trying simple login authentication using servlets and jdbc connection to MySQL database. After executing it on tomcat server I am getting following error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.leader.prog.Validate.checkUser(Validate.java:13)
at com.leader.servlet.Login1.doPost(Login1.java:42)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
I am sharing the content of all files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.leader.servlet.Login1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>com.leader.servlet.Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Home.html</welcome-file>
</welcome-file-list>
</web-app>
Login1.java
package com.leader.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.leader.*;
import com.leader.prog.Validate;
#WebServlet("/Login1")
public class Login1 extends HttpServlet {
/**
* #see HttpServlet#HttpServlet()
*/
public Login1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("userName");
String pass = request.getParameter("password");
if(Validate.checkUser(user.toString(),pass.toString()))
{
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("Home.html");
rs.include(request, response);
}
}
}
validate.java
package com.leader.prog;
import java.sql.*;
public class Validate
{
public static boolean checkUser(String user,String pass)
{
boolean st =false;
try{
//loading driver
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/person","root","password");
PreparedStatement ps =con.prepareStatement
("select * from person where pid=? and password=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Please help me to get out of this issue.
Check the availability of mysql driver is in classpath. If you are using IDE(eclipse) try to add it to build path.
You should add Mysql connector library you your project buildpath
You can download library from
http://dev.mysql.com/downloads/connector/j/5.0.html
or
http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm

Servlet call from Tomcat throwing HTTP Status 500 - java.lang.NullPointerException

I am trying to call my servlet GetAttributeValueServlet from apache tomcat and this error has been shown.
The Servlet is in CloudWebServerClient.
Severe: Servlet.service() for servlet [servlet.GetAttributeValueServlet] in context with path [/CloudWebServiceClient] threw exception
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: java.lang.NullPointerException
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}hostname
java.lang.NullPointerException
at org.apache.axis.message.SOAPFaultBuilder.createFault(SOAPFaultBuilder.java:222)
at org.apache.axis.message.SOAPFaultBuilder.endElement(SOAPFaultBuilder.java:129)
at org.apache.axis.encoding.DeserializationContext.endElement(DeserializationContext.java:1087)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
at org.apache.axis.encoding.DeserializationContext.parse(DeserializationContext.java:227)
at org.apache.axis.SOAPPart.getAsSOAPEnvelope(SOAPPart.java:696)
at org.apache.axis.Message.getSOAPEnvelope(Message.java:435)
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:796)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.client.service.WebServiceProxySoapBindingStub.getAttributeValue(WebServiceProxySoapBindingStub.java:297)
at com.client.service.WebServiceProxyProxy.getAttributeValue(WebServiceProxyProxy.java:50)
at servlet.GetAttributeValueServlet.doGet(GetAttributeValueServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
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_3_0.xsd" version="3.0">
<display-name>CloudWebServiceServer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<display-name>GetAttributeValueServlet</display-name>
<servlet-name>GetAttributeValueServlet</servlet-name>
<servlet-class>com.src.servlet.GetAttributeValueServlet</servlet-class>
</servlet>
<servlet>
<display-name>Apache-Axis Servlet</display-name>
<servlet-name>AxisServlet</servlet-name>
<servlet-class>org.apache.axis.transport.http.AxisServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAttributeValueServlet</servlet-name>
<url-pattern>/CloudWebServiceClient/WebContent/GetAttributeValueServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/servlet/AxisServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>*.jws</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<servlet>
<display-name>Axis Admin Servlet</display-name>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>org.apache.axis.transport.http.AdminServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet/AdminServlet</url-pattern>
</servlet-mapping>
</web-app>
GetAttributeValueServlet:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.client.service.WebServiceProxy;
import com.client.service.WebServiceProxyProxy;
/**
* Servlet implementation class GetAttributeValueServlet
*/
#WebServlet("/GetAttributeValueServlet")
public class GetAttributeValueServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetAttributeValueServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setHeader("Access-Control-Allow-Origin", "*");
response.setContentType("text/xml;charset=utf-8");
String EntityID=request.getParameter("entity_id");
String AttrName=request.getParameter("attrName");
//String Value=request.getParameter("value");
System.out.println(EntityID+AttrName);
WebServiceProxy wsp = new WebServiceProxyProxy();
System.out.println("Huuu"); //just to see if it is coming to this point and yes it comes to this point and after that throws exception!
String isGet = wsp.getAttributeValue(EntityID, AttrName);
System.out.println("Hagfgfg"); //it doesn't shows this value!
PrintWriter pw = response.getWriter();
pw.print(isGet);
return;
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Before using values you pull from request.getParameter() you should check them to see if they are null and do something if they are.
String entityID = request.getParameter("entity_id");
if(entityID==null)
{
entityID = "";
//or maybe print a message to user "Entity ID is required field" and return;
}
Or you can make sure they're not null like this:
String entityID = "" + request.getParameter("entity_id");
This would mean if what comes out of request.getParameter() was null, now it will be the String value "null" rather than null.
I resolved it.... The problem was in parameter attrName which was Null and it was because of wrong function call ;) thanx anyways

jersey NoClassDefFoundError: org/objectweb/asm/ClassVisitor exception

First time I'm trying a WebService using jersey. The below code I got from some blog.
I am getting following 500 error when I'm trying Java Web service using jersey client
javax.servlet.ServletException: Servlet.init() for servlet Jersey Root REST Service threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
com.sun.jersey.api.core.ScanningResourceConfig.init(ScanningResourceConfig.java:79)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.init(WebAppResourceConfig.java:102)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.<init>(WebAppResourceConfig.java:89)
com.sun.jersey.api.core.servlet.WebAppResourceConfig.<init>(WebAppResourceConfig.java:74)
com.sun.jersey.spi.container.servlet.WebComponent.getWebAppResourceConfig(WebComponent.java:672)
com.sun.jersey.spi.container.servlet.ServletContainer.getDefaultResourceConfig(ServletContainer.java:415)
com.sun.jersey.spi.container.servlet.ServletContainer.getDefaultResourceConfig(ServletContainer.java:582)
com.sun.jersey.spi.container.servlet.WebServletConfig.getDefaultResourceConfig(WebServletConfig.java:87)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:703)
com.sun.jersey.spi.container.servlet.WebComponent.createResourceConfig(WebComponent.java:678)
com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:203)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:374)
com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:557)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)'
Below is my web.xml file
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>RestFulWeb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jersey Root REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<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 Root REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>'
Here i tried adding the package also that didn't help:
Added only one jar file jersey-bundle-1.14.jar. The following is my Jersey server
package com.rest.server;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.rest.data.Hello;
// POJO, no interface no extends
// The class registers its methods for the HTTP GET request using the #GET annotation.
// Using the #Produces annotation, it defines that it can deliver several MIME types,
// text, XML and HTML.
// The browser requests per default the HTML MIME type.
//Sets the path to base URL + /hello
#Path("/hello")
public class HelloWorldRest {
#GET
#Path("/{param}/")
public String getMsg(#PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return output;
}
#GET
#Path("/world")
public String getFixedMsg(String msg) {
String output = "Jersey say : fixed path" + msg;
return output;
}
// This method is called if TEXT_PLAIN is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
System.out.println("sayPlain");
return "Hello Jersey";
}
// This method is called if XML is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
System.out.println("sayXML");
return "" + " Hello Jersey" + "";
}
// This method is called if HTML is request
#GET
//#Path("helloworld")
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
System.out.println("sayHTML");
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}
// This method is called if JSON is request
#GET
//#Path("helloworld")
#Produces(MediaType.APPLICATION_JSON)
public Hello sayJsonHello() {
return new Hello("Hello", "Jersey");
}
#POST
#Produces(MediaType.APPLICATION_JSON)
public Hello createHello(Hello hello)
{
System.out.println("post");
return hello;
}
}'
currently I'm trying only with GET hitting the following url http://localhost:8080/RestFulWeb/hello, I am getting the 505 error.
DO i missed any jar files , but i didn't get any compile time error.
This is caused by the missing of asm.jar,
Add this dependency
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
While writing a webservice I was getting following error:
INFO: Scanning for root resource and provider classes in the packages:
com.webservice.services
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor
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.webservice.StartWebService.startAttrService(StartWebService.java:32)
at com.webservice.StartWebService.main(StartWebService.java:20)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.ClassVisitor
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 5 more
I included asm.jar in my java project and error gone.
I was following steps from restful-web-services-first-application-mock-service-using-pure-java

Tomcat throws AbstractMethodError for WebSocketServlet.createWebSocketInbound() when custom servlet runs

I work on a project in which I need to create a real time web application. I've developed a small program to test WebSockets with Apache Tomcat, but it doesn't work and instead throws an AbstractMethodError exception. The servlet compiles and the web application deploys fine.
Here's the servlet's code.
public class TestWebSocket extends WebSocketServlet {
private static final long serialVersionUID = 1L;
#Override
protected boolean verifyOrigin(String origin) {
System.out.println("Origin: {}" + origin);
return true;
}
#Override
protected StreamInbound createWebSocketInbound(String subProtocol, HttpServletRequest request) {
return new WebSocketConnection();
}
private static class WebSocketConnection extends MessageInbound {
#Override
protected void onOpen(WsOutbound outbound) {
System.out.println("Conexión abierta");
}
#Override
protected void onClose(int status) {
System.out.println("Conexión cerrada");
}
#Override
protected void onBinaryMessage(ByteBuffer byteBuffer) throws IOException {
System.out.println("No se soportan mensajes binarios");
throw new UnsupportedOperationException("No se soportan mensajes binarios");
}
#Override
protected void onTextMessage(CharBuffer charBuffer) throws IOException {
final String user = charBuffer.toString();
System.out.println("Mensaje recibido: {}" + user);
getWsOutbound().writeTextMessage(CharBuffer.wrap("Hola " + user + " desde WebSocket"));
}
}
}
Here goes the deployment descriptor - 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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>TestWebSocket</display-name>
<servlet>
<servlet-name>TestWebSocket</servlet-name>
<servlet-class>com.test.TestWebSocket</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestWebSocket</servlet-name>
<url-pattern>/testWebSocket</url-pattern>
</servlet-mapping>
</web-app>
And the client code - testSocket.js:
/*
* For Testing websockets
*/
$(function(){
console.log("URL :" + 'ws://' + location.host + '/TestTomcatWebSocket/testWebSocket');
var ws = new WebSocket('ws://' + location.host + '/TestTomcatWebSocket/testWebSocket');
ws.onopen = function() {
console.log("Websocket Ready!!");
sendMessage();
};
ws.onmessage= function(data) {
console.log("message received : " + data);
};
function sendMessage() { ws.send("Test"); };
});
Upon execution the application finishes with the following java.lang.AbstractMethodError exception:
INFO: Server startup in 495 ms
Origin: {}http://localhost:8080
Dec 17, 2012 1:58:51 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [TestWebSocket] in context with path [/TestTomcatWebSocket] threw exception [Servlet execution threw an exception] with root cause
java.lang.AbstractMethodError: org.apache.catalina.websocket.WebSocketServlet.createWebSocketInbound(Ljava/lang/String;)Lorg/apache/catalina/websocket/StreamInbound;
at org.apache.catalina.websocket.WebSocketServlet.doGet(WebSocketServlet.java:125)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:307)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I use Apache Tomcat 7.0.33.
problem solved. basically i was using the older version of eclipse which configures tomcat according to tomcat's earlier configuration for running tomcat inside it. So when i used eclipse's latest version JUNO it configured it with tomcats latest configuration which includes websocket configuration in catilina.policy file.
// Applications using WebSocket need to be able to access this package permission java.lang.RuntimePermission "accessClassInPackage.org.apache.catalina.websocket";

Categories