SlideShare una empresa de Scribd logo
1 de 34
JSP - Servlets: A servlet example
-Gagandeep Singh
This section is going to show you a step by step to implement a simple servlet
example and run it. The example is going to:
Ask the user for a color in a JSP - in our example it will be "Home.jsp"
Display "Hello World" in the chosen color using a servlet - in our example it will be
"helloWorld.java"
Create a new project
In the menu bar, File / new / Dynamic web project.
Name your project - to be consistent with the example, name it
"ServletExample".
This By choosing "Dynamic web project", eclipse creates the default folders
hierarchy.
The folders hierarchy is shown in the
"Project Explorer" view at the left side
of the eclipse window. If it is not shown,
you can show it from the menu bar,
Window / Show View / Project Explorer.
It should look like that:
JSP, CSS files, images… etc will be
placed in the "WebContent" folder. Java
files (Servlets) will be placed in the
"Java Resources: src" folder.
Create the JSP file
In the "Project Explorer" view, R-click "WebContent" / New / JSP.
Name your JSP - to be consistent with the example, name it "Home.jsp"
Place the JSP the following code:
<%@ 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> My first JSP </title>
</head>
<body>
<form action="HelloServlet">
Please enter a color <br>
<input type="text" name="color"size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
Create the Servlet
In the "Project Explorer" view, R-click "Java Resources: src" / New / Class
Name your class - to be consistent with the example, name it "HelloWorld"
place the following code in the class:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// reading the user input
String color= request.getParameter("color");
PrintWriter out = response.getWriter();
out.println (
"<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">n" +
"<html> n" + “
<head> n" +
"<meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1"> n" +
"<title> My first jsp </title> n" +
"</head> n" +
"<body> n" +
"<font size="12px" color="" + color + "">" +
"Hello World" +
"</font> n" +
"</body> n" +
"</html>"
);
}
}
Define your servlet in "web.xml"
Open web.xml from the "Project Explorer" view, WebContent / Web-INF / R-
click web.xml / Open With / Text Editor
Replace its content by the following code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
</web-app>
Add your project to Tomcat
R-click the Tomcat server record / Add and Remove Projects; add your
project
Open the "Servers" view by clicking the "Servers" tab at the bottom of
eclipse window. If the "Servers" tab is not shown, you can show it from the
menu bar, Window / Show View/ Servers. Or Window / Show View / Other…
/ Server / Servers.
In the "Servers" view, R-click Tomcat-server record / Add and Remove
Projects (If Tomcat-server record is not there, please check Steps 5-6 in the
Configurations section by clicking next from here)
Add your project
Start "Tomcat": In the "Servers" view, R-click Tomcat-server record / Start
Test your project
In your web browser (Internet Explorer or Firefox) :
•If the port is set to 80: Type http://localhost/YourProjectName - In our
example the URL is http://localhost/ServletExample
•If the port is set to 8080: Type http://localhost:8080/YourProjectName - In
our example the URL is http://localhost:8080/ServletExample
Please note that Tomcat's default port is 8080, but the version refer to in the
Downloads section (the pre-configured version), has its port set to 80. We will
proceed in this tutorial assuming that the port is set to 80. (You can check your
version's port from Tomcat-Installation-Directory / conf / server.xml)
Click your JSP file name shown in the directory listing - in our example it is
Home.jsp
 This should be the result
Set your project's welcome file (let the server open "Home.jsp" once you open the project)
Open "web.xml" (WebContent / Web-INF / R-click web.xml / Open With / Text
Editor)
Set the "welcome-file-list" to be your home page - In our example it is Home.jsp. The
code in "web.xml" should look like that:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<welcome-file-list> <welcome-file>Home.jsp</welcome-file>
</welcome-file-list>
</web-app>
Restart the server and test your project again using
http://localhost/yourProjectName - in our example, the URL will be
http://localhost/ServletExample/.
Note that the server does not recognize changes in "web.xml" except if you
restarted, or started, the server.
If you have passed these steps successfully; so Congratulations for running your
servlet !!! To know how the process went in this example, click next.
Understanding JSP - Servlets: A servlet example
In this section, you are going to know how Servlets work by understanding the code of
our previous ServletExample and knowing how it works, from the time the user
requests the home page - in our previous example, it was Home.jsp - to displaying
"Hello World" in the color the user chose
Here is a brief on how the process goes:
1. The client requests the home page. In our example, it was "Home.jsp", and the
server replies with the HTML code of the requested page.
2. The client submits the form and the servlet's request is sent to the server (In our
example, the servlet was "HelloWorld")
3. The server locates the servlet
4. The servlet writes the appropriate HTML code to the response message
5. The response message is sent to the client
Now let's get a deeper insight into each of the previous five steps.
The Client's Request
The client requests the home page (http://localhost/ServletExample) and the server
replies with the HTML code of the requested page.
Once the client requests to view a certain page by writing its URL (in our example the
URL is http://localhost/ServletExample) , the server replies to this request by sending
the corresponding HTML data which is displayed by the client's browser.
<%@ 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> My first JSP </title>
</head>
<body>
<form action="Hello">
Please enter a color <br>
<input type="text" name="color" size="20px">
<input type="submit" value="submit">
</form>
</body>
</html>
Note that this URL, http://localhost/ServletExample does not refer to a certain file,
it refers to the project "ServletExample"; In this case, the server looks for a
"Welcome-file" in "web.xml" and replies to the request using this file. In case the
server did not find a "Welcome-file", it displays the so called "Directory-Listing"
that shows links to the HTML and JSP pages of your project.
The user starts to interact with the page by entering the required fields - in our
example we have only one field which is "color" - and then clicking the submit
button.
Client's Submit
The client submits the form and the servlet's request is sent to the server. Once the
user clicks the submit button; a request message is created and sent to the server. This
request message contains the following:
1. A request line That is the call for a URL, referring to a certain page or a servlet.
A typical Request example:
GET /path/to/file/index.html?parameter=value HTTP/1.0 | | | | | | Method -----------
path------------ ---query string--- HTTP version
This Request Line is formulated from
Method: The value of the method attribute embedded in the form tag (Default:
GET)
URL
Path: The value of the action attribute also placed in the form tag
Query String (Optional)
In our example: the form tag is as follows:
< form action="HelloServlet" method="GET" >
2. Header lines, those are lines providing information about the request. For
example, the language accepted by the client "Accept-Language: en". Read
about request headers at
http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html
3. Message body, this message body is optional. It contains the data entered or
files uploaded by the user to be sent to the server.
Sending Parameters in the Request message:
Parameters can be sent in
The Request Line
When using the method GET, parameters' names and values are concatenated
in a “Query String―that is of the form [?parameter1=value1parameter2=value2]
And, as mentioned before, this Query String is appended to the path to form the URL
The Message Body
When using the method POST, parameters are sent in the message body.
In our example, we are using the method GET. So parameters will be sent in the URL in
the form of a Query String.
We have only one parameter corresponding to one input field:
<input type="text" name="color" size="20px">
So this is how the Query String will look like:
?color=red
The Server
After the request is successfully formulated and submitted to the server, the server
starts creating a response to this request. This response is a message that contains:
1. An initial Response line: AKA Status Line, which shows the state of the requested
page. For example:
HTTP/1.0 200 OK, if page was found.
TTP/1.0 404 Not Found, if page was not found
2. Header lines: Those are lines providing information about the response. For
example, the content type of the message body Content-Type: text/html. Read
about Response headers at http://www.w3.org/Protocols/rfc2616/rfc2616-
sec14.html#sec14.17
3. The Message body: This is, for us, the most important part of the response. It is the
HTML representation of the page requested by the client. This HTML representation is
either:
Pre-constructed; in case of Static WebPages, and Client-Side scripted Dynamic
WebPages as each page has its code prewritten, and is sent to the client once it is
requested, or
Constructed on request; in case of Server-Side scripted Dynamic WebPages, as
the HTML code of the page is generated by the server after the page is requested.
A response message example and its corresponding web page when displayed by the
browser (the message body of this response is what we are trying to achieve) is as
follows:
Read more about request and response from jmarshall and
,Wikipedia. Also see Wikipedia for a response sample at
http://en.wikipedia.org/wiki/File:Http_request_telnet_ubuntu.png.
As said before, JSP – Servlets is a technology developing Dynamic
WebPages; so now let's see how the server constructs such
WebPage on request (Steps [3] and [4]).
Server Locating the Servlet
To start processing the request, the server reads the request line - in our
example, it is GET HelloServlet, The server will:
Locate the servlet by following these steps:
 Extract the url-pattern from the request line -In our example, the URL is
HelloServlet
 Search in the "web.xml" file (located under WebContent / WEB-INF ) for
the servlet-name corresponding to this url-pattern - In our example, the
servlet-name "Hello" corresponds to the url-pattern HelloServlet
 Get the corresponding servlet-class - In our example, the servlet-class is
"HelloWorld"
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
Note than in eclipse, you can create a new Servlet in two ways:
1. R-Click src / New / Class , and then do the servlet mapping in the web.xml
(like we did in our example)
2. R-Click src / New / Servlet, and the mapping, in the web.xml, is done
automatically by eclipse. The automatic mapping done by eclipse gives the
servlet-name and the url-pattern the same value of the servlet-class.For
example if we used this second way to create our servlet, the mapping in the
web.xml would look this way:
<servlet>
<servlet-name> HelloWorld </servlet-name>
<servlet-class>HelloWorld </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> HelloWorld </servlet-name>
<url-pattern>/HelloWorld </url-pattern>
</servlet-mapping>
So do not be confused, "A url-pattern is a URL used to invoke a certain servlet",
it does not have to be of the same name of the servlet class.
You can always use the New-Servlet-way to create your servlets; in our example
we used New-Class-way just for a better understanding
Find the .class file corresponding to the "servlet-class" mapped in "web.xml".
The server searches for the servlet's .class file in its specified directory.
Every web server has a directory where the .class files have to be saved in; In our
example, we are using the server "Tomcat" and its classes directory is located
under the URL
YourWorkspaceFolder / YourProjectName / build / classes; when we create our
servlets and save them under the src folder, Eclipse compiles our java code and
saves its .class file in this directory. In our example, the server will search for
"HelloWorld.class" at C: / Workspace / ServletExample / build / classes
Call the appropriate do method by:
Extracting the method from the request line - In our example, it is GET
Calling the corresponding do method - In our example, it is doGet - and
passing the request and response messages as arguments to the method
The Servlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class HelloWorld extends HttpServlet { protected void doGet(HttpServletRequest
request, HttpServletResponse response) throws ServletException, IOException {
// reading the user input
String color= request.getParameter("color");
PrintWriter out = response.getWriter();
out.println ( "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">n" +
"<html> n" +
"<head> n" +
"<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> n" +
"<title> My first jsp </title> n" +
"</head> n" +
"<body> n" +
"<font size="12px" color="" + color + "">" +
"Hello World" +
"</font> n" +
"</body> n" +
"</html>"
);
}
}
The Servlet Response
The servlet writes the appropriate HTML code to the response message. In our
example, this writing takes place when executing the doGet method. To execute the
doGet method, the servlet will:
1. Extract the value of the parameter "color" from the request message - In our
example, the value of the parameter "color" is "red" - using
request.getParameter("color") and save it into a new variable named "color" (the
variable is of type "String").
2. Get the writer of the response, so as to be able to edit the body of the response
message, using response.getWriter(); and save it to a variable named "out" (the
variable is of type "PrintWriter"). Go back to the response body explanation.
3. Write to the response using the println method of the response writer object. In
our example, the response writer is saved to the variable "out", so the method used
to write to the response body will be out.println().
The final code written to the response body, representing the result page, will look
like that:
<!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> My first jsp </title>
</head>
<body>
<font size="12px" color="red"> Hello World </font>
</body>
</html>
Response to Client
Finally, the response message is sent to the client, and the client's browser displays the
corresponding web page.
To be sure that this is the HTML code sent to the client via the response message,
view the result page's source. Go to
http://localhost/ServletExample/HelloWorld?color=red. In the Menu Bar,
View/source.

Más contenido relacionado

La actualidad más candente

Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
Prabhdeep Singh
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
Katrien Verbert
 
RESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkRESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP Framework
Bo-Yi Wu
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 

La actualidad más candente (20)

Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
 
Jsp
JspJsp
Jsp
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp
JspJsp
Jsp
 
Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course Introduction to the Servlet / JSP course
Introduction to the Servlet / JSP course
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Rich faces
Rich facesRich faces
Rich faces
 
JSP Directives
JSP DirectivesJSP Directives
JSP Directives
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
JSP
JSPJSP
JSP
 
RESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP FrameworkRESTful API Design & Implementation with CodeIgniter PHP Framework
RESTful API Design & Implementation with CodeIgniter PHP Framework
 
Java server pages
Java server pagesJava server pages
Java server pages
 
Servlets
ServletsServlets
Servlets
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsf Ajax
Jsf AjaxJsf Ajax
Jsf Ajax
 

Destacado

remote method invocation
remote method invocationremote method invocation
remote method invocation
Arun Nair
 
Servlets and jsp pages best practices
Servlets and jsp pages best practicesServlets and jsp pages best practices
Servlets and jsp pages best practices
ejjavies
 
JSP Scope variable And Data Sharing
JSP Scope variable And Data SharingJSP Scope variable And Data Sharing
JSP Scope variable And Data Sharing
vikram singh
 

Destacado (13)

Applet
AppletApplet
Applet
 
Oracle docs rmi applications
Oracle docs rmi applicationsOracle docs rmi applications
Oracle docs rmi applications
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
 
Servlets and jsp pages best practices
Servlets and jsp pages best practicesServlets and jsp pages best practices
Servlets and jsp pages best practices
 
JSP Scope variable And Data Sharing
JSP Scope variable And Data SharingJSP Scope variable And Data Sharing
JSP Scope variable And Data Sharing
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Java RMI Detailed Tutorial
Java RMI Detailed TutorialJava RMI Detailed Tutorial
Java RMI Detailed Tutorial
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
jdbc document
jdbc documentjdbc document
jdbc document
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Java database programming with jdbc
Java database programming with jdbcJava database programming with jdbc
Java database programming with jdbc
 
Teachers Application Letter
Teachers Application LetterTeachers Application Letter
Teachers Application Letter
 

Similar a Understanding JSP -Servlets

Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet example
rvpprash
 

Similar a Understanding JSP -Servlets (20)

Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet example
 
Oracle Endeca Developer's Guide
Oracle Endeca Developer's GuideOracle Endeca Developer's Guide
Oracle Endeca Developer's Guide
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
jsp tutorial
jsp tutorialjsp tutorial
jsp tutorial
 
JSP
JSPJSP
JSP
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
JEE Programming - 05 JSP
JEE Programming - 05 JSPJEE Programming - 05 JSP
JEE Programming - 05 JSP
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 MinutesBuild Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes
 
Servlets
ServletsServlets
Servlets
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
08 ajax
08 ajax08 ajax
08 ajax
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
Lecture2
Lecture2Lecture2
Lecture2
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 

Más de Gagandeep Singh (8)

Jsf login logout project
Jsf login logout projectJsf login logout project
Jsf login logout project
 
Introduction to webservices
Introduction to webservicesIntroduction to webservices
Introduction to webservices
 
Autosys
AutosysAutosys
Autosys
 
Log4jxml ex
Log4jxml exLog4jxml ex
Log4jxml ex
 
Log4jprop example
Log4jprop exampleLog4jprop example
Log4jprop example
 
Log4e
Log4eLog4e
Log4e
 
Web Sphere Administration guide – Packaging and Deploying Jee Applications
Web Sphere Administration guide – Packaging and Deploying Jee ApplicationsWeb Sphere Administration guide – Packaging and Deploying Jee Applications
Web Sphere Administration guide – Packaging and Deploying Jee Applications
 
Application server vs Web Server
Application server vs Web ServerApplication server vs Web Server
Application server vs Web Server
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

Understanding JSP -Servlets

  • 1. JSP - Servlets: A servlet example -Gagandeep Singh
  • 2. This section is going to show you a step by step to implement a simple servlet example and run it. The example is going to: Ask the user for a color in a JSP - in our example it will be "Home.jsp" Display "Hello World" in the chosen color using a servlet - in our example it will be "helloWorld.java"
  • 3. Create a new project In the menu bar, File / new / Dynamic web project. Name your project - to be consistent with the example, name it "ServletExample". This By choosing "Dynamic web project", eclipse creates the default folders hierarchy. The folders hierarchy is shown in the "Project Explorer" view at the left side of the eclipse window. If it is not shown, you can show it from the menu bar, Window / Show View / Project Explorer. It should look like that: JSP, CSS files, images… etc will be placed in the "WebContent" folder. Java files (Servlets) will be placed in the "Java Resources: src" folder.
  • 4. Create the JSP file In the "Project Explorer" view, R-click "WebContent" / New / JSP. Name your JSP - to be consistent with the example, name it "Home.jsp" Place the JSP the following code: <%@ 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> My first JSP </title> </head> <body> <form action="HelloServlet"> Please enter a color <br> <input type="text" name="color"size="20px"> <input type="submit" value="submit"> </form> </body> </html>
  • 5. Create the Servlet In the "Project Explorer" view, R-click "Java Resources: src" / New / Class Name your class - to be consistent with the example, name it "HelloWorld" place the following code in the class: import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; public class HelloWorld extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // reading the user input String color= request.getParameter("color"); PrintWriter out = response.getWriter(); out.println (
  • 6. "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">n" + "<html> n" + “ <head> n" + "<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> n" + "<title> My first jsp </title> n" + "</head> n" + "<body> n" + "<font size="12px" color="" + color + "">" + "Hello World" + "</font> n" + "</body> n" + "</html>" ); } }
  • 7. Define your servlet in "web.xml" Open web.xml from the "Project Explorer" view, WebContent / Web-INF / R- click web.xml / Open With / Text Editor Replace its content by the following code: <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> </web-app>
  • 8. Add your project to Tomcat R-click the Tomcat server record / Add and Remove Projects; add your project Open the "Servers" view by clicking the "Servers" tab at the bottom of eclipse window. If the "Servers" tab is not shown, you can show it from the menu bar, Window / Show View/ Servers. Or Window / Show View / Other… / Server / Servers. In the "Servers" view, R-click Tomcat-server record / Add and Remove Projects (If Tomcat-server record is not there, please check Steps 5-6 in the Configurations section by clicking next from here) Add your project
  • 9. Start "Tomcat": In the "Servers" view, R-click Tomcat-server record / Start
  • 10. Test your project In your web browser (Internet Explorer or Firefox) : •If the port is set to 80: Type http://localhost/YourProjectName - In our example the URL is http://localhost/ServletExample •If the port is set to 8080: Type http://localhost:8080/YourProjectName - In our example the URL is http://localhost:8080/ServletExample Please note that Tomcat's default port is 8080, but the version refer to in the Downloads section (the pre-configured version), has its port set to 80. We will proceed in this tutorial assuming that the port is set to 80. (You can check your version's port from Tomcat-Installation-Directory / conf / server.xml)
  • 11. Click your JSP file name shown in the directory listing - in our example it is Home.jsp
  • 12.  This should be the result
  • 13. Set your project's welcome file (let the server open "Home.jsp" once you open the project) Open "web.xml" (WebContent / Web-INF / R-click web.xml / Open With / Text Editor) Set the "welcome-file-list" to be your home page - In our example it is Home.jsp. The code in "web.xml" should look like that: <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>Home.jsp</welcome-file> </welcome-file-list> </web-app>
  • 14. Restart the server and test your project again using http://localhost/yourProjectName - in our example, the URL will be http://localhost/ServletExample/. Note that the server does not recognize changes in "web.xml" except if you restarted, or started, the server. If you have passed these steps successfully; so Congratulations for running your servlet !!! To know how the process went in this example, click next.
  • 15. Understanding JSP - Servlets: A servlet example In this section, you are going to know how Servlets work by understanding the code of our previous ServletExample and knowing how it works, from the time the user requests the home page - in our previous example, it was Home.jsp - to displaying "Hello World" in the color the user chose
  • 16. Here is a brief on how the process goes: 1. The client requests the home page. In our example, it was "Home.jsp", and the server replies with the HTML code of the requested page. 2. The client submits the form and the servlet's request is sent to the server (In our example, the servlet was "HelloWorld") 3. The server locates the servlet 4. The servlet writes the appropriate HTML code to the response message 5. The response message is sent to the client Now let's get a deeper insight into each of the previous five steps.
  • 17. The Client's Request The client requests the home page (http://localhost/ServletExample) and the server replies with the HTML code of the requested page. Once the client requests to view a certain page by writing its URL (in our example the URL is http://localhost/ServletExample) , the server replies to this request by sending the corresponding HTML data which is displayed by the client's browser.
  • 18. <%@ 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> My first JSP </title> </head> <body> <form action="Hello"> Please enter a color <br> <input type="text" name="color" size="20px"> <input type="submit" value="submit"> </form> </body> </html>
  • 19. Note that this URL, http://localhost/ServletExample does not refer to a certain file, it refers to the project "ServletExample"; In this case, the server looks for a "Welcome-file" in "web.xml" and replies to the request using this file. In case the server did not find a "Welcome-file", it displays the so called "Directory-Listing" that shows links to the HTML and JSP pages of your project. The user starts to interact with the page by entering the required fields - in our example we have only one field which is "color" - and then clicking the submit button.
  • 20. Client's Submit The client submits the form and the servlet's request is sent to the server. Once the user clicks the submit button; a request message is created and sent to the server. This request message contains the following: 1. A request line That is the call for a URL, referring to a certain page or a servlet. A typical Request example: GET /path/to/file/index.html?parameter=value HTTP/1.0 | | | | | | Method ----------- path------------ ---query string--- HTTP version This Request Line is formulated from Method: The value of the method attribute embedded in the form tag (Default: GET) URL Path: The value of the action attribute also placed in the form tag Query String (Optional) In our example: the form tag is as follows: < form action="HelloServlet" method="GET" >
  • 21. 2. Header lines, those are lines providing information about the request. For example, the language accepted by the client "Accept-Language: en". Read about request headers at http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html 3. Message body, this message body is optional. It contains the data entered or files uploaded by the user to be sent to the server.
  • 22. Sending Parameters in the Request message: Parameters can be sent in The Request Line When using the method GET, parameters' names and values are concatenated in a “Query String―that is of the form [?parameter1=value1parameter2=value2] And, as mentioned before, this Query String is appended to the path to form the URL The Message Body When using the method POST, parameters are sent in the message body. In our example, we are using the method GET. So parameters will be sent in the URL in the form of a Query String. We have only one parameter corresponding to one input field: <input type="text" name="color" size="20px"> So this is how the Query String will look like: ?color=red
  • 23. The Server After the request is successfully formulated and submitted to the server, the server starts creating a response to this request. This response is a message that contains: 1. An initial Response line: AKA Status Line, which shows the state of the requested page. For example: HTTP/1.0 200 OK, if page was found. TTP/1.0 404 Not Found, if page was not found 2. Header lines: Those are lines providing information about the response. For example, the content type of the message body Content-Type: text/html. Read about Response headers at http://www.w3.org/Protocols/rfc2616/rfc2616- sec14.html#sec14.17 3. The Message body: This is, for us, the most important part of the response. It is the HTML representation of the page requested by the client. This HTML representation is either: Pre-constructed; in case of Static WebPages, and Client-Side scripted Dynamic WebPages as each page has its code prewritten, and is sent to the client once it is requested, or Constructed on request; in case of Server-Side scripted Dynamic WebPages, as the HTML code of the page is generated by the server after the page is requested.
  • 24. A response message example and its corresponding web page when displayed by the browser (the message body of this response is what we are trying to achieve) is as follows:
  • 25. Read more about request and response from jmarshall and ,Wikipedia. Also see Wikipedia for a response sample at http://en.wikipedia.org/wiki/File:Http_request_telnet_ubuntu.png. As said before, JSP – Servlets is a technology developing Dynamic WebPages; so now let's see how the server constructs such WebPage on request (Steps [3] and [4]).
  • 26. Server Locating the Servlet To start processing the request, the server reads the request line - in our example, it is GET HelloServlet, The server will: Locate the servlet by following these steps:  Extract the url-pattern from the request line -In our example, the URL is HelloServlet  Search in the "web.xml" file (located under WebContent / WEB-INF ) for the servlet-name corresponding to this url-pattern - In our example, the servlet-name "Hello" corresponds to the url-pattern HelloServlet  Get the corresponding servlet-class - In our example, the servlet-class is "HelloWorld" <servlet> <servlet-name>Hello</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping>
  • 27. Note than in eclipse, you can create a new Servlet in two ways: 1. R-Click src / New / Class , and then do the servlet mapping in the web.xml (like we did in our example) 2. R-Click src / New / Servlet, and the mapping, in the web.xml, is done automatically by eclipse. The automatic mapping done by eclipse gives the servlet-name and the url-pattern the same value of the servlet-class.For example if we used this second way to create our servlet, the mapping in the web.xml would look this way: <servlet> <servlet-name> HelloWorld </servlet-name> <servlet-class>HelloWorld </servlet-class> </servlet> <servlet-mapping> <servlet-name> HelloWorld </servlet-name> <url-pattern>/HelloWorld </url-pattern> </servlet-mapping>
  • 28. So do not be confused, "A url-pattern is a URL used to invoke a certain servlet", it does not have to be of the same name of the servlet class. You can always use the New-Servlet-way to create your servlets; in our example we used New-Class-way just for a better understanding Find the .class file corresponding to the "servlet-class" mapped in "web.xml". The server searches for the servlet's .class file in its specified directory. Every web server has a directory where the .class files have to be saved in; In our example, we are using the server "Tomcat" and its classes directory is located under the URL YourWorkspaceFolder / YourProjectName / build / classes; when we create our servlets and save them under the src folder, Eclipse compiles our java code and saves its .class file in this directory. In our example, the server will search for "HelloWorld.class" at C: / Workspace / ServletExample / build / classes
  • 29. Call the appropriate do method by: Extracting the method from the request line - In our example, it is GET Calling the corresponding do method - In our example, it is doGet - and passing the request and response messages as arguments to the method
  • 30. The Servlet import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; public class HelloWorld extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // reading the user input String color= request.getParameter("color"); PrintWriter out = response.getWriter(); out.println ( "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">n" + "<html> n" +
  • 31. "<head> n" + "<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> n" + "<title> My first jsp </title> n" + "</head> n" + "<body> n" + "<font size="12px" color="" + color + "">" + "Hello World" + "</font> n" + "</body> n" + "</html>" ); } }
  • 32. The Servlet Response The servlet writes the appropriate HTML code to the response message. In our example, this writing takes place when executing the doGet method. To execute the doGet method, the servlet will: 1. Extract the value of the parameter "color" from the request message - In our example, the value of the parameter "color" is "red" - using request.getParameter("color") and save it into a new variable named "color" (the variable is of type "String"). 2. Get the writer of the response, so as to be able to edit the body of the response message, using response.getWriter(); and save it to a variable named "out" (the variable is of type "PrintWriter"). Go back to the response body explanation. 3. Write to the response using the println method of the response writer object. In our example, the response writer is saved to the variable "out", so the method used to write to the response body will be out.println().
  • 33. The final code written to the response body, representing the result page, will look like that: <!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> My first jsp </title> </head> <body> <font size="12px" color="red"> Hello World </font> </body> </html>
  • 34. Response to Client Finally, the response message is sent to the client, and the client's browser displays the corresponding web page. To be sure that this is the HTML code sent to the client via the response message, view the result page's source. Go to http://localhost/ServletExample/HelloWorld?color=red. In the Menu Bar, View/source.