Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist - - PowerPoint PPT Presentation

adv web technologies 1 servlets introduction
SMART_READER_LITE
LIVE PREVIEW

Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist - - PowerPoint PPT Presentation

Adv. Web Technologies 1) Servlets (introduction) Emmanuel Benoist Fall Term 2016-17 Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 1 Java Servlets Introduction HttpServlets Class


slide-1
SLIDE 1
  • Adv. Web Technologies

1) Servlets (introduction)

Emmanuel Benoist

Fall Term 2016-17

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 1

slide-2
SLIDE 2

Java Servlets

  • Introduction
  • HttpServlets Class

HttpServletResponse HttpServletRequest Lifecycle Methods

  • Session Handling

Example: Guess a Number

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 2

slide-3
SLIDE 3

Introduction

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 3

slide-4
SLIDE 4

Introduction to Servlets

Modules inside Request/Response-oriented Servers Can handel requests comming from HTML Forms and update the company DataBase. Servlet API : assumes nothing about how the servlet is used Allows servlets to be embedded in many different Web Servers. Platform independant Base for Java and the Web

Java Framework for Web Applications Specifications implemented in may web servers Powerfull and clean tool

Servlets vs PHP

PHP is aimed for small to middle size projects (PHP 4) or pure web projects (PHP 5). Java : Reusability of existing frameworks or packages, synergies with applications. AJAX : Web Site has the same fonctionalities as an Application

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 4

slide-5
SLIDE 5

Java Servlets ?

Server gets a request

Set of rules to send a request to a specific class One URL → One java class (.class file)

Each class is instanciated only once

One occurence Many requests: methode executed many times (for the same

  • bject)

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 5

slide-6
SLIDE 6

Servlets Architecture Overview, The servlet API

Central Abstraction : Servlet interface All servlets implement this interface Servlet interface defines the methods for communication with clients Servlets receve two objects for any request:

ServletRequest ServletResponse

For the web (HTTP)

A class to extend HttpServlet Two classes for the parameters, HttpServletRequest and HttpServletResponse.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 6

slide-7
SLIDE 7

HttpServlets Class

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 7

slide-8
SLIDE 8

Interacting with Clients

Servlets that specialize HttpServlets should override the methods designed to handle HTTP interactions → doGet for andling the GET and HEAD requests → doPost for handling POST requsts → doPut for handling PUT requests → doDelete for handling DELETE requests By default these methods return a BAD REQEST (400) error The service method also calls the doOptions and doTrace methods respectively as response to OPTIONS and TRACE requests

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 8

slide-9
SLIDE 9

Parameters

The methods take two arguments : HttpServletRequest Contains the request HTTP

Http method used (get, post, . . . ) Http header informations (useragent, prefered language, . . . ) Parameters sent by the client Cookies Session informations

HttpServletResponse Used to store the informations to send to the client

Http status and header Cookies Body of the message

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 9

slide-10
SLIDE 10

HttpServletResponse

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 10

slide-11
SLIDE 11

The HttpServletResponse class

To return Text, use the method getWriter If you want to return data, use method getOutputStream You should set HTTP header data before sending data.

setStatus Set the status code and message for this response sendError Sends and error response to the client sendRedirect Sends a temporary redirect response to the client ...

In HTTP Header you can insert a Cookie with addCookie

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 11

slide-12
SLIDE 12

Hello World

import java.io.∗; import javax.servlet.∗; import javax.servlet.http.∗; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType(”text/html”); PrintWriter out = response.getWriter();

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 12

slide-13
SLIDE 13
  • ut.println(”<html>”);
  • ut.println(”<head>”);
  • ut.println(”<title>Hello World!</title>”);
  • ut.println(”</head>”);
  • ut.println(”<body>”);
  • ut.println(”<h1>Hello World!</h1>”);
  • ut.println(”</body>”);
  • ut.println(”</html>”);

} }

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 13

slide-14
SLIDE 14

HttpServletRequest

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 14

slide-15
SLIDE 15

The HttpServletRequest class

Access information in the Http header

getHeader(String name)

request.getHeader(”UserAgent”); Access GET and POST parameters (independently of the method)

String getParameter(String name) returns the value of name, or null if it is not defined. Enumeration getParametersNames() returns an Enumeration of the names String[] getParmeterValues(String name)

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 15

slide-16
SLIDE 16

The HttpServletRequest (Cont.)

Access to the cookies

getCookies() returns an array of cookies sent by the client.

For HTTP methods POST PUT and DELETE, you have the choice:

getReader() : returns a BufferReader to read directly the input if you expect text data getInputStream : returns a ServletInputStream if you expect binary data.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 16

slide-17
SLIDE 17

Hello Boss

public class HelloBoss extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{ PrintWriter out = response.getWriter();

