Java Servlet & JSP (JSJ)


JSJ:   SOLD       




This tutorial is in the name of Wawan Chahyo Nugroho (NIM: 12131294), created in order to fulfill the Final Assignment and UAS for Network Programming Course, supervised by Mr. Untung Subagyo, S.Kom


Getting to Know Java Servlet and JSP

1. Java Servlet Technology

As the web began to be used to deliver services, service providers recognized the need for dynamic content. Applets were one of the early attempts to achieve this goal, focusing on using the client platform to provide a dynamic user experience. At the same time, developers were also exploring the use of server platforms for this purpose. Initially, Common Gateway Interface (CGI) scripting was the primary technology used to generate dynamic content. Although widely used, CGI scripting technology had several drawbacks, including platform dependency and lack of scalability. To overcome these limitations, Java Servlet technology was created as a portable way to provide dynamic, user-oriented content.

2. What is a servlet?

Servlet is a Java programming language class used to extend the server's ability to host an application accessed using the request-response programming model. Although servlets can respond to any type of request, they are usually used to extend applications hosted by a web server. For such applications, Java Servlet technology defines HTTP in the form of more specific servlet classes.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When implementing generic services, you can use or extend the GenericServlet class that comes with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, to handle HTTP-specific services.

3. JavaServer Pages (JSP) Technology

JavaServer Pages (JSP) technology allows you to easily create web content that has both static and dynamic components. JSP technology provides all the dynamic functionality/capabilities of Java Servlet technology but provides a more natural approach to creating static content.

The main features of JSP technology are as follows:

  • A language for developing JSP pages, which are text-based documents that describe how to process requests and construct a response.
  • An expression language for accessing server-side objects, such as jstl, etc.
  • A mechanism for defining extensions to the JSP language.

JSP technology also contains APIs used by web container developers, but these APIs are not covered in this tutorial.

JSP pages consist of HTML tags and JSP tags. JSP pages are easier to manage than servlets because we can separate designing and developing. It provides some additional features like Expression Language, Custom Tag etc.

4. Servlet Vs JSP

Like JSP, Servlets are also used to generate dynamic web pages, but both also have the most fundamental difference, namely servlet adds HTML code in Java, while JSP adds Java code in HTML. Not only that, there are still some other striking points, such as:

Servlets

  • Servlet is a Java program that supports HTML tags as well.
  • It is generally used to develop the business layer (complex computational code) of enterprise applications.
  • Servlets are created and maintained by Java developers.

JSP

  • JSP program is HTML code that also supports java statements. To be more precise, JSP embeds java in html using JSP tag.
  • Used to develop the presentation layer of enterprise applications.
  • Often used for designing websites and used by web developers.

5. JSP Page Life Cycle

Following are the phases that a JSP page goes through:

  • Translation of JSP Page / Translation of JSP pages
  • Compilation of JSP Page / Compilation of JSP pages
  • Classloading (class files are loaded by the classloader)
  • Instantiation (Objects are generated by Servlet)
  • Initialization (jspInit() method called by the container)
  • Request processing (_jspService() method called by the container).
  • Destroy (jspDestroy() method called by the container).


JSP Page Life Cycle

As in the image above, the JSP page is translated into a servlet with the help of a JSP interpreter. The JSP interpreter is a part of the web server that is responsible for translating JSP pages into servlets. After the Servlet page is compiled by the compiler and converted into a class file, then all the processes that occur in the servlet are carried out on the JSP such as initialization, responding to the browser and destroying it.

6. Example of a Simple Web Application Using Servlet and JSP

Here, we will show how a simple web application uses Servlet and JSP. Where to create a login form on a JSP page and create its validation on a Servlet page, then display the response from anywhere (either via Servlet or via JSP).

Required environment:

  • NetBeans IDE 8 (JDK 8 Ready)
  • GlassFish Server.

I hope you have both tools ready, or maybe there are those who don't know how to get GlassFish Server, here I show you:

1. Open NetBeans IDE

2. Click tools on the toolbar menu → click Servers → Add Server,


GlassFish Plugin is not available yet

3. If a notification like the one above appears, just close the notification and the Servers window.

4. Click tools on the toolbar menu → click Plugins → click the Available Plugins tab.

5. Type "GlassFish" in the Search Box.


Install Java EE Base (included GlassFish)

6. Check Java EE Base → click Install, and wait until the process is completed.


Certificate Verification

7. The certificate verification dialog will appear → click Continue.


Installation Completed!

8. Click Restart IDE Now → click Finish.

9. Repeat steps 1 & 2 → click GlassFish Server → click next.


GlassFish Server


Download GlassFish Server

10. Select Local Domain → Check the statement that you have read and agree to the license → click Download.

