Servlets - PowerPoint PPT Presentation

Servlets l.jpg
Download
1 / 33

  • 253 Views
  • Updated On :
  • Presentation posted in: Pets / Animals

Servlets. CEN 4010. Servlets overview. Servlet Technology Handling requests Session tracking Handling Cookies JDBC Servlet. Webserver. web site files html files: text, multi-media and links Common Gateway Interface (CGI): cgi scripts: sh, csh, Perl, … Servlets:

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Download Presentation

Servlets

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Servlets l.jpg

Servlets

CEN 4010


Servlets overview l.jpg

Servlets overview

  • Servlet Technology

  • Handling requests

  • Session tracking

  • Handling Cookies

  • JDBC Servlet


Webserver l.jpg

Webserver

  • web site files

    • html files: text, multi-media and links

    • Common Gateway Interface (CGI):

      • cgi scripts: sh, csh, Perl, …

      • Servlets:

        • Java program that runs on webserver

      • JavaServer pages (JSP):

        • Contains html and Java

        • Compiled into a servlet and run on webserver


Servlet l.jpg

Servlet

  • Supports request/response model

    • client send request

    • server responds (with html page)

  • Different types of servlets

    • GenericServlet

      • not protocol specific

    • HttpServlet

      • Serves http requests


Servlet tasks l.jpg

Servlet tasks

  • process html forms

  • middle-tier processing

    • connect to sources behind firewall (e.g. DB)

  • maintain session information between requests

  • serve as concentration point for multiple clients


Servlet runs on webserver l.jpg

Servlet runs on webserver

  • requested via URL by client

    • requires special webserver

      • Tomcat, IBM application server, JRun, Oracle …

  • can start with webserver

    • permanent: if startup effort is high

  • can be started on client request

    • temporary: if rarely used

  • servlet is unaware of when it was started


Basic modes of operation l.jpg

Basic modes of operation

  • Multi threaded

    • Single servlet instance runs in many threads

    • Servlet fields shared

    • Must consider field contention

  • Single threaded

    • Multiple instances, each in one thread

    • Servlet fields are not shared


Servlet interfaces and classes l.jpg

Servlet interfaces and classes

  • Java Servlet packages

    • javax.servlet

    • javax.servlet.http

  • Part of J2EE

  • to compile include into CLASSPATH

    (tomcat)... common\lib\servlet-api.jar


Httpservlet service method l.jpg

HttpServletservice method

invoked for

“get” and “post”

method in

html form


Httpservlet class l.jpg

HttpServlet class


Servlet example helloworld java l.jpg

Servlet example: HelloWorld.java

package mypackage;

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

out.println(“<html><head><title>Hello</title></head>”);

out.println(“<body>”);

out.println("Hello World“);

out.println(“</body></html>”);

}

}


Make the servlet known as web application web xml l.jpg

Make the servlet known as web application: web.xml

<web-app>

<display-name>HelloWorld example</display-name>

<description>Welcome to HelloWorld</description>

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>mypackage.HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

</web-app>


Html example hello html l.jpg

html example: hello.html

<html>

<head>

<title>Hello World Servlet Example</title>

<body>

<form

action=“http://localhost:8080/HelloExample/hello”

method=“get”>

<input type=“submit”>

</form>

</body>

</html>


Servlet deployment on tomcat l.jpg

Servlet deployment on Tomcat

  • Create directory ...\webapps\HelloExample

    • Copy hello.html into this directory as index.html

    • Create subdirectory WEB-INF

    • Create subdirectory WEB-INF\classes

    • Compile HelloWorld.java to

      WEB-INF\classes\mypackage\HelloWorld.class

    • Copy web.xml into directory: WEB-INF

  • Open “http://localhost:8080/HelloExample”


Process form parameters l.jpg

Process Form parameters

  • html form defines fields with

    • name

    • type

    • value(s)

  • received by servlet via request parameter

  • HttpServletRequest class defines helper methods


Helper methods l.jpg

Helper methods

  • getParameter(“name”)

    • Returns string (maybe empty) or null if parameter does not exist

  • getParameterValues(“name”)

    • Returns array of strings

  • getParameterNames()

    • Returns enumeration of parameter names


Html example l.jpg

html example

<html>

<body>

<head>

<title>Request Parameters Example</title>

</head>

<h3>Request Parameters Example</h3>

Please enter

<p><form action="params" method=POST>

First Name: <input type=text size=20 name=firstname> <br>

Last Name: <input type=text size=20 name=lastname> <br>

