Saturday, October 10, 2015

IP : Basic Form to Java Servlet Communication Tutorial


If you haven't tried the "Hello World" program in the blog, I recommend you to try it. Or else, you won't be able to follow this tutorial. And, you can use my code.

http://semlabs.blogspot.in/2015/09/ubuntu-java-servlet-code-for-displaying.html

because, I am gonna use the files in that and teach you stuff in this tutorial. Should have taught the Hello-World program itself actually, but I couldn't because of time constraints.

Anyways, let's start!

First of all, get the Hello-World Code files.

Now if you see, the folder is named "hello". This is the name of your web app.

A web application or web app is a client-server software application in which the client (or user interface) runs in a web browser. (Source : Wikipedia)

You would have placed the "hello" folder in your webapps folder, which is present in the tomcat files directory.

Now, let's take a look at the hierarchy of folders and files in "hello" folder.

cd /opt/tomcat/bin

./startup.sh



Below is a series of screen shots of the file explorer in my Ubuntu system.






Now, in each screen shot, if you see the top part, you will be able to see the path of the directories. That should help you understand what file is in which folder.

And, by the way, the "src" folder is not necessary, but we just keep it for our convenience.

But other folders : "WEB-INF" and "classes" are important and they must be named in the same way as they are named over here. These stuff are case sensitive, so please be careful when you are naming them, when you create a new web app.

So, now that we know the hierarchy of the folders, we are going to create a new web app with this hierarchy, and we will create the files one by one.

Go to your webapps folder. Create a new folder named "formexample".

Go inside this folder and create a new folder and name it "WEB-INF" and inside "WEB-INF" create two folders "classes" and "src", like how it was created in Hello-World program.

Now, we are going to create the files. First of all, let me tell you the aim of the program.

The aim is to display a form in a web page, which can contain anything, for simplicity, let's say we are going to get details of a student, we will just get his name. And when the student clicks "Submit" in the form, the form reaches the server and the server should display "Hi Karuppiah, your form is submitted" in a new web page, if the name typed was "Karuppiah".

First, let's create the web page with the form.

<html>

<head>
<title>Example</title>
</head>

<body>

    <form method="POST" action="server">
        Name : <input type="text" name="studname"> <br/><br/>
        <input type="submit" value="Submit">
    </form>
</body>

</html>

Now, that will create the form. And note the name attribute for the first input tag. The first input tag is used to create a text box to get text input, our name. And the next input tag is to create a button (meaning type is "submit") for submitting our form. Note the action attribute of form tag. We will talk about this soon.

And we are using POST method to submit information to the server. We can use GET method too. Google about the differences!

Place the example.html in "formexample" folder.

Now, let's create the server.java , the servlet code, which is used to send response webpage, when the user clicks Submit button in the form.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class server extends HttpServlet
{
    public void doPost(HttpServletRequest request,HttpServletResponse response)
    {
        PrintWriter out = null;

        response.setContentType("text/html");
               
        try
        {
            out = response.getWriter();
           
            String studname = request.getParameter("studname");

            out.println("Hey " + studname);

            out.close();

        }
        catch(Exception e)
        {
            out.println(e);
        }

    }

}

The class's name is server. And since, we used POST method in our form, the method used is doPost(). It's actually a built in function of HttpServlet class, which we override for our purpose. And if we use GET method in our form, we override doGet().

The "request" object contains all the data sent by the client to the server and response is the object which is going to be sent by the server to the client as a response to the request. We use the request object to get the information typed by the client. Here, we use "studname" , the name attribute of the form, to refer to the  input tag in the form and to get the value typed in the text box in the form, by using getParameter() function. And to write to the response object, that is put data in the response object, we use PrintWriter class object "out". So, after getting the information typed by the client, we put this information along with the word "Hey " in the response object using "out" and now we are done. The servlet engine will take care of sending this response to the client who sent the request.

Place this server.java file in "src" folder, which is in formexample -> WEB-INF -> src

And compile this java program using the command

javac -cp /opt/tomcat/lib/servlet-api.jar server.java

If you installed your tomcat somewhere else, accordingly change the path in the command, to the appropriate path, instead of "/opt/tomcat" .

Place the class file in the "classes" folder, which is in
formexample -> WEB-INF -> classes

After this, we need to define the web.xml file

<web-app>

    <welcome-file-list>
        <welcome-file>example.html</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>server</servlet-name>
        <servlet-class>server</servlet-class>
    </servlet>

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

"welcome-file" tag is used to mention the first page or welcome page of the webapp. Others are self explanatory. "servlet-name" is the name of servlet, you can give anything. "servlet-class" is the name of the class file which we get after compiling the servlet's java file. Here we created server.java, so when we compile, we will get server.class , so the class name is "server".

And coming to "url-pattern" , well, this will tell the url to be displayed when the response page of the server is displayed. And remember to put the forward slash along with the name you want in the url. For me it's "/server". And the name you mention here in the "url-pattern", by name, I mean "server" in my case, excluding the slash; this is the same name as the one provided in the action attribute in the form tag! If the url pattern name and the action tag's attribute are not the same, you are gonna have issues!

And after creating this web.xml, place it in "WEB-INF" folder, which is in
formexample -> WEB-INF

Now, go to the tomcat's bin folder and execute "startup.sh"

cd /opt/tomcat/bin

./startup.sh

And then, go to your browser and type

localhost:8080/formexample

And then type a name and press Enter !

Below are some screen shots. Note the URLs in the images!

Below are the source files !












No comments:

Post a Comment

Note: Only a member of this blog may post a comment.