Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They...

32
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
  • date post

    20-Dec-2015
  • Category

    Documents

  • view

    229
  • download

    0

Transcript of Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They...

Page 1: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

Page 2: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

Page 3: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

Page 4: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

public class MyServlet extends HttpServlet {

public void init() { //Sobreescribir para que haga lo que queramos }

public void doGet ( HttpServletRequestrequest, HttpServletResponse response)

throws ServletException, IOException { //Sobreescribir para que haga lo que queramos }

public void doPost( HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//Sobreescribir para que haga lo que queramos }

}

Page 5: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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.

Page 6: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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…)

Page 7: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Example 1import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import 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();

}}

Page 8: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Example 1import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import 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();

}}

Imports necessary classes

This is for the Date class

Page 9: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Example 1import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import 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();

}}

Every servlet extends HttpServlet

Overwrites doGet method

Page 10: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Example 1import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import 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();

}}

Tells the browser the content type of the answer

Gets writer to browser from response parameter

Page 11: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Example 1import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import 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();

}}

Get date and time from system

Printdata

tobrowser

Close connection to browser

Page 12: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

Page 13: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

Page 14: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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(); }}

Page 15: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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(); }}

Page 16: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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(); }}

Increments counter every time doGet is called by the web server

Page 17: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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(); }}

Sine Qua Non

Page 18: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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(); }}

Printdata

tobrowser

Page 19: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

Page 20: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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>");

..... ..... }}

Page 21: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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>");

..... ..... }}

Try to open the file when the servlet is called the first time

Page 22: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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>");

..... ..... }}

Read the line and convert the content to its integervalue

Page 23: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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>");

..... ..... }}

Page 24: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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>");

..... ..... }}

After count is incremented, open the file to write (overwrite), write the new number and close file

Page 25: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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>");

..... ..... }}

The restis

the same

Page 26: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

Exercise• Escriba un servlet que genere un número aleatorio entre 1

y 100 cada vez que es contactado y lo muestra al cliente junto con la IP del computador del cliente

• Además muestra el número más grande generado hasta ahora y la IP del computador para el cual lo generó

• La dirección del computador del cliente puede ser obtenida • String s = request.getRemoteHost();

– returns the IP number (like 133.8.109.158

• String s = request.getRemoteAddress(); – returns the name if it can be retrieved (like www.waseda.jp)

• Un número aleatorio entre 1 y 100 se genera con la siguiente instrucción en Java

• int numero = (int)(1 + Math.random()*100);

Page 27: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Page 28: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

public class NewServlet extends HttpServlet { int maxNumber = 0; String maxIP = ""; public void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

int aleatorio = (int)(1 + Math.random()*100); String ip = request.getRemoteAddr(); if (aleatorio > maxNumber) { maxNumber = aleatorio; maxIP = ip; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Bienvenido </h1><br>"); out.println("<h2> Su dirección IP es "+ ip+ "<br>"); out.println("Su número es "+aleatorio+"<br><br>"); out.println("El numero mayor generado es "+maxNumber); out.println("<br>Fue generado para "+maxIP); out.close(); }}

Page 29: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

public class NewServlet extends HttpServlet { int maxNumber = 0; String maxIP = ""; public void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

int aleatorio = (int)(1 + Math.random()*100); String ip = request.getRemoteAddr(); if (aleatorio > maxNumber) { maxNumber = aleatorio; maxIP = ip; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Bienvenido </h1><br>"); out.println("<h2> Su dirección IP es "+ ip+ "<br>"); out.println("Su número es "+aleatorio+"<br><br>"); out.println("El numero mayor generado es "+maxNumber); out.println("<br>Fue generado para "+maxIP); out.close(); }}

Inicializacion variables para guardar La IP y el valor del máximo

Page 30: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

public class NewServlet extends HttpServlet { int maxNumber = 0; String maxIP = ""; public void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

int aleatorio = (int)(1 + Math.random()*100); String ip = request.getRemoteAddr();

if (aleatorio > maxNumber) { maxNumber = aleatorio; maxIP = ip; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Bienvenido </h1><br>"); out.println("<h2> Su dirección IP es "+ ip+ "<br>"); out.println("Su número es "+aleatorio+"<br><br>"); out.println("El numero mayor generado es "+maxNumber); out.println("<br>Fue generado para "+maxIP); out.close(); }}

Generación número aleatorio

Obtencion ip del cliente

Page 31: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

public class NewServlet extends HttpServlet { int maxNumber = 0; String maxIP = ""; public void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

int aleatorio = (int)(1 + Math.random()*100); String ip = request.getRemoteAddr();

if (aleatorio > maxNumber) { maxNumber = aleatorio; maxIP = ip; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Bienvenido </h1><br>"); out.println("<h2> Su dirección IP es "+ ip+ "<br>"); out.println("Su número es "+aleatorio+"<br><br>"); out.println("El numero mayor generado es "+maxNumber); out.println("<br>Fue generado para "+maxIP); out.close(); }}

Actualización de los datosdel máximo generado

Page 32: Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.

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

public class NewServlet extends HttpServlet { int maxNumber = 0; String maxIP = ""; public void doGet(HttpServletRequest request,

HttpServletResponse response) throws IOException, ServletException {

int aleatorio = (int)(1 + Math.random()*100); String ip = request.getRemoteAddr(); if (aleatorio > maxNumber) { maxNumber = aleatorio; maxIP = ip; } response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1> Bienvenido </h1><br>"); out.println("<h2> Su dirección IP es "+ ip+ "<br>"); out.println("Su número es "+aleatorio+"<br><br>"); out.println("El numero mayor generado es "+maxNumber); out.println("<br>Fue generado para "+maxIP); out.close(); }}

Enviarinfoal

cliente