Web Technology Programming Web Applications with Servlets

Similar documents
SERVLET AND JSP FILTERS

JSP. Common patterns

Servlets and JSP (Java Server Pages)

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Java Technologies Web Filters

Servlet Fudamentals. Celsina Bignoli

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

JAVA SERVLET. Server-side Programming ADVANCED FEATURES

Servlets. An extension of a web server runs inside a servlet container

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

Unit-4: Servlet Sessions:

Advance Java. Configuring and Getting Servlet Init Parameters per servlet

JAVA SERVLET. Server-side Programming INTRODUCTION

Session 8. Introduction to Servlets. Semester Project

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

AJP. CHAPTER 5: SERVLET -20 marks

Advanced Web Technology

Session 9. Introduction to Servlets. Lecture Objectives

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

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

Servlet Basics. Agenda

CIS 455 / 555: Internet and Web Systems

Using Java servlets to generate dynamic WAP content

Introduction to Web applications with Java Technology 3- Servlets

Questions and Answers

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

Java servlets CSCI 470: Web Science Keith Vertanen Copyright 2013

SERVLETS INTERVIEW QUESTIONS

JavaServer Pages (JSP)

Web based Applications, Tomcat and Servlets - Lab 3 -

Java Servlets Basic Concepts and Programming

Chapter 17. Web-Application Development

4.1 The Life Cycle of a Servlet 4.2 The Java Servlet Development Kit 4.3 The Simple Servlet: Creating and compile servlet source code, start a web

Unit 4 - Servlet. Servlet. Advantage of Servlet

Servlets by Example. Joe Howse 7 June 2011

CSC309: Introduction to Web Programming. Lecture 10

Advanced Internet Technology Lab # 4 Servlets

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

Introduction to Servlets. After which you will doget it

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

a. Jdbc:ids://localhost:12/conn?dsn=dbsysdsn 21. What is the Type IV Driver URL? a. 22.

UNIT-V. Web Servers: Tomcat Server Installation:

Servlet and JSP Review

Session 20 Data Sharing Session 20 Data Sharing & Cookies

Oracle 1Z Java EE 6 Web Component Developer(R) Certified Expert.

Introduction to JSP and Servlets Training 5-days

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Handling the Client Request: HTTP Request Headers

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

********************************************************************

Java Servlets. Preparing your System

The Structure and Components of

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

Generating the Server Response: HTTP Response Headers

文字エンコーディングフィルタ 1. 更新履歴 2003/07/07 新規作成(第 0.1 版) 版 数 第 0.1 版 ページ番号 1

JAVA SERVLET. Server-side Programming PROGRAMMING

Table of Contents. Introduction... xxi

Vendor: SUN. Exam Code: Exam Name: Sun Certified Web Component Developer for J2EE 5. Version: Demo

Servlet. Web Server. Servlets are modules of Java code that run in web server. Internet Explorer. Servlet. Fire Fox. Servlet.

CS506 Web Design & Development Final Term Solved MCQs with Reference

Oracle EXAM - 1Z Java Enterprise Edition 5 Web Component Developer Certified Professional Exam. Buy Full Product

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

ServletConfig Interface

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

Lab session Google Application Engine - GAE. Navid Nikaein

Development of the Security Framework based on OWASP ESAPI for JSF2.0

SSC - Web applications and development Introduction and Java Servlet (I)

Handout 31 Web Design & Development

Generating the Server Response: HTTP Status Codes

Introduction. This course Software Architecture with Java will discuss the following topics:

CE212 Web Application Programming Part 3

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

COMP9321 Web Application Engineering

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

COMP9321 Web Application Engineering

Backend. (Very) Simple server examples

CS433 Technology Overview

CH -7 RESPONSE HEADERS

HTTP and the Dynamic Web

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

UNIT-VI. HttpServletResponse It extends the ServletResponse interface to provide HTTP-specific functionality in sending a response.

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Get the cookies from the service request: Cookie[] HttpServletRequest.getCookies() Add a cookie to the service response:

Servlets. How to use Apache FOP in a Servlet $Revision: $ Table of contents

Lecture Notes On J2EE

1Z Java EE 6 Web Component Developer Certified Expert Exam Summary Syllabus Questions

Tutorial: Developing a Simple Hello World Portlet

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Advanced Internet Technology Lab # 5 Handling Client Requests

Introduction to Server-Side Technologies

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Module 4: SERVLET and JSP

WHITE LABELING IN PROGRESS ROLLBASE PRIVATE CLOUD

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Java Server Pages JSP

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

Session 10. Form Dataset. Lecture Objectives

First Servlets. Chapter. Topics in This Chapter

Transcription:

Programming Web Applications with Servlets Klaus Ostermann, Uni Marburg Based on slides by Anders Møller & Michael I. Schwartzbach

