I have installed JDK 1.7 and Tomcat 7.0. I am unable to execute basic servlet program. Kindly tell me the process of execution. And just give me details what are new things in Tomcat 7.0.
If I have to place any annotation like #WebServlet, tell me in which file I have to place and which packages I have to import.
web.xml
<web-app>
<servlet>
<servlet-name>kiru</servlet-name>
<servlet-class>DatesrvApp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>kiru</servlet-name>
<servlet-pattern>/classes/date</servlet-pattern>
</servlet-mapping>
</web-app>
DatesrvApp.java
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class DatesrvApp extends GenericServlet {
public void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Date d = new Date();
pw.println("<b><center>Date and Time is" + d.toString() + "</center></b>");
pw.close();
}
}
GenericServlet servlet can't read your URL pattern, Please use HttpServlet.
you should put
<url-pattern>/classes/date</url-pattern>
instead of
<servlet-pattern>/classes/date</servlet-pattern>
And put servlet-api.jar file from lib folder of the directory where Tomcat 7.0 is installed in your classpath.
Please use HttpServlet as suggested by Masud.
Related
I know this question has been asked a lot but I tried everything and it's still not working for me, hoping someone can help.
I'm trying to run a servlet page on server with eclipse, keeps showing this error:
Here's my source code:
I've wrote a simple servlet page just to see it running on server:
package main.java.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class StationsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StationsServlet() {
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<body>");
writer.println("Hello");
writer.println("</body></html>");
writer.flush();
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
My web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>weather-files-war</display-name>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>stationsServlet</servlet-name>
<servlet-class>main.java.servlet.StationsServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>stationsServlet</servlet-name>
<url-pattern>/stations</url-pattern>
</servlet-mapping>
</web-app>
and finally, my folders/modules structure:
PS: I created a homepage.jsp and it's working properly on server, the problem is when hitting the servlet class.
First of all check what the problem with exclamation mark near your StationsServlet.java
Also try to add annotation #WebServlet(name = "StationsServlet ", value = "/stations")
before public class StationsServlet extends HttpServlet { in your servlet class.
it need to help.
I created a new project and a new workspace and just copied modules and classes to the new one and it worked.
I guess it was something to do with eclipse project structure and configurations.
Hope this information is useful for the programmers looking for an answer for this common issue. This answer is based on this question.
Please make sure your servlet class under the following folder
(Your Project Name)/src/main/java
Add Annotation to your servlet
#WebServlet(name="stationsServlet", value = "/stations")
Your .jsp (homepage.jsp) form should be,
Please follow these steps.
I'm a university student, currently developing an Android app for a module. Working on connecting it to a server to perform logins, etc. The department have given us a server to use and instructed us to use Servlets. I would rather do it a Restful manner, seeming as it's an industry standard. Here is the code I have written so far:
import javax.ws.rs.QueryParam;
/**
*
* #author Tom
*/
public class Login {
public boolean doLogin(#QueryParam("email") String email) {
return checkCredentials(email);
}
private boolean checkCredentials(String email){
boolean result = false;
if (email != ""){
try {
result = DBConnection.checkLogin(email);
} catch (Exception e) {
result = false;
}
} else {
result = false;
}
return result;
}
}
I wrote another class, DBConnection, but this seems to work ok (using JDBC to connect to the MySQL database).
The problem I'm having, is that when I run the webserver (using Jetty, and ant is the build tool) and try to access the page on the server through my browser, it just gives me a 503, Servlet not initialised error. I assume this is because I'm not extending the HttpServlet class? Here is some example Servlet code they gave us:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class Product extends HttpServlet
{
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
httpServletResponse.setContentType("text/plain");
PrintWriter out = httpServletResponse.getWriter();
out.println("Hello");
out.close();
}
}
They've given us a file called JettyStart.java, which starts the web server when you run ant:
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHttpContext;
public class JettyStart
{
public static void main(String[] args) throws Exception
{
//A server running at http://localhost:8085 is created
Server server = new Server();
server.addListener(":8085");
ServletHttpContext context = (ServletHttpContext) server.getContext("/");
context.addServlet("/path/to/Login", "package.name.Login");
server.start();
}
}
So how would I go about integrating Servlets into my Restful approach to communicating with the server/database? Or am I doing it all wrong?
I'm not sure if this is an answer, but you may have better luck making your project maven-based and using the jetty-maven-plugin. I have, personally. It's easy to set up if you have an IDE which can produce a simple maven archetype. You just drop the plugin into your pom and run mvn jetty:run from the command line. Wiring up the JAX-RS web services isn't too complicated, you just give them the correct annotations like so:
package com.my.project.services;
// imports here
#Path("/login")
public class Login extends HttpServlet {
#GET
#Produces({"text/html", MediaType.TEXT_HTML})
public String getLoginInfo(#QueryParam("email") String email) {
// ...
}
}
And that should be enough to get them picked up by the jetty servlet container as long as your web.xml is set up properly. If you use a maven webapp archetype this may be done for you, otherwise you'll have to poke around a bit, but if it helps this is what (the relevant parts of) my web.xml looks like in one of my projects:
<web-app>
<servlet>
<servlet-name>rest</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>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.my.project.services</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/myproject/rest/*</url-pattern>
</servlet-mapping>
</web-app>
The mapping here is saying take the servlet-name "rest" and map it to the package com.my.project.services where all my JAX-RS services live, with the #Path value appended to the end (so the login service above would be located at /myproject/rest/login). You can set the mapping paths up any way you want.
edit: should mention my project is also using Jersey. Here's a good guide to setting up a project like this: http://crunchify.com/how-to-build-restful-service-with-java-using-jax-rs-and-jersey/
Not duplicate of this question
Here is my code
HelloWorld.java
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
}
}
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Servlet</display-name>
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
there is no compilation error, however facing this issue.
Please help!!
I changed url to
http://localhost:8080/Servlet/HelloWorld
and now facing exception
Folder Structure
You should provide the class name with the package name.
However, I would recommend to try using #WebServlet(name = "HelloWorld", urlPatterns = "/helloWorld") above the servlet class.
so if owuld be :
#WebServlet(name = "Welcome", urlPatterns = "/testPage")
public class HelloWorld extends HttpServlet {
//blah blah
}
There are a couple of things to check :
- first that the application is deployed corectly on the server. You should have a .war project that is deployed. You should see a successful deployment on you server logs
- Build your url. This is composed of server IP, in your case local host, than port 8080 is usually the default, than context root (if not defined than it should be the name of the application) and last the servlet name: http://localhost:8080/appname/helloworld
There is also an possible error on your Web.xml. The servlet class tag you defined your class but has no package. Probably you have the class also in a package.
package. HelloWorld
Verify if there is another application working on the same port as Apache Tomcat.
Try to clean your Apache Tomcat server.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I have a problem with my simple servlet that I am trying to run, Hello.java. I made it in eclipse, then placed the file it in the webapps/ServletTest/WEB-INF/classes folder and compiled it, creating the file Hello.class in the same folder. I then modified my web.xml file to map the servlet and tried to run it through the following address
http://localhost:8080/ServletTest/Hello
However, this did not work, giving the following error
HTTP Status 404 -
type Status report
message
description The requested resource is not available.
Apache Tomcat/7.0.42
The mapping in the web.xml file looks like this:
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>Main.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
The code of the servlet:
package Main;
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("/Hello")
public class Hello extends HttpServlet {
private static final long serialVersionUID = 1L;
public Hello() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String path = request.getContextPath();
String ip = request.getRemoteAddr();
out.print("<html>" +
"<title>Hello</title>" +
"Hello World"+ "<br>" +
"Your ip is: " + ip + "<br>" +
"Your path is: " + path
+ "</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
The compiled Hello.class file should be in the folder
webapps/ServletTest/WEB-INF/classes/Main
since it's declared to be in package Main.
Also, you can see Tomcat's startup logs in /logs/catalina.out or /logs/catalina.log, depending.
Also, Suresh is right in the comments, use either a <servlet> declaration or #WebServlet. Don't use both.
Try to delete web.xml.
Annotation #WebServlet("/Hello") is enough for Tomcat 7+
If the root folder not having proper permission you will face this issue. So please check the root folder property and remove read only permission and add user to full access permission in security tab.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 1 year ago.
I am writing a Java Servlet, and I am struggling to get a simple HelloWorld example to work properly.
The HelloWorld.java class is:
package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
I am running Tomcat v7.0, and have already read similar questions, with responses referring to changing the invoker servlet-mapping section in web.xml. This section actually doesn't exist in mine, and when I added it the same problem still occurred.
Try this (if the Java EE V6)
package crunch;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
#WebServlet(name="hello",urlPatterns={"/hello"}) // added this line
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
now reach the servlet by http://127.0.0.1:8080/yourapp/hello
where 8080 is default Tomcat port, and yourapp is the context name of your applciation
You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like
#WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
//rest of the class
Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Writing Java servlets is easy if you use Java EE 7
#WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}
Since servlet 3.0
The good news is the deployment descriptor is no longer required!
Read the tutorial for Java Servlets.
this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.
Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output
For those stuck with "The requested resource is not available" in Java EE 7 and dynamic web module 3.x, maybe this could help: the "Create Servlet" wizard in Eclipse (tested in Mars) doesn't create the #Path annotation for the servlet class, but I had to include it to access successfuly to the public methods exposed.
You have to user ../../projectName/Filename.jsp in your action attr. or href
../ = contains current folder simple(demo.project.filename.jsp)
Servlet can only be called with 1 slash forward to your project name..
My problem was in web.xml file. In one <servlet-mapping> there was an error inside <url-pattern>: I forgot to add / before url.