java left logo
java middle logo
java right logo
 


 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 4086
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Introduction to Java Servlets with Eclipse E-mail
User Rating: / 1358
PoorBest 

Implementation of Java Servlet

Back to our Eclipse and modify your index.jsp to something like below.

    <form action="GreetingServlet" method="POST">
        First Name: <input type="text" name="firstName" size="20"><br>
        Surname: <input type="text" name="surname" size="20">
        <br><br>
        <input type="submit" value="Submit">
    </form>

It means that every time we execute the Submit button in our JSP, it will call GreetingServlet that we created earlier. However, now, our Java Servlet actually do nothing. We need to modify our GreetingServlet.java as well.

This GreetingServlet.java contains our implementation of the Java Servlet. If you carefully pay attention to this file, you should realize that this class extends HttpServlet. So wherever you found Java classes that extends HttpServlet, those classes must definitely be a Java Servlet and there must be an entry in web.xml.

There are few Java methods created by default in GreetingServlet.java i.e.

  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  protected void doPost(HttpServletRequest request, HttpServletResponse response)

and many more.

Let’s focus on the doGet and doPost methods as these two methods are the most important. Do you remember that in our <form></form> tag, we actually specify the method attribute as POST? For your information, we can also set the method in the <form></form> tag into GET. If we specify it as POST, the doPost method will be called. On the other hand, if we specify the <form> tag as GET, doGet method will be executed. Then, what would be the difference between GET and POST?

Each method has its own advantages and disadvantages. GET has limited length for the information that is submitted but it is easily appended on the last URL of your Java Servlet. POST does not have any limitation of the length of information sent and it is hidden from the URL. For example, GET will display something like http://localhost:7001/MyFirstServlet/GreetingServlet?firstName=david&surname=test while POST would not display firstName and surname in the end of the URL. POST has URL like “http://localhost:7001/MyFirstServlet/GreetingServlet”. It is obvious that GET may have some issues on security as everyone may clearly see the information sent to the Java Servlet. POST would be a better choice but sometimes, there would just be a situation where we need to use GET to make our development easier. I am sure that as you go along, you will meet a situation where you need to use GET for sending some information to Servlet.

As our JSP used POST, let’s add some Java codes into our doPost method. Add these two lines into your doPost method so it should be like below.

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {        
        String firstName = request.getParameter("firstName").toString();
        System.out.println("firstName = " + firstName);
    }

    String firstName = request.getParameter("firstName").toString();

What does above code means? If you remember, the textbox that we created in our JSP contains the name attribute.

  <input type="text" name="firstName" size="20">

This is where the name attribute is useful. We can get the value entered by the user in the index.jsp by executing request.getParameter(“firstName”). Remember that firstName is case sensitive so firstName is different with FirstName or firstname. The next line of code is used to print out the value into your Tomcat console.

  System.out.println("firstName = " + firstName);

Okay, let’s see how the index.jsp works with our incomplete Java Servlet now. Right-click your Dynamic Web Project, choose Export and choose WAR file and keep the Destination and Web Module same as before (remember to tick the Overwrite existing file in the final step of your WAR export wizard) then press Finish button. Then pay attention to your Tomcat carefully. Remember that Tomcat AUTOMATICALL re-deploy your application if it found a new WAR file is located in its webapps folder.

After few seconds, Tomcat will detect that the WAR file has changed and it automatically re-deploy it as shown on illustration below.



Image

Now, try to go to your browser and go to http://localhost:8080/MyFirstServlet again, provide your first name and surname and try to press the Submit button and see the Tomcat console on what’s happening.



Image

After pressing Submit button, it goes to blank page. This is happening because we have not specified the successful page.



Image

And the Tomcat console has something interesting to look at.



Image

It displays “firstName = David”. It means that our doPost implementation of our Java Servlet has been successfully executed. Try to play around with it and provide with few different first names and pay attention to your Tomcat console.

Now, our Java Servlet has been proven to execute successfully but it has not greeted the user properly. After pressing Submit button, it goes to blank page. We need to modify it to go to success page. Ok, let’s get back to our Eclipse.

Please modify your doPost method in your GreetingServlet.java into below codes.

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String firstName = request.getParameter("firstName").toString();
        String surname = request.getParameter("surname").toString();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GreetingServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () "</h1>");
        out.println("<p>Welcome " + firstName + " " + surname + "</p>");
        out.println("</body>");
        out.println("</html>");

        out.close();

Let’s see on what the codes do.

        String firstName = request.getParameter("firstName").toString();
        String surname = request.getParameter("surname").toString();

The two lines above are used to get the firstname and the lastname from our JSP.

Then, these two variables are used and displayed into JSP and located in below codes. The out.println(“”); is used to render the HTML into JSP page.

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet GreetingServlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet GreetingServlet at " + request.getContextPath () "</h1>");
        out.println("<p>Welcome " + firstName + " " + surname + "</p>");
        out.println("</body>");
        out.println("</html>");

You need to re-deploy your Dynamic Web Project into Tomcat (by exporting it into WAR file) and refresh your Internet Browser.

However, there is a little problem. PrintWriter may be red-underlined by Eclipse as we have not imported the necessary packages for it. Red-underlined means that it is syntax-error and we should fix it before exporting it into WAR file for deployment. Do not be afraid, click on the symbol on the left side of the codes and choose “Import PrintWriter (java.io)”. Yes, IDE is supposed to help your programming easier and fun. If you develop it in less sophisticated IDE such as Notepad, you need to figure out by yourself on what import statement that you need to insert for PrintWriter class.



Image

Okay, please re-deploy your Dynamic Web Project by exporting it into WAR file again as described in earlier discussion. Wait until Tomcat console has shown that it has been re-deployed, refresh your browser and try to press Submit button again and see what’s happening now.

My final screen looks like



Image

Congratulations, you have successfully created your Java Servlet.

How to Shutdown Tomcat Manually

Shutting down Tomcat is simple. You can double click on the shutdown.bat in your Tomcat’s bin folder. It will open another “closing” console and after few seconds, both consoles will be disappeared and you should not be able to try to access http://localhost:8080 anymore.



Image

Conclusion

Well, I am sure that you now have been able to create a Servlet using Eclipse 3.1.2 with the help of Web Tools Platform (WTP) plugin. By reading this tutorial, you should be able to send information to Java Servlet, know how to get this information from your Java Servlet and redirect the user to the success page. However, you should practice more and more as your skills will be improved along your experiences. There are still a lot of things in Java world that you need to know such as Filter, Listener, Struts, EJB and etc. If you grab the concept, you are good to go to the next level. I wish you all the best luck

You can find the NetBeans project for the tutorial source codes here.
The README file for the sources is available here.


 Related Tips



 
< Prev   Next >
Posted by Prabhu, prabhurangasamy@gmail.com on Tuesday, 27 June 2006 at 9:17

Hai guys. This is the best, best, best website which gives me an idea for using the webtools platform of eclipse.


 1 
Page 1 of 1 ( 1 comments )

You can share your information about this topic using the form below!

Please do not post your questions with this form! Thanks.


Name (required)


E-Mail (required)

Your email will not be displayed on the site - only to our administrator
Homepage(optional)



Comment Enable HTML code : Yes No



 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.