servlets
Download
Skip this Video
Download Presentation
Servlets

Loading in 2 Seconds...

play fullscreen
1 / 33

Servlets - PowerPoint PPT Presentation


  • 281 Views
  • Uploaded on

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:

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

PowerPoint Slideshow about 'Servlets' - Anita


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

Servlets

CEN 4010

servlets overview
Servlets overview
  • Servlet Technology
  • Handling requests
  • Session tracking
  • Handling Cookies
  • JDBC Servlet
webserver
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
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
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
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
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
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
HttpServletservice method

invoked for

“get” and “post”

method in

html form

servlet example helloworld java
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
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
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
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
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
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
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
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
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
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
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
Attributes
  • getAttribute(“name”)
  • setAttribute(“name”, value)
    • value can be any object
  • removeAttribute(“name”)
  • getAttributeNames()
httpsession methods
HttpSession methods
  • getID()
  • isNew()
  • getCreationTime()
  • getLastAccessedTime()
  • invalidate()
  • setMaxInactiveInterval()
  • getMaxInactiveInterval()
sessionservlet dopost 1 3
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
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
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
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
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
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
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
Access database
  • servlet may access database using JDBC
    • load driver
    • get connection
    • formulate statement
    • execute statement
    • process result set
example database access
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
Performance considerations
  • new connection is created for every request to servlet
  • other choices
    • place connection into session
ad