0% found this document useful (0 votes)
18 views29 pages

Advanced Programming / Java Programming: by Melese E

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views29 pages

Advanced Programming / Java Programming: by Melese E

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Advanced Programming

/
Java Programming
By Melese E.

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 1


Advanced Programming
/
Java Programming

Servlets

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 2


Servlet – Introduction
• Java servlets are a key component of server-side Java development
• Servlets are small programs that execute on the server side of a web connection
• Servlets run inside a Java Virtual Machine (JVM) on the web server
• A servlet accepts a client request, processes it and sends a response back to
the client
• Servlet is an alternative to other dynamic web content technologies
• Some of the dynamic web content technologies are Common Gateway Interface
(CGI), Active Server Pages (ASP), Server-side JavaScript

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 3


Servlet – Introduction
• Advantages of using servlets
• Portability – are written in Java and conform to a well-defined and widely accepted API, they
are highly portable across operating systems and across server implementations
• Power – Servlets can harness the full power of the core Java APIs: such as networking,
multithreading, database connectivity, internationalization, RMI, object serialization, among
others. (In fact all the core Java libraries are available for servlet development)
• Efficiency – Servlet invocation is highly efficient. Once a servlet is loaded, it generally
remains in the server’s memory as a single object instance. Thereafter, the server invokes
the servlet to handle a request using a simple, lightweight method invocation
• Safety – Servlets support safe programming practices on a number of levels. Because they
are written in Java, servlets inherit the strong type safety of the Java language
• Integration – Servlets are tightly integrated with the server. This integration allows a servlet
to cooperate with the server
• Extensibility and Flexibility – The Servlet API is designed to be easily extensible. As it stands
today, the API includes classes that are optimized for HTTP servlets. But at a later date, it
could be extended and optimized for another type of servlets
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 4
Servlet – Introduction
• To run a servlet program, you need to
• Download and Install a Java enabled web server of your choice and Configure your web app
• Among the web servers that support servlet are
• Apache Tomcat, Glassfish, Jetty – In this chapter, we will use Apache Tomcat
• The classes and interfaces needed to build servlets are contained in TomcatHome\lib\servlet-api.jar
• You need to add CLASSPATH to this JAR file so that you can compile your servlet code successfully
• To configure your own web app in Apache Tomcat, do the following steps
• Identify where Apache Tomcat is installed
• Go to the webapps folder in the Tomcat installation directory
• The webapps folder is the Tomcat’s default location for storing Web Applications
• Create a folder for your app (for example: hresource)
• Create a folder name WEB-INF in hresouce
• Create a file called web.xml in WEB-INF folder
• Put the following in the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0“ metadata-complete="true">
<!-- We will configure our servlets here -->
</web-app>
• Create a file called hresource.xml in webapps folder and put the following in it
• <Context path="/hresource" docBase= "hresource" debug="0"/>
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 5
Servlet – Introduction
• Where to save your code and libraries
• Static files such as html, css, images can be saved directly in your web app folder (webapps/hresource
in the case of our example)
• Saving your java code here is not recommended since everything in this folder is accessed by every user
• To save your servlet code and other code, create a folder named classes in hresource/WEB-INF folder
• Then put your code here
• If you have JAR files (libraries) create a folder named lib in hresource/WEB-INF folder
• Then put your JAR files here in this folder
• The jakarta.servlet and jakarta.servlet.http packages provide us the classes to work
with servlets
• To start Apache Tomcat
• Go to the installation folder and open the bin folder
• Double click on the startup.bat
• To shutdown it
• Go to the same folder and double click shutdown.bat
• The server must be running before accessing any URL using the browser
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 6
Servlet – A Generic Servlet Example
import java.io.*; //for input / output
import jakarta.servlet.*;

public class ExampleServlet extends GenericServlet {


public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<h1>This is a test</h1>");
pw.println("<b>Hello there!</b>");
pw.close();
}
}
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 7
Servlet – A Generic Servlet Example
• Then compile the Java code
• javac ExampleServlet.java
• The result of the compilation is ExampleServlet.class file
• Copy this file and paste into webapps\hresource\WEB-INF\classes folder that you already
created
• The put the following configurations into the web.xml file that you already
created Used to register our servlet class file with a name – in this example
<servlet> the name is Example and the file is ExampleServlet.class
<servlet-name>Example</servlet-name>
<servlet-class>ExampleServlet</servlet-class>
</servlet> Used to map our servlet to a url – use the name
<servlet-mapping> specified previously and – use any URL of your choice
<servlet-name>Example</servlet-name>
<url-pattern>/myexample/servlet/hello</url-pattern>
</servlet-mapping>
• Use http://localhost:8080/hresource/myexample/servlet/hello to access this
servlet
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 8
Servlet – Servlet Life Cycle
• All servlet class must extend GenericServlet class which provides the following
three methods
• init() , service(), and destroy() methods
• The subclasses need to override them – at least the service() method
• Servlets run in an environment called container (within the web server)
• As a result, servlets follow a three phase life:
• Initialization – the first time a request is made to a servlet, the initialization happens (in
other words a call to the init() method is made by the container)
• This is needed to initialize resources that the servlet may need
• Service – then every time a user request comes, the service phase happens (in other words,
the service() method is called)
• The service method is called once per request and is responsible for generating response to that
request
• Destruction – if the servlet is no more needed, it has to be removed by the container – in
this case the destroy() method is called (just before removing it) in order to release the
resources that the servlet was using.

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 9