Objectives How to program Web applications using servlets Advanced concepts, such as listeners, filters, and request dispatchers Running servlets using the Tomcat server 2

Web Applications Web servers return files run programs Web application: collection of servlets, JSP pages, HTML pages, GIF files,... Servlets: programmed using the servlet API, which is directly based on HTTP Notion of lifecycle, possibility to react to lifecycle events Different forms of state application (shared state) session (session state) interaction (transient state) 3

An Example Servlet 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>servletexample</title></head>"+ "<body><h1>hello World!</h1>"+ "This page was last updated: "+ new java.util.date()+ "</body></html>"); 4

Requests Methods in HttpServletRequest getheader getparameter getinputstream getremotehost, getremoteaddr, getremoteport... 5

Example: HttpServletRequest (1/2) public class Requests 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>requests</title></head><body>"); out.println("<h1>hello, visitor from "+request.getremotehost()+"</h1>"); String useragent = request.getheader("user-agent"); if (useragent!=null) out.println("you seem to be using "+useragent+"<p>"); String name = request.getparameter("name"); if (name==null) out.println("no <tt>name</tt> field was given!"); else out.println("the value of the <tt>name</tt> field is: <tt>" + htmlescape(name) + "</tt>"); out.println("</body></html>"); 6

Example: HttpServletRequest (2/2) public void dopost(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException { doget(request, response); private String htmlescape(string s) { StringBuffer b = new StringBuffer(); for (int i = 0; i<s.length(); i++) { char c = s.charat(i); switch (c) { case '<': b.append("<"); break; case '>': b.append(">"); break; case '"': b.append("""); break; case '\'': b.append("&apos;"); break; case '&': b.append("&"); break; default: b.append(c); return b.tostring(); 7

Responses Methods in HttpServletResponse setstatus addheader, setheader getoutputstream, getwriter setcontenttype senderror, sendredirect... 8

Example: BusinessCardServlet public class BusinessCardServlet extends HttpServlet { public void doget(httpservletrequest request,... HttpServletResponse response) throws IOException, ServletException { response.setcontenttype("text/xml;charset=utf-8"); long expires = new Date().getTime() + 1000*60*60*24; response.adddateheader("expires", expires); XMLOutputter outputter = new XMLOutputter(); outputter.output(getbusinesscard(), response.getoutputstream()); using JDOM to generate an XML document with a reference to an XSLT stylesheet 9

Servlet Contexts One ServletContext object for each Web application getserverinfo getinitparameter... Shared state: setattribute( name, value) getattribute( name ) don t use for mission critical data! 10

Example: A Polling Service A Web application consisting of QuickPollQuestion.html QuickPollSetup.java QuickPollAsk.java QuickPollVote.java QuickPollResults.java 11

Example: QuickPollQuestion.html <html> <head><title>quickpoll</title></head> <body> <h1>quickpoll</h1> <form method=post action=setup> What is your question?<br> <input name=question type=text size=40>?<br> <input type=submit name=submit </form> </body> </html> value="register my question"> 12

Example: QuickPollSetup.java public class QuickPollSetup extends HttpServlet { public void dopost(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException { String q = request.getparameter("question"); ServletContext c = getservletcontext(); c.setattribute("question", q); c.setattribute("yes", new Integer(0)); c.setattribute("no", new Integer(0)); response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.print("<html><head><title>quickpoll</title></head><body>"+ "<h1>quickpoll</h1>"+ "Your question has been registered. "+ "Let the vote begin!"+ "</body></html>"); 13

Example: QuickPollAsk.java public class QuickPollAsk extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.print("<html><head><title>quickpoll</title></head><body>"+ String question = "<h1>quickpoll</h1>"+ "<form method=post action=vote>"); (String)getServletContext().getAttribute("question"); out.print(question+"?<p>"); out.print("<input name=vote type=radio value=yes> yes<br>"+ "<input name=vote type=radio value=no> no<p>"+ "<input type=submit name=submit value=vote>"+ "</form>"+ "</body></html>"); 14

Example: QuickPollVote.java (1/2) public class QuickPollVote extends HttpServlet { public void dopost(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException { String vote = request.getparameter("vote"); ServletContext c = getservletcontext(); if (vote.equals("yes")) { int yes = ((Integer)c.getAttribute("yes")).intValue(); yes++; c.setattribute("yes", new Integer(yes)); else if (vote.equals("no")) { int no = ((Integer)c.getAttribute("no")).intValue(); no++; c.setattribute("no", new Integer(no)); 15

Example: QuickPollVote.java (2/2) response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.print("<html><head><title>quickpoll</title></head><body>"+ "<h1>quickpoll</h1>"+ "Thank you for your vote!"+ "</body></html>"); 16

Example: QuickPollResult.java (1/2) public class QuickPollResults extends HttpServlet { public void doget(httpservletrequest request, HttpServletResponse response) throws IOException, ServletException { ServletContext c = getservletcontext(); String question = (String)c.getAttribute("question"); int yes = ((Integer)c.getAttribute("yes")).intValue(); int no = ((Integer)c.getAttribute("no")).intValue(); int total = yes+no; response.setcontenttype("text/html"); response.setdateheader("expires", 0); response.setheader("cache-control", "no-store, no-cache, must-revalidate"); response.setheader("pragma", "no-cache"); PrintWriter out = response.getwriter(); 17

Example: QuickPollResult.java (2/2) out.print("<html><head><title>quickpoll</title></head><body>"+ "<h1>quickpoll</h1>"); if (total==0) out.print("no votes yet..."); else { out.print(question + "?<p>"+"<table border=0>"+ "<tr><td>yes:<td>"+drawbar(300*yes/total)+"<td>"+yes+ "<tr><td>no:<td>"+drawbar(300*no/total)+"<td>"+no+ "</table>"); out.print("</body></html>"); String drawbar(int length) { return "<table><tr><td bgcolor=black height=20 width="+ length+"></table>"; 18

Problems in QuickPoll Need access control to QuickPollSetup No escaping of special characters Need to check right order of execution Need to check that expected form field data is present No synchronization in QuickPollVote Should store state in database Redundancy in HTML generation 19

Example: Shopping Cart 20

Sessions One HttpSession object for each session obtained by getsession in the HttpServletRequest object Session state: setattribute( name, value) getattribute( name ) Hides the technical details of tracking users with URL rewriting / cookies / SSL sessions 21

Web Applications A Web app is structured as a directory: myapp/ contains HTML/CSS/GIF/... files myapp/web-inf/ contains the deployment descriptor web.xml myapp/web-inf/classes/ contains servlet class files (in subdirs corresponding to package names) myapp/web-inf/lib/ contains extra jar files 22

Deployment Descriptors An XML file web.xml describing mapping from URIs to application resources initialization parameters security constraints registration of listeners and filters Mapping from HTTP error codes to resources 23

Example web.xml <web-app xmlns="http://java.sun.com/xml/ns/j2ee version="2.4"> <display-name>a Small Web Application</displayname> <servlet> <servlet-name>myfirstservlet</servlet-name> <servlet-class>helloworld</servlet-class> </servlet> <servlet-mapping> <servlet-name>myfirstservlet</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping> </web-app> 24

The Tomcat Server Reference Implementation, Open Source common/lib/servlet-api.jar bin/startup.sh, bin/shutdown.sh conf/server.xml webapps/myapp 25

Advanced Features Listeners Filters and wrappers Request dispatchers Security 26

Listeners also called observers or event handlers ServletContextListener Web application initialized / shut down ServletRequestListener request handler starting / finishing HttpSessionListener session created / invalidated ServletContextAttributeListener context attribute added / removed / replaced HttpSessionAttributeListener session attribute added / removed / replaced 27

Example: SessionMonitor (1/2) import javax.servlet.*; import javax.servlet.http.*; public class SessionMonitor implements HttpSessionListener, ServletContextListener { private int active = 0, max = 0; public void contextinitialized(servletcontextevent sce) { store(sce.getservletcontext()); public void contextdestroyed(servletcontextevent sce) { public void sessioncreated(httpsessionevent se) { active++; if (active>max) max = active; store(se.getsession().getservletcontext()); 28

Example: SessionMonitor (2/2) public void sessiondestroyed(httpsessionevent se) { active--; store(se.getsession().getservletcontext()); private void store(servletcontext c) { c.setattribute("sessions_active", new Integer(active)); c.setattribute("sessions_max", new Integer(max)); Registration in web.xml: <listener> <listener-class>sessionmonitor</listener-class> <listener> 29

Filters Code being executed before and after the servlet executed in stack-like fashion with servlet at the bottom Can intercept and redirect processing security auditing Can modify requests and responses data conversion (XSLT, gzip,...) specialized caching all without changing the existing servlet code! 30

Example: LoggingFilter (1/2) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LoggingFilter implements Filter { ServletContext context; int counter; public void init(filterconfig c) throws ServletException { context = c.getservletcontext(); public void destroy() { 31

Example: LoggingFilter (2/2) public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String uri = ((HttpServletRequest)request).getRequestURI(); int n = ++counter; context.log("starting processing request #"+n+" ("+uri+")"); long t1 = System.currentTimeMillis(); chain.dofilter(request, response); long t2 = System.currentTimeMillis(); context.log("done processing request #"+n+", "+(t2-t1)+" ms"); 32

Registration of Filters in web.xml <web-app...>... <filter> <filter-name>my Logging Filter</filter-name> <filter-class>loggingfilter</filter-class> </filter> <filter-mapping> <filter-name>my Logging Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>... </web-app> 33

Wrappers Used by filters to modify requests and responses HttpServletRequestWrapper HttpServletResponseWrapper Example: performing server-side XSLT transformation for older browsers 34

Example: XSLTFilter (1/5) import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.jdom.*; import org.jdom.transform.*; import org.jdom.input.*; import org.jdom.output.*; public class XSLTFilter implements Filter { ServletContext context; public void init(filterconfig c) throws ServletException { context = c.getservletcontext(); public void destroy() { 35

Example: XSLTFilter (2/5) public void dofilter(servletrequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest)request; HttpServletResponse hresp = (HttpServletResponse)response; boolean client_capable = checkxsltsupport(hreq.getheader("user-agent")); ServletResponse res; if (client_capable) res = response; else res = new BufferingResponseWrapper(hresp); chain.dofilter(request, res); 36

Example: XSLTFilter (3/5) if (!client_capable) { try { hresp.setcontenttype("application/xhtml+xml"); transform(((bufferingresponsewrapper)res).getreader(), response.getwriter()); catch (Throwable e) { context.log("xslt transformation error", e); hresp.senderror(500, "XSLT transformation error"); boolean checkxsltsupport(string user_agent) { if (user_agent==null) return false; return user_agent.indexof("msie 5.5")!=-1 user_agent.indexof("msie 6")!=-1 user_agent.indexof("gecko")!=-1; 37

Example: XSLTFilter (4/5) void transform(reader in, Writer out) throws JDOMException, IOException { System.setProperty("javax.xml.transform.TransformerFactory", SAXBuilder b = new SAXBuilder(); Document d = b.build(in); "net.sf.saxon.transformerfactoryimpl"); List pi = d.getcontent(new org.jdom.filter.contentfilter (org.jdom.filter.contentfilter.pi)); String xsl = ((ProcessingInstruction)(pi.get(0))).getPseudoAttributeValue("href"); XSLTransformer t = new XSLTransformer(xsl); Document h = t.transform(d); (new XMLOutputter()).output(h, out); 38

Example: XSLTFilter (5/5) class BufferingResponseWrapper extends HttpServletResponseWrapper { CharArrayWriter buffer; PrintWriter writer; public BufferingResponseWrapper(HttpServletResponse res) { super(res); buffer = new CharArrayWriter(); writer = new PrintWriter(buffer); public PrintWriter getwriter() { return writer; Reader getreader() { return new CharArrayReader(buffer.toCharArray()); 39

Request Dispatchers Forwarding requests to other resources RequestDispatcher disp = context.getrequestdispatcher ( /shop/buy ); disp.forward(req,resp); Often used with JSP... Alternative: sendredirect method Advantage: no client involvement Disadvantage: Can only redirect on the same server 40

Security Roles and Authentication <web-app...>... <security-role> <role-name>administrator</role-name> <role-name>teacher</role-name> <role-name>student</role-name> </security-role> <login-config> <auth-method>basic</auth-method> <realm-name>administration</realm-name> </login-config>... </web-app> 41

Security Constraints... <security-constraint> <web-resource-collection> <web-resource-name>restricted Area</web-resource-name> <url-pattern>/restricted/*</url-pattern> <http-method>get</http-method> <http-method>post</http-method> </web-resource-collection> <auth-constraint> <role-name>administrator</role-name> <role-name>teacher</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>confidential</transport-guarantee> </user-data-constraint> </security-constraint>... 42

Programmatic Security Useful request methods: getremoteuser() isuserinrole(string role) issecure() getauthtype() getattribute( javax.servlet.request.x509certificate ) 43

Summary (1/2) Servlets closely follow the request-response pattern from HTTP Features: Multi-threading Declarative configuration Request parsing, including decoding of form data Shared state Session management Advanced code structuring: listeners, filters, wrappers Client authentication, SSL 44

Summary (2/2) Limitations of Servlets Dynamic construction of HTML low-level No compile-time guarantees that the result is well-formed or valid Possibility of CSS attacks Redundancy in HTML code Difficult to separate HTML code and business logic Control flow through a session can be difficult to understand Logical flow of a session is severly distorted Untyped getattribute/setattribute is another source of errors 45

Essential Online Resources The servlet API: http://jakarta.apache.org/tomcat/ tomcat-5.5-doc/servletapi/ Sun's home page for servlets: http://java.sun.com/products/servlet/ The Tomcat server: http://jakarta.apache.org/tomcat/ 46