  • ut.println(...);
  • ut.println(”<h1>Hello World!</h1>”);

String username = request.getParameter( ”username”); if(username==null) printForm(out); else out.println(”Hello ”+username);

  • ut.println(”...”);

}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 17

slide-18
SLIDE 18

Hello Boss (Cont.)

void printForm(PrintWriter out){

  • ut.println(”<form>”);
  • ut.println(”What is your name? ”);
  • ut.println(”<input type=\”text\””+

”name=\”username\”>”);

  • ut.println(”</form>”);
  • ut.println(””);

} }

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 18

slide-19
SLIDE 19

Lifecycle Methods

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 19

slide-20
SLIDE 20

Lifecycle methods : init

Initialisation : the server should prepare the resources it manages Init method takes a ServletConfig object as a parameter The method have to save this object, so it can be returned by the getServletConfig method : call the super.init method.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 20

slide-21
SLIDE 21

Lifecycle methods : init (Cont.)

public void init(ServletConfig config) throws ServletException { super.init(config); //Store the directory that will hold the //survey−results files resultsDir = getInitParameter(”resultsDir”); //If no directory was provided, if (resultsDir == null) { throw new UnavailableException (this, ”Not given a directory!”); } }

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 21

slide-22
SLIDE 22

Lifecycle methods : destroy

This method is called when the server unloads the servlet It should undo any initialization and synchrionize persistent state with current in-memory state. The service method might still be running when destroy is called It is ofen used to close connection to a server (for instance Data Base)

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 22

slide-23
SLIDE 23

Lifecycle methods : destroy (Cont.)

/∗∗ Cleans up database connection ∗/ public void destroy() { try {con.close();} catch (SQLException e) { while(e != null) { log(”SQLException: ” + e.getSQLState() + e.getMessage() + ’\t’ + e.getErrorCode() + ’\t’); e = e.getNextException(); } } catch (Exception e) { e.printStackTrace(); } }

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 23

slide-24
SLIDE 24

Providing information about the Servlet

Some applets and applications display information about a servlet For instance:

short description purpose of the servlet author version number

The servlet API provides the method getServletInfo to return this information

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 24

slide-25
SLIDE 25

Providing information about the Servlet

public class SimpleServlet extends HttpServlet { ... public String getServletInfo() { return ”A simple servlet”; } }

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 25

slide-26
SLIDE 26

Session Handling

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 26

slide-27
SLIDE 27

Session Handling

Session are everywhere on the internet

Authorisation Basket for e-commerce Statistics . . .

Get the current Session Session session = request.getSession() Get attributes of a session

getAttribute(name) returns the Object stored under the given name setAttribute(name, value) affects an Object to a string removeAttribute(name) to end the action.

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 27

slide-28
SLIDE 28

Example: Guess a Number

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 28

slide-29
SLIDE 29

Example: Guess a Number

Game for kids

The user has to find a number The computer choose a number, it answers higher or lower

Java Structures

Form to type the guess Tests if valid If not : error If OK, compares with the hidden number

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 29

slide-30
SLIDE 30

Guess.java

Access the GET parameter number String number = request.getParameter(”number”); Creates a new number to find if needed if(request.getSession().getAttribute(”TOGUESS”) ==null){ int answer = Math.abs(new Random().nextInt() % 100) + 1; request.getSession().setAttribute( ”TOGUESS”, new Integer(answer)); } int toGuess = ((Integer)request.getSession(). getAttribute(”TOGUESS”)).intValue(); int intGuess = −1;

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 30

slide-31
SLIDE 31

Guess.java (Cont.)

Tests the inputs: if(number==null){

  • ut.println(”Wellcome in our game,”);
  • ut.println(”choose a number”);

} else{ try { intGuess = Integer.parseInt(number); } catch (Exception e) { error(out,”Malformed number”); return; } if(intGuess <0 || intGuess > 100){ error(out,”Number out”); return; }

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 31

slide-32
SLIDE 32

Guess.java (Cont.)

Test the value to return the message if(intGuess==toGuess){

  • ut.println(”Congratulation you found it”);

request.getSession().setAttribute(”TOGUESS”,null); } else if(intGuess < toGuess){

  • ut.println(”Nice Try, it’s larger<br>”);

} else{

  • ut.println(”Not so bad, it’s smaller<br>”);

}

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 32

slide-33
SLIDE 33

Conclusion

Java Servlets Engine handles HTTP Requests and generate Responses Servlet Class receives HTTPServletRequests and HTTPServletResponse Servlet can use built-in mechanism for dealing with

Sessions, Configuration of the application

Servlet contain a lot of out.println

Layout is developed in Dreamwaver Then transformed in Java What about a modification?

Idea: could we integrate Java inside a HTML page like for PHP

Anwer Yes, it is called JSP (Java Server Pages)

Berner Fachhochschule | Haute cole spcialise bernoise | Berne University of Applied Sciences 33