<input type=submit>

</form>

</body>

</html>


Dopost method l.jpg

doPost method

String first = request.getParameter("firstname");

String last = request.getParameter("lastname");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><head><title>Answer</title></head>");

out.println("<body>Welcome " + first + " " + last);

out.println("</body></html>");


Keep track of session l.jpg

Keep track of session

  • http is a stateless protocol

  • but there is need to maintain session information

    • username, password

    • shopping cart

  • possible: use hidden field(s)

  • better: HttpSession


Keep track of session20 l.jpg

Keep track of session

  • session can remember values for attributes across servlet invocations

  • methods:

    • session = request.getSession(true);

    • session.setAttribute(“name”, object);

    • session.getAttribute(“name”);


Getsession l.jpg

getSession

session = request.getSession(true);

  • retrieves current session from request

  • “true” parameter causes new session to be created if it does not exist

  • session remains alive until:

    • it times out (reaches time maximum)

    • explicit cancellation


Attributes l.jpg

Attributes

  • getAttribute(“name”)

  • setAttribute(“name”, value)

    • value can be any object

  • removeAttribute(“name”)

  • getAttributeNames()


Httpsession methods l.jpg

HttpSession methods

  • getID()

  • isNew()

  • getCreationTime()

  • getLastAccessedTime()

  • invalidate()

  • setMaxInactiveInterval()

  • getMaxInactiveInterval()


Sessionservlet dopost 1 3 l.jpg

SessionServlet: doPost (1/3)

HttpSession session = request.getSession(true);

String heading;

if (session.isNew()) {

heading = "Welcome, Newcomer";

} else {

heading = "Hello Again";

}


Sessionservlet dopost 2 3 l.jpg

SessionServlet: doPost (2/3)

Integer accessCount = (Integer)session.getAttribute("accessCount");

if (accessCount != null) {

accessCount =

new Integer(accessCount.intValue() + 1);

} else {

accessCount = new Integer(0);

}

session.setAttribute("accessCount", accessCount);


Sessionservlet dopost 3 3 l.jpg

SessionServlet: doPost (3/3)

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><head><title>Answer</title></head>");

out.println("<body> " + heading + "<br>");

out.println("Number of previous accesses " + accessCount );

out.println("</body></html>");


Handle cookies l.jpg

Handle Cookies

  • allow to store information in the browser

  • can be retrieved by servlet

  • 2 types

    • temporary cookies

      • lasts as long as the browser instance

    • permanent cookies

      • must have expiration date

      • can be deleted

  • Note: browsers can disable cookies


To establish a cookie l.jpg

To establish a Cookie

  • create instance of class Cookie

    Cookie mine = new Cookie(“name”, “value”);

  • permanent has max age

    mine.setMaxAge(seconds);

  • can have domain and path

    mine.setDomain(“.aul.fiu.edu”);

    mine.setPath(“/catalog”);


To access cookies l.jpg

To access Cookies

  • through request parameter

    Cookie all[] = request.getCookies();

  • find your cookie

    for (int i=0; i<all.length; i++) {

    out.println(“Cookie name: “ + all[i].getName());

    out.println(“ value: “ + all[i].getValue());

    }


To save cookie l.jpg

To save Cookie

  • through response header

    response.addCookie(singleCookie);

  • Example:

    Cookie mine = new Cookie(“user”, “ege”);

    mine.setMaxAge(60 * 60 * 24 * 365);

    response.addCookie(mine);


Access database l.jpg

Access database

  • servlet may access database using JDBC

    • load driver

    • get connection

    • formulate statement

    • execute statement

    • process result set


Example database access l.jpg

Example: database access

Class.forName("com.sybase.jdbc.SybDriver");

conn = DriverManager.getConnection("jdbc:sybase:Tds:ocelot.aul.fiu.edu:7100",

“student", “student");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><head><title>Customers</title></head><body>");

String s1 = "select * from Customers;";

Statement s = conn.createStatement();

ResultSet result = s.executeQuery(s1);

out.println("<table border=1><tr><th>ID<th>name<th>city<th>street</tr>");

while (result.next()) {

out.println("<tr><td>" + result.getInt(1));

out.println("<td>" + result.getString(2));

out.println("<td>" + result.getString(3));

out.println("<td>" + result.getString(4) + "</tr>");

}

out.println("</table></body></html>");


Performance considerations l.jpg

Performance considerations

  • new connection is created for every request to servlet

  • other choices

    • place connection into session


  • Login