1 Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh….) Representation and Management of Data on the Internet, 2007 CS Department, HUJI.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Servlets & JSPs - Sharad Ballepu.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
JSP and Servelets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
M-V-C for web applications. Model for Web Applications model consists of data and system state database tables –persistent data session information –current.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
JLab Lattice Portal – Data Grid Web Service Ying Chen, Chip Watson Thomas Jefferson National Accelerator Facility.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Apache Tomcat as a container for Servlets and JSP
Java Server Pages (JSP)
Apache Struts Technology
Java Servlets Java Server Pages (JSP)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
An introduction to Java Servlet Programming
1 Servlet/JSP Miscellaneous Representation and Management of Data on the Web.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
1 Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh….)
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Lecture 2 - Struts ENTERPRISE JAVA. 2 Contents  Servlet Deployment  Servlet Filters  Model View Controllers  Struts  Dependency Injection.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 8 Servlets (Based on Møller and Schwartzbach,
AN OVERVIEW OF SERVLET TECHNOLOGY SERVER SETUP AND CONFIGURATION WEB APPLICATION STRUCTURE BASIC SERVLET EXAMPLE Java Servlets - Compiled By Nitin Pai.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
JSP Filters 23-Oct-15. JSP - FILTERS A filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually.
Chapter 6 Server-side Programming: Java Servlets
1 Uploading Files with Servlets Read more about the FileUpload APIFileUpload API.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Servlet Filters import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TimerFilter implements Filter { /* J2EE v1.3 Filter.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
1 Web Programming with Servlets & JSP ASSIGNMENT GUIDELINE.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
 Java Server Pages (JSP) By Offir Golan. What is JSP?  A technology that allows for the creation of dynamically generated web pages based on HTML, XML,
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
Servlets.
Java Servlets.
Pre assessment Questions
Chapter 6 Server-side Programming: Java Servlets
Pre-assessment Questions
Sessions.
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
COP 4610L: Applications in the Enterprise Spring 2005
Presentation transcript:

1 Servlets: Leftover Odds and Ends (Most apply to JSPs as well, duh….) Representation and Management of Data on the Internet, 2007 CS Department, HUJI

2 A Warning: Don’t Panic… Many of the examples in this presentation are using various features not discussed throughout this course. There is not need to understand them in a deeper extent than the understanding of the relevant examples. They are there to give you a general idea of what these feature names refer to and what can be done with them. Google these features if you want / ever need to...

3 Exceptions Exceptions are caught by the server You can find them in the log file under $CATALINA_BASE/logs/ The result shown in the browser depends on the buffer state Check the example on the next slide… Find the exceptions in the log

4 Run : public class ExceptionServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); int nLines = Integer.parseInt(request.getParameter("nlines")); out.println(" "); for (int i = 0; i bla bla bla " + i + " "); } out.println(" "); out.println(" " + 1/0 + " "); }} This line causes an exception

5 Uploading Files with Servlets Read more about the FileUpload APIFileUpload API

6 Handling Uploads with Package Commons FileUpload Commons FileUpload is a package of Apache for handling uploaded files in the Servlet side Files are sent in the body of post requests Using this package, uploaded files are temporarily written into the memory or the disk (depending on the file size) You can set the size threshold beyond which files are written to disk This is not a configuration parameter in web.xml but a part of the API as we’ll see in the next slides

7 Handling Uploads with Package Commons FileUpload Servlets read the file from the disk or memory In Tomcat, the default temporary directory is $CATALINA_BASE/temp/ However, you can specify a temporary directory of your own (e.g., /tmp ) What if a very big file is uploaded? -You can define the maximal size of uploaded files -Exception is thrown for larger files

8 Example 1 Upload Files and Parameters <form action="upload1" method="post" enctype="multipart/form-data"> File: upload1.html Sends the client the uploaded file This is the right encoding type for files uploading

9 import org.apache.commons.fileupload.disk.*; import org.apache.commons.fileupload.servlet.*; import org.apache.commons.fileupload.*; public class Upload1 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); //factory.setRepository(new File("/tmp")); factory.setSizeThreshold(1000); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(60000); Upload1.java Sets the repository directory Sets the memory vs. disk threshold (bytes) Sets the maximum file size (bytes). Bigger files generate exceptions

10 try { List items = upload.parseRequest(request); Iterator it = items.iterator(); FileItem item = (FileItem) it.next(); response.setContentType(item.getContentType()); response.setContentLength((int)item.getSize()); InputStream is = item.getInputStream(); OutputStream os = response.getOutputStream(); byte[] buffer = new byte[4096]; int read = -1; while((read=is.read(buffer))>=0) os.write(buffer,0,read); } catch (FileUploadException exp) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" Error : " + exp.getMessage() + " "); }}} Upload1.java In our example, we expect a single parameter We use an Output stream and not the out PrintWriter (why?) Makes life much easier

11 Example 2 Upload Files and Parameters <form action="upload2" method="post" enctype="multipart/form-data"> Parameter x: File: Parameter y: upload2.html Mixed parameter types

12 List items = upload.parseRequest(request); Iterator it = items.iterator(); out.println(" "); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField()) out.println(" Field : " + item.getFieldName() + " = " + item.getString() + " "); else out.println(" File " + ": parameter name: " + item.getFieldName() + ", file name: " + item.getName() + ", file size: " + item.getSize() + " bytes, file type: " + item.getContentType() + " "); } out.println(" "); Upload2.java This time we use a loop since there are several parameters

13 Example 3 The latter example reflected a common design problem: combining complex HTML code and Java code in a Servlet or a JSP -Java code for processing parameters and uploaded files -HTML code for generating the (dynamic) response An accepted solution is to process the parameters in a Servlet, and forward the request to a JSP for generating the response -Attributes can be sent to the JSP via the request object. The next example also uses JSTL

14 JSTL JSTL stands for JSP Standard Tag Library This is a regular tag library that can be imported to your page, like the ones we created in the past This library includes some standard actions that are common in JSP, like iteration and conditions over EL expressions, parsing/manipulation of XML and database access More details can be found in Sun's J2EE Tut.Sun's J2EE Tut

15 Example 3 Upload Files and Parameters <form action="upload3" method="post" enctype="multipart/form-data"> Parameter x: File: Parameter y: upload3.html

16 List formParams = new LinkedList(); List files = new LinkedList(); List items = upload.parseRequest(request); Iterator it = items.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); if (item.isFormField())formParams.add(item); else files.add(item); } request.setAttribute("formParams",formParams); request.setAttribute("files",files); this.getServletContext().getRequestDispatcher ("/WEB-INF/jsp/upload3.jsp").forward(request,response); Upload3.java We’ll store parameters and fileitems in those lists Attach the lists to the request

17 Submitted Parameters Submitted Parameters: Parameter : name: ${item.fieldName}, value: ${item.string} File : name: ${item.name}, length: ${item.size}, size: type:${item.contentType} /WEB-INF/jsp/upload3.jsp

18 A Question What is the advantage of redirecting to JSP pages that are under WEB-INF? -Pages under the WEB-INF are not accessible -You can make sure no one invokes the JSP directly -You can hide the implementation

19 Programmatic Security with Servlets

20 Programmatic-Security Methods The Servlet API contains several accessories for handling programmatic security: - getRemoteUser() - isUserInRole(String role) - getAuthType() These are all methods of HttpServletRequest To enable user authentication (even for public URLs), provide a link to some protected page Returns the authenticated user or null if none exists

21 An Example: Security Constraints in web.xml Firm People /login.html employees managers web.xml Roles, some users and their roles are defined in /conf/tomcat-users.xml Some secured resources Roles that can view those resources

22 FORM /login /login?fail=fail managers employees web.xml An Example: Security Constraints in web.xml Roles used in this application (not required)

23 public class FirmServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Firm "); out.println(" Hello. "); String username = req.getRemoteUser(); if(username==null) { out.println(" "); out.println(" Login "); out.println(" "); return; } FirmServlet Returns the authenticated user or null if none exists

24 if(req.isUserInRole("employees")) { out.println(" "); out.print(" Welcome Employee " + username + "! "); } if(req.isUserInRole("managers")) { out.println(" "); out.print(" Executive average salary: 42764NIS! "); } out.print(" Log Out "); out.println(" "); } FirmServlet This is ugly. This is why attributes in HTML can be single- or double-quoted. Same goes for strings in many scripting languages (watch out for escaping differences, though!)

25 public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Login "); if(req.getParameter("fail")!=null) out.print(" Login Failed. Try Again. "); out.println(" " + " Login: " + " Password: " + " " + " "); } LoginServlet.java Notice that though this code contains no getSession() calls, the server tries to put session-cookie as a part of the FORM authorization

26 public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { this.doGet(req,res); } LoginServlet.java Login LoginServlet Login /login web.xml

27 public class EndSession extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(false); if(session!=null) { session.invalidate(); } res.sendRedirect("firm"); } EndSession.java EndSession EndSession /endsession web.xml Tomcat’s session implementation saves the user details in the session but not as attributes. Recovering this data is done by calling the mentioned request methods, but of course invalidating the session leads to logout

28 Logged On You are logged on! Back to the firm page. login.html

29 Managing User Authentication with Tomcat

30 A Reminder create table users ( username varchar(30) not null primary key, pass varchar(30) not null ); create table users_roles ( username varchar(30) not null, role varchar(30) not null, primary key (username,role), foreign key (username) references users(username) );

31 In tomcat-base/conf/server.xml <Realm className="org.apache.catalina.realm.JDBCRealm" driverName="org.postgresql.Driver" connectionURL= "jdbc:postgresql://dbserver/public?user=snoopy" userTable="users" userNameCol="username" userCredCol="pass" userRoleTable="users_roles" roleNameCol="role"/>

32 User Tables What if we do not have one table that stores usernames and passwords? What if we only have one role for the all users? What if we wanted the above information to be stored in several tables (e.g., users and administrators)? The idea is to use views rather than real tables

33 Creating Views create view up as (select username u, pass p from users union select u,p from admin); create view ur as (select username u, 'myRole' r from users union select u, 'admin' r from admin); Unifies the user/password data from 2 tables Default role for “simple” users Default role for “admin” users

34 Fixing server.xml <Realm className="org.apache.catalina.realm.JDBCRealm" driverName="org.postgresql.Driver" connectionURL= "jdbc:postgresql://dbserver/public?user=snoopy" userTable="up" userNameCol="u" userCredCol="p" userRoleTable="ur" roleNameCol="r"/>

35 Filters

36 Filters in Servlet API Filters are used to dynamically intercept requests and responses A filter that applies to a URL u typically acts as follows given a request for u -performs some actions before the processing of u -passes the request handling to the next filter -The last filter passes the request to u itself -performs some actions after the processing of u

37

38 public class FilterExample implements Filter { public void init(FilterConfig filterConfig) throws ServletException {... } public void destroy() {... } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {... chain.doFilter(request, response);... }} FilterExample.java Before other elements in way “down” After other elements in way “up”

39 Example Filter FilterExample Example Filter /images/* Registering a Filter web.xml You can also add an element like we saw in servlets and JSPs.

40 What Can we Do with Filters? Examine and log requests Modify request headers and properties Modify the response headers and response data Block requests And more... Open FilterExample.java.FilterExample.java Check the result of calling in the server’s logshttp://localhost/dbi/images/image1.gif

41 Notes About Filters The order of the filters in the chain is the same as the order that filter mappings appear web.xml The life cycle of filters is similar to that of Servlets Filters typically do not themselves create responses, although they can The request and response arguments of doFilter are actually of type HttpServletRequest and HttpServletResponse The FilterConfig interface is used to read initialization parameters -Those are set in web.xml

42 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse)response; HttpServletRequest req = (HttpServletRequest)request; String URI = req.getRequestURI(); if (URI.endsWith(filterConfig.getInitParameter("type")) && (req.getParameter("nofilter") == null)) { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" ImageFilter "); out.println(" Image filename = " + URI + " \n"); out.println(" "); out.println(" "); } ImageFilter.java URI is the part of the URL following the Only for filetypes with no “nofilter” parameter in the query We have to add the “nofilter” query so that the filter won’t work again on the

43 else {chain.doFilter(request, response); }} fImageFilter ImageFilter type.gif fImageFilter /images2/* Default filter chaining. This time next element in the chain is not a filter but the original URL web.xml The Filter applies only to.gif files in /dbi/images/ but not for other files on the same directory such as.txt Open /images2/image1.gif/images2/image1.gif Open /images2/joke1.txt/images2/joke1.txt A url-pattern of /images2/*.gif doesn’t work. That’s why we check the suffix in the Java code