Servlet – Servlet Life Cycle
• The service() method is mandatory while the other two are optional
• The service method looks like
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException {
//what the service will do
}
• This method is called for each user request, for the URL associated with the
servlet
• This method has two arguments
• The first argument is used to describe the user request using ServletRequest object
• The second argument is an object used to send a response for the request described
in the first argument – using ServletResponse object

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 10


Servlet – HTTP Servlets
• If you need to develop servlets that specifically use HTTP protocol, use the following
classes and interfaces
• HttpServlet – your servlet class needs to be a subclass of this class
• HttpServletRequest – is an interface used to encapsulate a user’s HTTP request
• HttpServletResponse – an interface used to send an HTTP response to the requester
• HttpSession – Allows session data to be read and written
• Cookie – Allows state information to be stored on a client machine
• The classes for HTTP servlets are found in jakarta.servlet.http package
• The servlet service() life cycle method is no longer used in this case
• It will be replaced by one of the doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ),
and doTrace( ) methods
• These methods are the equivalents to the HTTP verbs (GET, POST, DELETE, PUT, TRACE, OPTIONS,
HEAD
• However, the two mostly used HTTP methods are GET and POST -> you need mostly use the doGet()
and doPost() methods
• These methods have two arguments
• The first argument is a request object which is of type HttpServletRequest
• The second argument is a response object which is of type HttpServletResponse

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 11


Servlet – HTTP Servlets
import java.io.*; //for input / output
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class HttpExampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head>");
pw.println("<title>HTTP Servlet Example</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h1>This is just an example</h1>");
pw.println("</body>");
pw.println("</html>");
pw.close();
}
}

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 12


Servlet – HTTP Servlets
• You need to register this servlet class with a unique name and you need to
register a mapping between the name of the servlet and the URL you want for
this servlet.
• Use the web.xml file to do so
<servlet>
<servlet-name>HttpExample</servlet-name>
<servlet-class>HttpExampleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HttpExample</servlet-name>
<url-pattern>/myexample/servlet/httphello</url-pattern>
</servlet-mapping>
• After registering the servlet in web.xml – use the URL in the browser of you
choice http://localhost:8080/hresource/myexample/servlet/httphello
• For every new servlet created, you must register it with a new unique name and you need to
register the mapping of the servlet name with a unique URL

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 13


Servlet – HTTP Servlets
• HttpServletResponse object has the following important methods
• ServletOutputStream getOutputStream()
• PrintWriter getWriter()
• The PrintWriter has important methods such as print(), printf(), println(), close()
• void sendRedirect(String url) – to redirect the request to another servlet or …
• void addCookie(Cookie c) – to add cookie into the response
• void setContentType(String value) – to set the content type of the response
• void addHeader(String name, String value) – this method allows response headers to have multiple
values
• void addIntHeader(String name, int value) – this method allows response headers to have multiple
values
• void addDateHeader(String name, long value) – this method allows response headers to have
multiple values
• void setHeader(String name, String value) – if the header already exists, this method replaces it with
the new value
• void setIntHeader(String name, int value) – if the header already exists, this method replaces it with
the new value
• void setDateHeader(String name, long value) – if the header already exists, this method replaces it
with the new value
• boolean containsHeader(String name) – returns true if the header with the specified name has
already been set
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 14
Servlet – HTTP Servlets
• Some of the header fields you may want to set are
• Location – in redirecting a client to a new source, the location of this resource is
specified by the Location header as an absolute URI
• Date – represents the date and time at which the message was generated
• Content-type – the MIME type that corresponds to the content of the respose
• Content-length – indicates the size of the message body in bytes (the message to
sent as a response)
• Most of the time you will only need to specify the content type using
setContentType() method of the response object – when the response is an
HTML document, the content type is “text/html”

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 15


