Problem with the Apache DefaultHttpClient class - java

I am a newbie for servlet applications, trying to learn the subject. On my way, I wrote a servlet class called FormWebServlet that uses the org.apache.http.impl.client.DefaultHttpClient class. However, I get the exception
java.lang.ClassNotFoundException: org.apache.http.impl.client.DefaultHttpClient
... that clearly shows that this class does not exist, although I have added the jar file to the project.
The server returns an "HTTP Status 500" error with the message that the "root cause" is this missing class:
java.lang.NoClassDefFoundError: org/apache/http/impl/client/DefaultHttpClient
testPackage.FormWebServlet.doGet(FormWebServlet.java:45)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
TRIES
1) I searched for the missing jar file and added it to the project (by going on the project in "Eclipse JAVA EE IDE for Web Developers, 20100917-0705"'s project explorer, select "Properties", selected the "Java Build Path" and clicked the [Add External JARs...] button.) The added jar file is from the Apache site and is called httpclient-4.1.1.jar.
2) As I still get the same error, I extracted with 7-ZIP the DefaultHttpClient.class file and put it into the WebContent/WEB-INF/lib directory.
QUESTION
What am I doing wrong? Neither of the other two JAR files do contain the class, nor is there a class with this name in the WEB-INF/lib folder.
DETAILS
Inculded JARs:
common-httpclient-3.0.1.jar
httpclient-4.1.1.jar
httpcore-4.1.jar
FormWebServlet.jar:
/**
*
*/
package testPackage;
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 org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import coreServlets.ServletUtilities;
/**
*
*/
#WebServlet(description = "Gets the book's barcode with a form", urlPatterns = { "/FormWebServlet" })
public class FormWebServlet extends HttpServlet {
/** */
private static final long serialVersionUID = 6008315960327824633L;
/**
* #see HttpServlet#doGet(HttpServletRequest request,
* HttpServletResponse response)
*/
protected void doGet(final HttpServletRequest request,
final HttpServletResponse response)
throws IOException, ServletException {
final String BAR_CODE = request.getParameter("barCode");
response.setContentType("text/html");
final PrintWriter out = response.getWriter();
if (BAR_CODE != null) {
HttpClient client = new DefaultHttpClient();
final String ADDRESS = ServletUtilities.getHttpAddress(BAR_CODE);
out.println("ADDRESS = \"" + ADDRESS + '\"');
HttpGet get = new HttpGet(ADDRESS);
HttpResponse httpResponse = null;
// Removed commented code that will use these objects
}
}
}

Just put the JAR files themselves into WEB-INF/lib, not the class file. That way they will be included in your deployment.

Related

Embedded jetty 9 doesn't work for #Webservlet

I'm using java 11 and embedded jetty 9 foor my javaEE application,I'm trying to use #Websevlet annotation to publish my servlet but it doesn't work i don't know why.
My start class java
import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.*;
public class Start {
public static void main(String[] args) throws Exception {
Server server = new Server(80);
WebAppContext wacHandler = new WebAppContext();
wacHandler.setConfigurations(new Configuration[]
{
new AnnotationConfiguration(),
new WebInfConfiguration(),
new WebXmlConfiguration(),
new MetaInfConfiguration(),
new FragmentConfiguration(),
new JettyWebXmlConfiguration()
});
server.setHandler(wacHandler);
server.start();
server.join();
}
}
My hello world class
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;
#WebServlet( "/getservlet")
public class ServletX extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hi there..</h1>");
}
}
I don't have a web.xml configuration ,Should i do?
If ServletX is in the war file, meaning it's in WEB-INF/classes/ archive directory, then the configuration you have declared (specifically the AnnotationConfiguration) will perform a bytecode scan of the WAR file and load the #WebServlet annotation.
Also note that the WebAppContext will need point to this WAR file, which your code examples do not do.
WebAppContext wacHandler = new WebAppContext();
waxHandler.setWar("/path/to/myapp.war");
// ... more setup
But! if the ServletX is not in the WAR file, but is instead housed with your embedded-jetty Start class, then you'll need to expose the servlet container to be scanned by the bytecode scanning step.
You can always turn on DEBUG/FINE level logging for the named logger org.eclipse.jetty and see the activity being performed with regards to the deployment and bytecode scanning.

