Creating a WebServer

Hello, how are you?

Today’s post will be a little different. I will post about how to load a Servlet “Hello World” using forward. This post purpose it’s to let us have some base of web services, so in the future, I can post here some web service with Hibernate, Struts, Ajax, Log4J, RB and others things. It’s already a base to those who does not know how to load a web service, might follow the “advanced” posts, and even learn how can make a simple one web service. And, in the end, I will show some topics about SCWCD that we saw here (SCWCD it’s the Java certification for Web).

You will need to have JDK installed at you pc. I will make this tutorial using an IDE just to make it easier, but if you want to make without an IDE, you just have to use all created files here (XML, Java, JSP, and HTML). At the end of this post I will show how to do it without an IDE.

Two downloads are needed:

First, we shall install the Tomcat.
01) I chose the Full configuration and did “Microsoft installation pattern: Next, Next, Finish”.
Instal Tomcat 01

02) Tomcats icon will be at your system bar, if it’s not green just click on it with the right button and select “Start Service”.
Instal Tomcat 02

03) Open your browser and type http://localhost:8080, it will show you that our server is installed and ready to use.
Instal Tomcat 03

04) We shall stop Tomcat service for now. We will execute it through Eclipse, so there is no reason to leave it active.
Instal Tomcat 04

Uncompress the Eclipse file, and execute it (eclipse.exe). Eclipse will ask you to select a workspace, it’s a place where Eclipse will store the project and the configurations that we do. The directory that you chose won’t affect the final purpose of this post, so select the directory that you feel more comfortable with.
Config Eclipse 01

A Welcome Screen will be displayed, let’s change to Java perspective.
Config Eclipse 02

Let’s go to the View Servers.
Config Eclipse 03

Type Servers and choice the View.
Config Eclipse 04

Now, let’s add Tomcat. Right button on: “Servers -> New -> Server”.
Config Eclipse 05

Select Tomcat 7.
Config Eclipse 06

Point the Tomcat installation folder. Then click on Finish button.
Config Eclipse 07

Almost done with those configurations we got just one last. Double click on the Tomcat server that is on the Servers Views. A configuration screen will be displayed.
Let’s change the configuration “Server Locations” to “Use Tomcat installation (takes control of Tomcat installation)”. This configuration allow that Eclipse might have the control over Tomcat, by doing this, every time we need to change anything at the server, we can make in here. Now, just close and save it.
Config Eclipse 08

Finally, let’s do some code! o Uhull!
Create a new project at Eclipse. We will name this project of Servlet. File > New > Other.
Project 01

Type “Dynamic Web Project” and select a Web project.
Project 02

Type “Servlet” as our project name and press Finish button.
Project 03

Eclipse will ask if you want change perspective. Check no. Let’s get used to one perspective, after you can test the others at your will.
Project 04

Let’s create a first page, a welcome home page. Right click on “WebContent” > New > File.
Project 05

Name the file as index.html and click on “Finish”.
Project 06

Let’s edit index.html file, double click on it. I’ll put the code in here:

<html>
    <body>
        <h1>Olá</h1>
    </body>
</html>

We will create now a “web.xml” file, to access our welcome page. To do it, right click on “WEB-INF > New > File”. Remember, this file must stay on WEB-INF folder!
Project 07

All web.xml files have its first lines with some default configurations. You might find it easily at internet that is why I will just type it here without explains.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>hello</servlet-name>
    <jsp-file>/index.html</jsp-file>
  </servlet>

  <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>

In another day, I might explain better about web.xml tags. For now:

  • For each servlet (< servlet >) we need a mapping (< servlet-mapping >). The mapping it’s the one that will show a direction to each URL typed at the browser. The Servlet does not need to be a Java class. Realize that we are mapping the typed URL to a HTML page. In other words, mapping is used to capture the typed URL and send it to a servlet.

To run our little application right click on our project Servlet > Run as > Run on Server.
Project 08

Just click on “Finish”.
Project 09

Eclipse will open a web browser and will show the welcome page. If your Eclipse does not open the browser, after Tomcat be active, just type the follow address at your web browser: http://localhost:8080/Servlet/hello . After the first page, push the red button to stop the server, we have a lot of work ahead.

Let’s do some refactor at the index.html so it might be able to send values, and our servlet will handle those values and send it to another page. Our field names will be name, value1 and value2. Realize that we got 3 tags: “form”, “action” and method. Form put all values inside its body, it is like a bag. Everything inside the form body will go inside the request. Method will define wich kind of request will be done, there are several types and for now we are going to use the “post”. Action defines the destination our request will be delivered.