Servlet – HTTP Servlets
• HttpServletRequest object has the following important methods
• Header and Cookie related methods
• String getHeader(String name)
• Enumeration<String> getHeaders(String name)
• int getIntHeader(String name)
• long getDateHeader(String name)
• Enumeration<String> getHeaderNames()
• Cookie[] getCookies()
• Form data and parameter methods – used to get data sent by the GET and
POST methods
• String getParameter(String name)
• String[] getParameterVaules(String name)
• Enumeration<String> getParameterNames()
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 16
Servlet – HTTP Servlets
• Some of the request header fields are
• Host – the internet host and port of the resource being requested
• User-Agent – the browser originating the request
• Accept – used to specify certain media types that are acceptable for the response
• Accept-Language – used to restrict the set of natural languages that are preferred as
a response
• Accept-Charset – to specify what character sets are acceptable for the response

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 17


Servlet – HTTP Servlets – Retrieving GET Parameters
import java.io.*; //for input / output
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
public class HttpExampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
This is a modified version of the previous program such
PrintWriter pw = response.getWriter();
that the servlet can now retrieve GET parameters sent
String abc = request.getParameter("abc");
by the requester. Use
pw.println("<html>");
http://localhost:8080/hresource/myexample/servlet/ht
pw.println("<head>");
tphello?abc=150
pw.println("<title>HTTP Servlet Example</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h1>Using doGet - Parameters</h1>");
pw.println(abc);
pw.println("</body>");
pw.println("</html>");
pw.close();
}}

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 18


Servlet – HTTP Servlets – Retrieving POST Data
• To post data to a servlet, you need a form
• This form can be a static HTML file or
• Can be displayed using a servlet
• Then you need a servlet that accepts the POST request and process the
parameters
• Such servlet must override the doPost() method
• The following program demonstrates two servlets
• One used to send the form data
• The doGet() – used to send the form to the requester
• The other used to retrieve what has been sent using the form
• The doPost() – used to process the post data when the form is submitted

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 19


