Transcript Servlets

Servlets
• Servlets are modules that extend the functionality of a
“java-enabled” web-server
• They normally generate HTML code and web content
dynamically. This is sent to the browser which displays it.
• For example, they send a query to a database based on
parameters sent by the browser and send the results to the
browser in html format
Development Environments
• There are many good development environments
which help to write and test the servlets
• They include an editor and a java-enabled sever
• They also include all the necessary jar files an import
statements
• Some of them are Eclipse (need to download plugins)
and Netbeans (which also has full j2ee support
Anatomy of a Servlet
• A new servlet can be written by extending the
HttpServlet class which has the following pre-defined
methods
• init()
is called when the servlet is “uploaded” the first time (this can
vary depending on the server)
• doGet(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException
is called every time the servlet is contacted by a GET request
(which is the default way)
• doPost(HttpServletRequest req, HttpServletResponse
res) throws ServletException, IOException
is called when the client contacted the servlet with a POST
request
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void init() {
//Overwrite
}
public void doGet ( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Overwrite
}
public void doPost( HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
//Overwrite
}
}
The HttpServletRequest
Parameter
• HttpServletRequest is the class of the first
parameter the server uses to calls doGet and
doPost. It gives access to:
– Information about the client, for example, parameters
passed, protocol used, client’s host, etc.
– The input stream, ServletInputStream is used by the
servlet to receive data from the client when the method
POST or PUT has been used.
The HttpServletResponse
parameter
• HttpServletResponse is the class of the second
argument.
• Provides methods for :
– Declaring the MIME type of the answer that will be
sent to the client
– Getting the output stream ServletOutputStream and a
Writer through which the servlet can send dinamically
generated html code to the browser.
– Sending other information to the browser (cookies,
refreshment time, etc…)
Example 1
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.Date;
public class SimpleServlet extends HttpServlet
{
public void doGet ( HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// set content type
response.setContentType("text/html");
// open print writer to browser
PrintWriter out = response.getWriter();
//send data
out.println("<HTML>")
out.println("<H1> Mi Primer Servlet </H1>");
out.println("<BR> <H2>Fecha y hora: "+(new Date())+"<H2>");
out.println("</HTML>");
out.close();
}
}
Example 1
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.Date;
Imports necessary classes
This is for the Date class
public class SimpleServlet extends HttpServlet
{
public void doGet ( HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// set content type
response.setContentType("text/html");
// open print writer to browser
PrintWriter out = response.getWriter();
//send data
out.println("<HTML>")
out.println("<H1> Mi Primer Servlet </H1>");
out.println("<BR> <H2>Fecha y hora: "+(new Date())+"<H2>");
out.println("</HTML>");
out.close();
}
}
Example 1
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.Date;
Every servlet extends HttpServlet
public class SimpleServlet extends HttpServlet
{
public void doGet ( HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// set content type
response.setContentType("text/html"); Overwrites doGet method
// open print writer to browser
PrintWriter out = response.getWriter();
//send data
out.println("<HTML>")
out.println("<H1> Mi Primer Servlet </H1>");
out.println("<BR> <H2>Fecha y hora: "+(new Date())+"<H2>");
out.println("</HTML>");
out.close();
}
}
Example 1
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.Date;
public class SimpleServlet extends HttpServlet
{
public void doGet ( HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// set content type
Tells the browser the content
response.setContentType("text/html");
type of the answer
// open print writer to browser
Gets writer to browser from respo
PrintWriter out = response.getWriter();
parameter
//send data
out.println("<HTML>")
out.println("<H1> Mi Primer Servlet </H1>");
out.println("<BR> <H2>Fecha y hora: "+(new Date())+"<H2>");
out.println("</HTML>");
out.close();
}
}
Example 1
import
import
import
import
java.io.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.Date;
public class SimpleServlet extends HttpServlet
{
public void doGet ( HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// set content type
response.setContentType("text/html");
// open print writer to browser
PrintWriter out = response.getWriter();
//send data
Print
out.println("<HTML>")
data
out.println("<H1> Mi Primer Servlet </H1>");
to
out.println("<BR> <H2>Fecha y hora: "+(new Date())+"<H2>");
browser
out.println("</HTML>");
out.close();
}
Get date and time from system
}
Close connection to browser
Running the first example
• Writing a servlet with Netbeans is very easy
• Also the deployment is done automatically
– Open netbeans
– Create a web project (this will create a lot of
directories for putting the different kind of
files)
– Create a servlet
– Copy the code of SimpleServlet.java
– Run the file
A second example
• Implementing a web counter
• It will count how many times an object of
this class has been creates
• It will show the Address of the computer
that contacted the servlet
• It will show a
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count extends HttpServlet {
int count = 0;
// a counter starts in 0
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
}
}
out.println("<H1> A web page counter </H1>");
out.println("<HR>");
out.println("This servlet was accessed "+count+" time(s)");
out.println("<HR>");
out.println("Your computer is "+req.getRemoteHost());
out.println("<HR>");
out.close();
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count extends HttpServlet {
int count = 0;
// a counter starts in 0
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
}
}
out.println("<H1> A web page counter </H1>");
out.println("<HR>");
out.println("This servlet was accessed "+count+" time(s)");
out.println("<HR>");
out.println("Your computer is "+req.getRemoteHost());
out.println("<HR>");
out.close();
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count extends HttpServlet {
int count = 0;
// a counter starts in 0
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
Increments counter every time doGet
is called by the web server
PrintWriter out = res.getWriter();
res.setContentType("text/html");
}
}
out.println("<H1> A web page counter </H1>");
out.println("<HR>");
out.println("This servlet was accessed "+count+" time(s)");
out.println("<HR>");
out.println("Your computer is "+req.getRemoteHost());
out.println("<HR>");
out.close();
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count extends HttpServlet {
int count = 0;
// a counter starts in 0
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
}
}
Sine Qua Non
out.println("<H1> A web page counter </H1>");
out.println("<HR>");
out.println("This servlet was accessed "+count+" time(s)");
out.println("<HR>");
out.println("Your computer is "+req.getRemoteHost());
out.println("<HR>");
out.close();
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Count extends HttpServlet {
int count = 0;
// a counter starts in 0
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter out = res.getWriter();
res.setContentType("text/html");
Print
data
to
browser
}
}
out.println("<H1> A web page counter </H1>");
out.println("<HR>");
out.println("This servlet was accessed "+count+" time(s)");
out.println("<HR>");
out.println("Your computer is "+req.getRemoteHost());
out.println("<HR>");
out.close();
What happens if the server crashes
and starts again ?
• The counter will start from 0 again
• To “remember” the value of the counter in
cast of an unexpected crash, we will write
the value of the variable in a file every time
it changes.
• At the beginning, the servlet reads the initial
value from a file, if it exists, or creates the
file with the initial value = 0
public class Count extends HttpServlet {
int count = 0;
// a counter for the object
public void init() {
try {
BufferedReader in = new BufferedReader(
newFileReader(„count.txt“));
String l = in.readLine();
count = Integer.parseInt(l);
} catch (FileNotFoundException e) {
//no need to do anything here
}
}
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter outFile = new PrintWriter(
new Filereader(„count.txt“));
outFile.println(count);
outFile.close();
PrintWriter outBrowser = res.getWriter();
res.setContentType("text/html");
outBrowser.println("<H1> A web page counter </H1>");
outBrowser.println("<HR>");
.....
.....
}
public class Count extends HttpServlet {
int count = 0;
// a counter for the object
public void init() {
try {
BufferedReader in = new BufferedReader(
newFileReader(„count.txt“));
String l = in.readLine();
count = Integer.parseInt(l);
} catch (FileNotFoundException e) {
//no need to do anything here
}
}
Try to open the
file when
the servlet is
called the first time
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter outFile = new PrintWriter(
new Filereader(„count.txt“));
outFile.println(count);
outFile.close();
PrintWriter outBrowser = res.getWriter();
res.setContentType("text/html");
outBrowser.println("<H1> A web page counter </H1>");
outBrowser.println("<HR>");
.....
.....
}
public class Count extends HttpServlet {
int count = 0;
// a counter for the object
public void init() {
try {
BufferedReader in = new BufferedReader(
newFileReader(„count.txt“));
String l = in.readLine();
Read the line and
count = Integer.parseInt(l);
convert the content
} catch (FileNotFoundException e) {
to its integer
//no need to do anything here
value
}
}
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter outFile = new PrintWriter(
new Filereader(„count.txt“));
outFile.println(count);
outFile.close();
PrintWriter outBrowser = res.getWriter();
res.setContentType("text/html");
outBrowser.println("<H1> A web page counter </H1>");
outBrowser.println("<HR>");
.....
.....
}
public class Count extends HttpServlet {
int count = 0;
// a counter for the object
public void init() {
try {
BufferedReader in = new BufferedReader(
newFileReader(„count.txt“));
String l = in.readLine();
count = Integer.parseInt(l);
} catch (FileNotFoundException e) {
//no need to do anything here
}
}
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter outFile = new PrintWriter(
new Filereader(„count.txt“));
outFile.println(count);
outFile.close();
PrintWriter outBrowser = res.getWriter();
res.setContentType("text/html");
outBrowser.println("<H1> A web page counter </H1>");
outBrowser.println("<HR>");
.....
.....
}
public class Count extends HttpServlet {
int count = 0;
// a counter for the object
public void init() {
try {
BufferedReader in = new BufferedReader(
newFileReader(„count.txt“));
String l = in.readLine();
count = Integer.parseInt(l);
} catch (FileNotFoundException e) {
//no need to do anything here
}
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
}
}
After count is incremented,
count++;
open the file to write
PrintWriter outFile = new PrintWriter(
new Filereader(„count.txt“));
(overwrite),
outFile.println(count);
write the new number
outFile.close();
and close file
PrintWriter outBrowser = res.getWriter();
res.setContentType("text/html");
outBrowser.println("<H1> A web page counter </H1>");
outBrowser.println("<HR>");
.....
.....
public class Count extends HttpServlet {
int count = 0;
// a counter for the object
public void init() {
try {
BufferedReader in = new BufferedReader(
newFileReader(„count.txt“));
String l = in.readLine();
count = Integer.parseInt(l);
} catch (FileNotFoundException e) {
//no need to do anything here
}
}
public void doGet ( HttpServletRequest req,
HttpServletResponse res) throws
ServletException, IOException {
count++;
PrintWriter outFile = new PrintWriter(
new Filereader(„count.txt“));
outFile.println(count);
outFile.close();
The rest PrintWriter outBrowser = res.getWriter();
res.setContentType("text/html");
is
outBrowser.println("<H1> A web page counter </H1>");
the
outBrowser.println("<HR>");
same
.....
.....
}
}
Parameters passed by client
• One of the most important features to make the web an
interactive environment is the passing of parameters from
client so the server
• The client can pass parameters with the request according to
the following format
– http://host:port/servlet?param1=value1&param2=value2
– This means the server will receive 2 parameters: one with name param1
and value value1 and the other with name param2 and value value2
• The servlet can ask for those values in the following way:
– String valueOfParam1 = request.getParameter(“param1”);
– String valueOfParam2 = request.getParameter(“param2”);
• Parameter names and values are strings
• Names of parameters are case sensitive (Param1 != param1)
http://host:port/ServletParameter1?firstname=Nelson&lastname=Baloian
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletParameter1 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException {
PrintWriter out = null;
response.setContentType("text/html");
// obtaining parameter value for parameter named “firstname"
String fname = request.getParameter(“firstname");
// obtaining parameter value for parameter named “lastname"
String lname = request.getParameter(“lastname");
}
}
out = response.getWriter();
out.println(<h1> "Hello "+fname+" “+lname</h1");
out.close();
The normal way is to gather
parameters with forms
• A Form is an HTML page
which may contain
graphical objects to gather
information which is sent
to the server automatically
in an URL
<HTML>
<H1>
Collecting parameters
</H1>
<FORM ACTION=“ServletParameter1”>
Nombre: <INPUT TYPE=TEXT NAME=firstname><BR>
Apellido: <INPUT TYPE=TEXT NAME=lastname><BR>
<INPUT TYPE=SUBMIT VALUE=“MANDAR”>
</HTML>
<HTML>
<H1> Collecting parameters</H1>
<FORM ACTION=“ServletParameter1”>
Nombre: <INPUT TYPE=TEXT NAME=fistname><BR>
Apellido: <INPUT TYPE=TEXT NAME=lastname><BR>
<INPUT TYPE=SUBMIT VALUE=“MANDAR”>
</FORM>
</HTML>
<FORM> y </FORM> define the beginning and end of a Formulary which will be
filled in order to transfer data to the server
ACTION= “…” defines the action that will be taken when the input button is pressed
In this case, the URL that will be called
<HTML>
<H1> Collecting parameters</H1>
<FORM ACTION=“ServletParameter1”>
Nombre: <INPUT TYPE=TEXT NAME=fistname> <BR>
Apellido: <INPUT TYPE=TEXT NAME=lastname> <BR>
<INPUT TYPE=SUBMIT VALUE=“MANDAR”>
</FORM>
</HTML>
<INPUT … defines an input (interaction) element
This element will be transfered as a parameter to the server with the URL
TYPE defines the type of element (TEXT)
NAME defines the name of the element, which will also be transfered
<HTML>
<H1> Collecting parameters</H1>
<FORM ACTION=“ServletParameter1”>
Nombre: <INPUT TYPE=TEXT NAME=fistname> <BR>
Apellido: <INPUT TYPE=TEXT NAME=lastname> <BR>
<INPUT TYPE=SUBMIT VALUE=“MANDAR”>
</FORM>
</HTML>
TYPE=SUBMIT defines a button element which will trigger the ACTION defined
VALUE=“……” label of the button
When pressing the button the URL
Shown will be sent
The parameters will be automatically
added
Other Input types
• Radio: only one element between various
alternatives can be chosen
• Select: like radiobutton but with puldown
menu
• TextArea: like text but can contain many
lines.
• Password: like text but does not show the
content (***** instead of what you really
input)
Radio
<h2> Elija una laternativa </h2>
<HTML>
<input type=radio name=radio1
value=valor1> Alternativa 1 <br>
<input type=radio name=radio1
value=valor2> Alternativa 2 <br>
<input type=radio name=radio1
value=valor3> Alternativa 3 <br>
<input type=radio name=radio1
value=valor4> Alternativa 3 <br>
</HTML>
Radio
<h2> Elija una laternativa </h2>
<HTML>
Código para chequear cuál
alternativa se seleccionó
<input type=radio name=radio1
value=“valor1”> Uvas <br>
String alt =
request.getParameter(“radio1”);
<input type=radio name=radio1
value=“valor2”> Peras <br>
if (alt.equals(“valor1”))
out.println(“Ud. Eligió Uvas”);
<input type=radio name=radio1
value=“valor3”> Higos <br>
<input type=radio name=radio1
value=“valor4”> Mangos <br>
</HTML>
else if (alt.equals(“valor2”))
out.println(“Ud. Eligió Peras”);
else if(alt.equals(“valor3”)
out.println(“Ud. Eligió Higos”);
else
out.println(“Ud. Eligió Mangos”);
Select
(Elección entre varias alternativas con pul-down menu)
HTML
Preview
SERVLET
Text Area
HTML
<h2>Ingrese aqui su opinion </h2>
<TEXTAREA NAME=“Ta1" ROWS=10 COLS=40>
lo que se excriba aca saldra
en el area pero se puede editar
</TEXTAREA>
SERVLET
String texto;
texto =
request.getParameter(“Ta1”);