Simple Web Using Servlet & JSP

Here in this post we will see a simple web application using Servlet and JSP in which we will provide customer details in JSP page then get customer details in servlet and show entered customer details in Welcome page.

Environment used:

  1. Eclipse 3.3
  2. JDK6
  3. Tomcat Server 6.x

1. Create a "Dynamic Web Project" with the dynamic web module version - 2.5 Then Click Finish. The web application structure in eclipse will look like this.

2. Create a Customer.jsp page inside the WebContent folder of the web application structure.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Details</title>
</head>
<body>
<form action="insertCustomer" method="post">
<table align="center" bgcolor="#99FFCC" border="1" width="70%">
    <tr>
        <td colspan="2" align="center">Customer Details </td>
    </tr>
    <tr>
        <td>Name </td>
        <td><input type="text" name="name" maxlength="25"></td>
    </tr>
    <tr>
        <td>Address </td>
        <td><input type="text" name="address" maxlength="40"></td>
    </tr>
    <tr>
        <td>Mobile </td>
        <td><input type="text" name="mobile" maxlength="10"></td>
    </tr>
    <tr>
        <td>EmailId </td>
        <td><input type="text" name="emailid" maxlength="30"></td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" value="Submit"></td>
    </tr>
</table>
</form>
</body>
</html>

This customer page will look like below.

3. Create a servlet class InsertCustomerServlet.java. When submitting a form from the "Customer.jsp" page, the servlet will get the form values ​​in the HttpServletRequest object.

package com.room.sample.servlet;

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;

import com.room.sample.view.Customer;

public class InsertCustomerServlet extends HttpServlet{

    private static final long serialVersionUID = 1L;
    public void doPost(HttpServletRequest request, HttpServletResponse response){
        System.out.println("----- InsertCustomerServlet -----");
        try {
        // Get the customer value submitted from Customer.jsp page through HttpServletRequest object
            String name=request.getParameter("name");
            String address=request.getParameter("address");
            String mobile=request.getParameter("mobile");
            String emailid=request.getParameter("emailid");

            //Set the Customer values into Customer Bean or POJO(Plain Old Java Object) class
            Customer customer=new Customer();
            customer.setName(name);
            customer.setAddress(address);
            customer.setMobile(Long.valueOf(mobile));
            customer.setEmailid(emailid);

            RequestDispatcher dispatcher=request.getRequestDispatcher("/Welcome.jsp");
            //Set the customer instance into request.Then only the customer object
            //will be available in the Welcome.jsp page
            request.setAttribute("cust",customer);
            dispatcher.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

4. Bean Class to store information received in the Servlet class.

package com.room.sample.view;

import java.io.Serializable;

public class Customer implements Serializable{

    private static final long serialVersionUID = 1L;
    private String name;
    private String address;
    private Long mobile;
    private String emailid;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public Long getMobile() {
        return mobile;
    }
    public void setMobile(Long mobile) {
        this.mobile = mobile;
    }
    public String getEmailid() {
        return emailid;
    }
    public void setEmailid(String emailid) {
        this.emailid = emailid;
    }

}

5. Create a Welcome.jsp page to display the processed customer details.

<%@page import="com.room.sample.view.Customer"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View Customer Details</title>
</head>
<body>
<%
    Customer customer=(Customer)request.getAttribute("cust");
%>
<table align="center" bgcolor="#FFFFCC" border="1" width="70%">
    <tr>
        <td colspan="2" align="center"><%="Welcome "+customer.getName()+" !!!!. Your details Processed." %></td>
    </tr>
    <tr>
        <td>Name </td>
        <td><%=customer.getName()%></td>
    </tr>
    <tr>
        <td>Address </td>
        <td><%=customer.getAddress() %></td>
    </tr>
    <tr>
        <td>Mobile </td>
        <td><%=String.valueOf(customer.getMobile()) %></td>
    </tr>
    <tr>
        <td>EmailId </td>
        <td><%=customer.getEmailid() %></td>
    </tr>
</table>
</body>
</html>

6. Connect the data flow using web.xml. For defining servlet must pay attention to the value of the element below the element and the value of the element below must be the same. Then only the request "insertCustomer" can find which servlet is appropriate to execute from the web.xml file.

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Simple Customer Application</display-name>
  <welcome-file-list>
    <welcome-file>Customer.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>customer</servlet-name>
    <servlet-class>com.room.sample.servlet.InsertCustomerServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>customer</servlet-name>
    <url-pattern>/insertCustomer</url-pattern>
  </servlet-mapping>
</web-app>

The Welcome.jsp page will look like below.

Demo

https://youtu.be/RPsoLYsYfms

Reference


Post a Comment

Previous Next

نموذج الاتصال