Web servlet error by using html code in get method

I am new to web programming. I am using this simple code in my get method
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
I am getting the below error while clicking on run on server
enter image description here
Note: When i removed the html code, the servlet is working fine.Is it my Html code problem or any tomcat sevrver issue.
The servlet is in my package cs3220homework and servlet name is #WebServlet("/MainFolder").
I tried everywhere to look for the issue and i was not able to find it.If its duplicate please let me know.
Thanks for your reply
Harminder
Its working fine. App is named Test and Servlet class is also named Test. This is the url http://localhost:8080/Test/Test
package foo;
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;
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
}
}

Verify header before request receive in tomcat

I need verify header before receive the request. I found that tomcat valve can help in it. I follow these steps but valve is not called:
make a maven project and do this code in it.
package cz.ValveTest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
public class ProcessingValve extends ValveBase {
private static final Logger logger = Logger.getLogger(ProcessingValve.class.getName());
#Override
public void invoke(Request request, Response response) throws IOException,
ServletException {
HttpServletRequest httpServletRequest = request.getRequest();
Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
logger.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
logger.log(Level.INFO, "Header --> {0} Value --> {1}", new Object[]{header, httpServletRequest.getHeader(header)});
}
getNext().invoke(request, response);
}
}
make jar and put jar inside tomcat/lib folder
add this line in server.xml
<valve className="cz.ValveTest.ProcessingValve"/>
restart tomcat.
Now I hit my web service with header:
Expect : 100-continue
but using this configuration and code valve is not called on http hit.If any one knew why tomcat valve is not called please help.
The tags in server.xml are case sensitive.
So try this :
<Valve className="cz.ValveTest.ProcessingValve"/>

WebService not being produced./Generated

