I am using Eclipse Kepler, Java, Jboss 7.1 and Mongodb.
When I am trying to send request from the Servlet to the class that works with the Mongodb I get an exception:
java.lang.ClassNotFoundException: org.bson.conversions.Bson
I am including the org.bson to the prohect by importing jar file named mongo-java-driver-3.0.3.jar.
The code is really basic and simple:
import java.net.UnknownHostException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.*;
public class UserConnection {
private MongoClient client;
private MongoDatabase md;
private MongoCollection<Document>userCollection;
public void initUserConnection(){
client=new MongoClient();
md=client.getDatabase("eatFreeLottery");
userCollection=md.getCollection("users");
}
public void addClient(){
Document d=new Document();
d.append("name", "Sam");
this.initUserConnection();
userCollection.insertOne(d);
}
Servlet:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserConnection uc=new UserConnection();
uc.addClient();
}
Main class:
public class Test {
public static void main(String[] args) {
UserConnection uc=new UserConnection();
uc.addClient();
}
}
Both the servlet and the class work fine as long as they don't need to work together.
At first I thought that the problem was with my glassFish server so I switched to Jboss, but that got me nowhere.
Thanks!
OK.
Just copy paste the Jar file (mongo-java-driver-3.0.3.jar) under the web-inf/lib of the project and it works.
Related
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.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 5 years ago.
I am trying to learn servlets using Eclipse Juno. I am trying to run a servlet Hello2.java using Tomcat v7.0. This error of HTTP Status 404 keeps coming up. If there is any error in my code, then How can I debug it. And if there is something by which I can ignore this error please do tell me as soon as possible.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
#WebServlet("/Hello2")
public class Hello2 implements Servlet {
private static final long serialVersionUID = 1L;
ServletConfig config = null;
public Hello2() {
super();
}
#Override
public void init(ServletConfig config) throws ServletException {
this.config=config;
System.out.println("Servlet is initialized!");
System.out.println(serialVersionUID);
}
#Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html><title>");
out.println("Hello again!");
out.println("</title><body>");
out.println("Hello Hello!!!!!!");
out.println("</body></html>");
//out.close();
}
#Override
public void destroy() {
System.out.println("Servlet is destroyed.");
}
#Override
public ServletConfig getServletConfig() {
return config;
}
#Override
public String getServletInfo() {
return "Copyright 2017-2018";
}
}
Your URL is incorrect. That's why you get 404 (client error).
Try the URL http://localhhost:8080/SDM1/Hello2
Those links were correct earlier but then I viewed some posts of other people questioning about the same error error and some solutions were given in which they were trying to add a folder names 'classes' in 'WEB-INF' folder and then adding that folder to the build path.
Even if I correct the requesting URL it still gives me this error message.
You should call the index file on running/debugging the Project.
try this URL http://localhost:8080/ or
http://localhost:8080/SDM1/WEB-INF/classes/Hello2.html
I'am trying this example https://cloud.google.com/appengine/docs/java/tools/remoteapi
Everything works fine if I run script as java application, but when I do it as servlet it always loads forever and doesn't throw any errors. Also works fine on localhost. Also I noticed it happens when query is made, when I comment it out (datastore.put), servlet loads instantly.
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;
#SuppressWarnings("serial")
public class Gae_java_Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
RemoteApiOptions options = new RemoteApiOptions()
.server("java-dot-project.appspot.com", 443)
.useApplicationDefaultCredential();
RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options);
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
System.out.println("Key of new entity is " +
datastore.put(new Entity("Hello Remote API!")));
} finally {
installer.uninstall();
}
}
}
I figured it out, needed to use RemoteApiOptions().useServiceAccountCredential("service email", "p12key") instead of useApplicationDefaultCredential()
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>");
}
}
}
I am trying log4j. I got output for printing in console. But when I try using FileAppender it shows error. I am using google app engine.
This is my code.
package com.log4jtest;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.*;
import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
#SuppressWarnings("serial")
public class Log4jTestServlet extends HttpServlet
{
int count=0;
private static Logger log=Logger.getLogger(Log4jTestServlet.class);
public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
resp.setContentType("text/plain");
/*BasicConfigurator.configure();*/
Appender app=new FileAppender(new SimpleLayout(),"hello.log");
log.setLevel(Level.TRACE);
BasicConfigurator.configure(app);
PrintWriter out=resp.getWriter();
//private static Logger log=Logger.getLogger(Log4jTestServlet.class);
String username="faisal";
String password="mohamed";
//int count=0;
count++;
out.println(count);
log.trace("TRACE");
log.debug("DEBUG");
log.info("INFO");
log.warn("WARN");
log.error("ERROR");
log.fatal("FATAl");
System.out.println("end line of the program");
resp.getWriter().println("Hello, world");
}
}
And this is my error..
Http error 500
java.io.FileOutputStream is a restricted class. Please see the Google App Engine developer's guide for more details.
now what I have to do
See answer to this: Does Google App Engine allow creation of files and folders on the server?
You cannot write files on GAE. Use console or Log API.