Solved

servlet example issue

Posted on 2014-02-23
6
417 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
ID: 39881716
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
ID: 39954210
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
ID: 39954387
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 7

Author Comment

by:gudii9
ID: 39954394
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
ID: 39955154
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
ID: 39955186
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Need to track down Infection in a Server 2008 domain user profile 7 48
eclipse shortcuts 9 45
Arrays.asList  VS  ArrayList 4 44
difference of if loops 23 39
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

911 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

20 Experts available now in Live!

Get 1:1 Help Now