<html>
    <body>
        <form action="/Servlet/mathit" method="post">
            <h1>Hello</h1>
            Type your name: <input type="text" name="name"/> <br/><br/>
            Lets do some math?<br/>
            Type the first value to be added: <input type="text" name="value1"/> <br/>
            Type the second value to be added: <input type="text" name="value2"/> <br/><br/>
            <input type="submit" value="Do some math"/>
        </form>
    </body>
</html>

Now, we are going to create a Servlet (Java class that will handle the request). Inside the fold src we will create a package and a Java class that will extend HttpServlet. This class will receive the values from our index.html, to sum the values and forward it to a jsp.
Project 11a

Project 11b

Project 12

Project 13

package com;

import java.io.IOException;

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 Servlet extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res)    throws ServletException, IOException {
        int value1;
        int value2;
        int total = 0;
        String name = (String) req.getParameter("name");
        String warning = "";
        try {
            // I know this is ugly, but in a future we can do some refactor and apply some OO and Design principles
            value1 = Integer.parseInt((String) req.getParameter("value1"));
        } catch (NumberFormatException e) {
            // Catching this execption in case some invalid value was sent
            value1 = 0;
            warning = "We got some bad value(like in blank or non numerics values, we set 0 instead";
        }
        
        try {
            // I know this is ugly, but in a future we can do some refactor and apply some OO and Design principles
            value2 = Integer.parseInt((String) req.getParameter("value2"));
        } catch (NumberFormatException e) {
            // Catching this execption in case some invalid value was sent
            value2 = 0;
            warning = "We got some bad value(like in blank or non numerics values, we set 0 instead";
        }
        // Setting the name inte the request
        req.setAttribute("name", name);
        
        // Sending the warning to the customer
        req.setAttribute("warning", warning);

        total = value1 + value2;
        
        // Setting the total value ate the request
        req.setAttribute("total", total);
        
        // The Request Dispatcher sets the next direction to the webservice.
        // Lets redirect to the JSP that we will create.
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/show.jsp");
        
        // Sends the process forward with the request and the response
        requestDispatcher.forward(req, res);
    }
}

We will show the sum value and the sent name from our first page. Our JSP will be inside WEB-INF folder. Pay attention, inside WEB-INF folder!
Project 14

Project 15

<%@page isELIgnored="false" %>
<html>
    <body>
        Thanks ${name} for passing by. <br/>
        The total is: ${total}. <br/>
        
        <br/>${warning}
    </body>
</html>

Almost done, we will change our web.xml so it might be able to handle our new request. Do you remember our tag “action=mathit” at index.html? It is now that we are going to map it so Tomcat knows how to work with.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>  
    </welcome-file-list>
  
    <servlet>
        <servlet-name>hello</servlet-name>
        <jsp-file>/index.html</jsp-file>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
    <servlet>
        <servlet-name>final</servlet-name>
        <servlet-class>com.Servlet</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>final</servlet-name>
        <url-pattern>/mathit</url-pattern>
    </servlet-mapping> 
</web-app>

Now just starts Tomcat just like when we did the first time to access our first page, our servlet will work fine.
PS.: If your Tomcat shows an error message and does not work, go to: Servers > Tomcat (folder) > server.xml. Open it and then push F5. Execute Tomcat again.
Project 16

And to run the web service without the Eclipse it’s easier. We will use all files created here (those might be created even using a computer notepad). First, inside Tomcats installation folder, go to wtpwebapps and create the folders tree bellow (inside WEB-INF folder, it must have the same files):
Project 17

Project 18

Inside Servlet folder put the index.html file. And inside “/classes/com” will be our Servlet.class. Our file .class you can find it inside the workspace you have set up when we started the Eclipse.

Now, just start Tomcat service (like we did when we installed the Tomcat) and type http://localhost:8080/Servlet/hello in your browser.

About SCWCD:

  • All files inside WEB-INF folder are protected. Try to access our jsp: http://localhost:8080/Servlet/show.jsp . Now if we talk about index.html we can access it directly because this file is not inside of the WEB-INF folder http://localhost:8080/Servlet/index.html . All files inside WEB-INF folder are protected from direct access. Always remember this! ;)
  • Its worth memorize a sample of web.xml (with all other tags), because those tags and mappings will be found at the test.

I hope this post might be useful to you.
See you soon.

OBS.: Sorry about the double posts. I got some erros about names!

Leave a Comment