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>");
}
}
}
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 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> ");
}
}
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 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"/>