Servlet – HTTP Servlets – Retrieving POST Data
import jakarta.servlet.ServletException; pw.println("<label>Name</label>");
import jakarta.servlet.http.*; pw.println("<input type='text' name='name'><br>");
import java.io.IOException; pw.println("<label>Father Name</label>");
import java.io.PrintWriter; pw.println("<input type='text' name='fname'><br>");
public class FormData extends HttpServlet{ pw.println("<input value='submit' type='Submit'>");
public void doGet(HttpServletRequest req, pw.println("</form>");
HttpServletResponse res)
pw.println("</body>");
throws IOException, ServletException {
pw.println("</html>");
res.setContentType("text/html");
pw.close();
PrintWriter pw = res.getWriter();
}
pw.println("<html>");
}
pw.println("<head>");
pw.println("<title>HTTP Servlet Example</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<form method='post'
action='http://localhost/hresource/myexample/servlet/e
mployeedata'>");

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 20


Servlet – HTTP Servlets – Retrieving POST Data
import jakarta.servlet.*; req.getParameter("fname"));
import jakarta.servlet.http.*; Enumeration<String> paramNames =
req.getParameterNames();
import java.util.Enumeration;
String name;
import java.io.*;
while((name = paramNames.nextElement())!=null){
public class ReceiveFormData extends HttpServlet {
pw.println("<br>" + name + "---" +
public void doPost(HttpServletRequest req, req.getParameter(name));
HttpServletResponse res)
}
throws ServletException, IOException{
pw.println("</body>");
res.setContentType("text/html");
pw.println("</html>");
PrintWriter pw = res.getWriter();
pw.close();
pw.println("<html>");
}
pw.println("<head>");
}
pw.println("<title>Your Data</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("Your Name is: " +
req.getParameter("name") +
"<br>Your Father name is: " +
Wednesday, June 5, 2024 By Melese E., Department of Computer Science 21
Servlet – HTTP Servlets – Retrieving POST Data
• You need to add the following in the web.xml for the servlet displaying the form
<servlet>
<servlet-name>PostingData</servlet-name>
<servlet-class>FormData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostingData</servlet-name>
<url-pattern>/myexample/servlet/employee</url-pattern>
</servlet-mapping>
• You need to add the following in the web.xml for the servlet retrieving the post
<servlet>
<servlet-name>ReceivingData</servlet-name>
<servlet-class>ReceiveFormData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ReceivingData</servlet-name>
<url-pattern>/myexample/servlet/employeedata</url-pattern>
</servlet-mapping>

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 22


Servlet – HTTP Servlets – Database Connectivity
• Copy the mysql-connector-j-8.4.0.jar into the Tomacat_HOME\lib folder
• You may need to call either the following in case your driver do not support
automatic loading
• Class.forName() or
• DriverManager.registerDriver() methods
• Then you can execute any of the DDL or DML operations
• Apply the concepts from JDBC chapter

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 23


Servlet – HTTP Servlets – Database Connectivity
import jakarta.servlet.ServletException; pw.println("<input type='text' name='name'><br>");
import jakarta.servlet.http.*; pw.println("<label>Father Name:</label>");
import java.io.IOException; pw.println("<input type='text' name='fname'><br>");
import java.io.PrintWriter; pw.println("<label>Grand Father Name:</label>");
public class EmployeeForm extends HttpServlet{ pw.println("<input type='text' name='gfname'><br>");
public void doGet(HttpServletRequest req, HttpServletResponse res) pw.println("<label>Your Age:</label>");
throws IOException, ServletException { pw.println("<input type='text' name='age'><br>");
res.setContentType("text/html"); pw.println("<label>Your Salary:</label>");
PrintWriter pw = res.getWriter(); pw.println("<input type='text' name='salary'><br>");
pw.println("<html>"); pw.println("<label>Job Title:</label>");
pw.println("<head>"); pw.println("<input type='text' name='jtitle'><br>");
pw.println("<title>HTTP Servlet Example</title>"); pw.println("<input value='submit' type='Submit'>");
pw.println("</head>"); pw.println("</form>");
pw.println("<body>"); pw.println("</body>");
pw.println("<form method='post' pw.println("</html>");
action='http://localhost/hresource/myexample/servlet/connectdb'>");
pw.close();
pw.println("<label>Employee ID:</label>");
}
pw.println("<input type='text' name='id'><br>");
}
pw.println("<label>Your Name:</label>");

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 24


Servlet – HTTP Servlets – Database Connectivity
import jakarta.servlet.ServletException; res.setContentType("text/html");
import jakarta.servlet.http.*; PrintWriter pw = res.getWriter();
import java.io.IOException; String query = "INSERT INTO employee VALUES('" + req.getParameter("id") +
"', '" + req.getParameter("name") + "', '" + req.getParameter("fname") + "', '" +
import java.io.PrintWriter;
req.getParameter("gfname") + "', " +
import java.sql.*; Integer.parseInt(req.getParameter("age")) + ", " + req.getParameter("salary") +
", '" + req.getParameter("jtitle") +"');";
public class ServletJDBC extends HttpServlet{
System.out.println(query);
Connection con=null;
pw.println("<html>");
String db = "jdbc:mysql://localhost:3306/human_resource";
pw.println("<head>");
String un = "root";
pw.println("<title>HTTP Servlet Example</title>");
String pass = "root";
pw.println("</head>");
public void init(){
pw.println("<body>");
try{
if(con != null){
Class.forName("com.mysql.cj.jdbc.Driver");
try{
con = DriverManager.getConnection(db, un, pass);
Statement st = con.createStatement();
}catch(Exception e){
int r = st.executeUpdate(query);
e.printStackTrace();
if(r > 0)
}
pw.println("Successfully inserted<br> <h1>All the emplyee
} information<h1>");
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 25


Servlet – HTTP Servlets – Database Connectivity
ResultSet rs = st.executeQuery("SELECT * FROM employee;"); }
pw.println("<table>"); }else{
pw.println("<th><td>ID</td><td>Your name</td><td>Father pw.println("Failed to Connect");
name</td><td>Grand Father Name</td><td>Your Age</td>"+
}
"<td>Your Salary</td><td>Job Title</td></th>");
pw.println("</body>");
while(rs.next()){
pw.println("</html>");
pw.println("<tr>");
pw.close();
pw.println("<td>"+ rs.getString(1) +"</td>");
}
pw.println("<td>"+ rs.getString(2) +"</td>");
public void destroy(){
pw.println("<td>"+ rs.getString(3) +"</td>");
if(con!=null)
pw.println("<td>"+ rs.getString(4) +"</td>");
try{
pw.println("<td>"+ rs.getInt(5) +"</td>");
con.close();
pw.println("<td>"+ rs.getDouble(6) +"</td>");
}catch(SQLException e){
pw.println("<td>"+ rs.getString(7) +"</td>");
e.printStackTrace();
pw.println("</tr>");
}
}
}
pw.println("</table>");
}
}catch(SQLException e){
pw.println("Failed to Insert");

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 26


Servlet – HTTP Servlets – Database Connectivity
• You need to update the web.xml file
<servlet>
<servlet-name>EmpForm</servlet-name>
<servlet-class>EmployeeForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EmpForm</servlet-name>
<url-pattern>/myexample/servlet/empform</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>JDBCTest</servlet-name>
<servlet-class>ServletJDBC</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JDBCTest</servlet-name>
<url-pattern>/myexample/servlet/connectdb</url-pattern>
</servlet-mapping>

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 27


Servlet – HTTP Servlets – Database Connectivity

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 28


The End!

Wednesday, June 5, 2024 By Melese E., Department of Computer Science 29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy