Solved

servlet example issue

Posted on 2014-02-23
6
414 Views
Last Modified: 2014-04-03
Hi,

I am trying below example


http://www.tutorialspoint.com/servlets/servlets-first-example.htm
[// 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.
  }
}/code]

The above code in link did not work.

I have to modify the code as below to make it work at URL
http://localhost:8080/TutorialPointServletProj/HelloWorld

[quote]package com.tp.first;

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;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String message;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    
    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>");
}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
[/quote]

Which worked after some trial and error
My web.xml looks as below
[code]<?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>TutorialPointServletProj</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>
</web-app>

Open in new window


I wonder why i do not have servlet mapping either


please advise
Any links resources ideas highly appreciated. Thanks in advance
0
Comment
Question by:gudii9
  • 3
  • 3
6 Comments
 
LVL 20

Expert Comment

by:chaitu chaitu
Comment Utility
servlet mapping was not there in your first example.thats why its not working.

<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>

in the second example you are using annotation so its working.

@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet

check this example.

http://www.javatpoint.com/servlet-with-annotation
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
When I try to create Servlet by adding web.xml mapping entry giving error saying HelloWorld servlet name already exists. How to fix this. please advise
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
I just created separate dynamic webprojec callled WebExample and put this servlet. There is no other servlet woth same name but i still get error saying 'same servlet already existing' like that. Doe eclipse check all other dynamic web projects and see if any other servlet with same name?
I see on HelloWorld.jsp is there in one other project but not servlet

If I use annotation as below
package com.gp;

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;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/HelloWorld2")
public class HelloWorld2 extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String message;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld2() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */

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


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

Open in new window


Do I still need to have web.xml?
Can I remove web.xml as annotation is taking care of the configuration.

I wrote code as above and ran on tomcat 7 server. When i right click on the servlet and said Run As --->Server
I do not see browser page opened automatically as below on my other laptop.
http://localhost:8080/HelloWorld2
Do I need to do make any set up changes so that IE automcatically opens and go to URL
http://localhost:8080/HelloWorld2
Please advise.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 7

Author Comment

by:gudii9
Comment Utility
I am not able to run this annotation example on tomcat6 says only supports 1.3, 1.4, 1.5 only.

please advise if i only have to use tomcat7 and beyond?
0
 
LVL 20

Expert Comment

by:chaitu chaitu
Comment Utility
I ran this example in tomcat 7 its working fine.web.xml is not required.

i think you missed the contextname in the url.

http://localhost:8080/servletexample/HelloWorld2
0
 
LVL 20

Accepted Solution

by:
chaitu chaitu earned 500 total points
Comment Utility
when you use tomcat 6 then you should select dynamic project version as 2.5.

to change the version do the following step.

right clik on the project--properties--Project facets--Dynamic Web Module--select version as 2.5

for tomcat  7 you can select  Dynamic Web Module version as 3.0
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now