I am trying to deploy a webservice on my localhost, but it doesn't seem to produce the "Endpoint".
I don't know how I messed it up :(
I am using apache cxf 2.7.1 and glassfish 3.1. I even attempted to add ear libraries.
Here is my build path:
and my project explorer looks like this:
I have annotations on both my webservice and webservice interface, as shown below:
Code for webservice interface (I removed the other some parts to make the code shorter)
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import no.solarsoft.venus2.webservice.exception.WebServiceException;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQuery;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQueryParameterKey;
import no.solarsoft.venus2.webservice.queryoptions.QueryParameter;
#WebService()
public interface WebServiceVenus2Interface {
/**
* FETCHING DATA FROM DATABASE
*
*/
#WebMethod
public void Foo(ParticipantQueryParameterKey pqpk);
#WebMethod
public String test();
#WebMethod
public String sayHello(String string) throws WebServiceException;
The code for my web service:
import javax.annotation.Resource;
import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import no.solarsoft.venus2.datamanager.CRUDOperation;
import no.solarsoft.venus2.datamanager.DataManager;
import no.solarsoft.venus2.entities.GradeScale;
import no.solarsoft.venus2.enums.ImageType;
import no.solarsoft.venus2.exception.DataAccessException;
import no.solarsoft.venus2.exception.InstanceNotFoundException;
import no.solarsoft.venus2.service.EmailService;
import no.solarsoft.venus2.webservice.exception.ParameterValidationException;
import no.solarsoft.venus2.webservice.exception.WebServiceException;
import no.solarsoft.venus2.webservice.exception.WebServiceFaultBean;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQuery;
import no.solarsoft.venus2.webservice.queryoptions.ParticipantQueryParameterKey;
import no.solarsoft.venus2.webservice.queryoptions.QueryParameter;
// #Stateless()
#javax.jws.WebService(endpointInterface = "no.solarsoft.venus2.webservice.WebServiceVenus2Interface", serviceName = "WebServiceVenus2Service")
public class WebServiceVenus2 implements WebServiceVenus2Interface {
private DataManager dataManager = DataManager.getInstance();
private static final Logger log = Logger.getAnonymousLogger();
#Resource
WebServiceContext wsContext;
#Override
public void Foo(ParticipantQueryParameterKey pqpk) {}
private void logEntered(String login) {
log.info(MessageFormat.format("{0}: ''{1}'' entered web service method ''{2}()''",
WebServiceVenus2.class.getSimpleName(), login, getMethodName()));
}
private String getClientIp() {
MessageContext mc = wsContext.getMessageContext();
HttpServletRequest req = (HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST);
return req.getRemoteAddr();
}
/**
* Get the method name for a depth in call stack. <br />
* Utility function
*
* #param depth
* depth in the call stack (0 means current method, 1 means call method, ...)
* #return method name
*/
public static String getMethodName() {
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
return ste[3].getMethodName(); // Thank you Tom Tresansky
}
/**
* FETCHING DATA FROM DATABASE
*/
#Override
public String test() {
String ip = getClientIp();
logEntered(ip);
return "WebService test succeded! Client IP: " + ip;
}
#Override
public String sayHello(String string) throws WebServiceException {
logEntered(null);
if (string == null || string.isEmpty()) {
log.severe("Throwing excetion...");
throw new WebServiceException("String can not be empty or NULL!", new WebServiceFaultBean());
}
log.exiting(WebServiceVenus2.class.getName(), WebServiceVenus2.getMethodName());
return "Hello " + string + "!";
}
and here is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</web-app>
I hope someone can help me. Thanks
I loaded this code nearly verbatim to a dynamic web module in eclipse and deployed to Glassfish4. When deployed (using eclipse "add to server") the WSDL is available at http://localhost:8181/Venus2WebService/WebServiceVenus2Service?wsdl
and the web service endpoint is http://localhost:8181/Venus2WebService/WebServiceVenus2Service
The only jars I included from CXF (not shown in your post) are, from reading WHICH_JARS readme within CXF binary distribution lib dir:
asm-3.3.1.jar
commons-logging-1.1.1.jar
cxf-2.7.17.jar
geronimo-javamail_1.4_spec-1.7.1.jar
geronimo-jaxws_2.2_spec-1.1.jar
jaxb-api-2.2.6.jar
jaxb-impl-2.2.6.jar
neethi-3.0.3.jar
stax2-api-3.1.4.jar
wsdl4j-1.6.3.jar
xmlschema-core-2.1.0.jar
I got the endpoint URL from watching the eclipse console for the server:
2015-09-09T21:45:40.683-0400|Info: Webservice Endpoint deployed WebServiceVenus2
listening at address at http://oc-mbp01.local:8181/Venus2WebService/WebServiceVenus2Service.
Classpath (all in WEB-INF/lib for me):

How to run a java web application?

I have a folder that has only .java files. There are no .html, .jsp, .jsf etc. files only .java. I was told that this is a web application, but I have no idea on how to run it.
Here is a sample code from one of the .java files:
public List<String> generateHtml(String name, String css) {
List<String> html = new ArrayList<>();
html.add("<!DOCTYPE HTML><html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"" + css
+ "\"/></head><body>");
html.add("<div class='screen page_size " + name + "'>");
for (HtmlElement element : orderedElements) {
element.generateHtml(html);
}
html.add("</div>");
html.add("</body></html>");
return html;
}
I tried making a web project in eclipse and importing the files and running it, but no luck. It gives me a lot of errors with something to do with jetty. After installing jetty it still didnt work. Maybe I am installing it wrong. Anyone has any idea?
If you want to create a runnable war with jetty, have a look a the Embedded Jetty examples
You can call the generateHtml method from the servlet below.
package org.eclipse.jetty.embedded;
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.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
public class MinimalServlets
{
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class, "/*");
server.start();
server.join();
}
#SuppressWarnings("serial")
public static class HelloServlet extends HttpServlet
{
#Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
//From here you can call the generateHtml method
response.getWriter().println("<h1>Hello from HelloServlet</h1>");
}
}
}

Categories