Java Servlets & Java Server Pages Brad Rippe Fullerton College.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
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.
Java Servlets and JSP.
Chapter 10 Servlets and Java Server Pages. A servlet is a Java class designed to be run in the context of a special servlet container An instance of the.
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.
Java Enterprise Edition Java Web Development Structure of a web project Introduction to Web Applications The first project Introduction to Java Web Development.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Java Server Pages Lecture July Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java)
JSP Most of the web developers deploying web applications using servlets mixes the presentation logic and business logic. Separation of business logic.
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.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
Java Servlets & Java Server Pages Lecture July 2013.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
A seminar on j2ee by saritha. s. What is J2EE J2EE (Java 2 Platform, Enterprise Edition) is a Java platform designed for the mainframe-scale computing.
@2008 Huynh Ngoc Tin Chapter #2 JAVA SERVLET PRGRAMMING.
Java Servlets and Java Server Pages Norman White Stern School of Business.
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.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
Servlets.
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.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
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.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Java Servlets Java Server Pages (JSP)
Java Servlets and Java Server Pages
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
 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,
JSP JavaServer Pages. What is JSP? Java based technology that simplifies the development of dynamic web sites JSP pages are HTML pages with embedded code.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 4 Request and Response. Servlets are controlled by the container.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
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.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
Speaker Name Speaker Title Speaker Title Oracle Corporation Olivier Le Diouris Principal Product Manager Oracle Corporation Building Servlet and JSP Applications.
Java Servlets References: Karen Anewalt, Mary Washington College.
Introduction to Servlets
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Java Server Pages By: Tejashri Udavant..
MSIS 655 Advanced Business Applications Programming
Chapter 26 Servlets.
Java Servlets & Java Server Pages
CS3220 Web and Internet Programming Introduction to Java Servlets
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Servlets & Java Server Pages Brad Rippe Fullerton College

What is a Servlet? A servlet is a java class that extends an application hosted on a web server. Handles the HTTP request-response process (for our purposes) Often thought of as an applet that runs on a server. Provides a component base architecture for web development, using the Java Platform The foundation for Java Server Pages (JSP). Alternative to CGI scripting and platform specific server side applications.

Common Uses Processing and/or storing data submitted by an HTML form. Providing dynamic content, e.g. returning the results of a database query to the client. Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

Architectural Roles Servlets provide the middle tier in a three or multi-tier system. Servlets provide logic and/or traffic control for requests/response to the server. Servlets allow web developers to remove code from the client and place the logic on the server.

Architectural Roles Connection management Business rule enforcement Transaction management Mapping clients to a redundant set of servers Supporting different types of clients such as pure HTML, WML clients, other Java based clients

What is required? Servlets are not run in the same sense as applets and applications. Since they extend a web server, they require a servlet container to function. A servlet container is a part of a web server or application server that provides the network services over which request and response are sent. Contains and manages the servlets through there lifecycle. The container provides other services as well.

J2EE Container Web Container/Servlet engine Browser Servlets Web Server Deployment Descriptor Java Classes web.xml Deployment Descriptor is used to configure web applications that are hosted in the App Server.

Web Application Directory Structure Application Root (htdocs/wwwroot) WEB-INF/web.xml WEB-INF/classes Compiled servlet classes and other utility classes WEB-INF/lib Any required third party jars All J2EE compliant App Servers require this directory structure

Common Containers Are Provided by the App Server Apache’s Jakarta BEA’s WebLogic ATG Dynamo Allaire/MacroMedia’s JRun IONA iPortal Sun’s Java Web Server * available with the J2EE SDK ex.html ex.html

Overview of the Servlet API All servlets implement the Servlet interface. The API provides two classes that implement this interface, GenericServlet and HttpServlet Servlet API is specified in two packages, javax.servlet and javax.servlet.http

Servlet Interface This is a contract between the servlet and the web container. Guarantees that all containers can communicate with a servlet. public void init(ServletConfig) public void service(request, response) public void destroy() public ServletConfig getServletConfig() public String getServletInfo()

HttpServlet Abstract class that extends GenericServlet Provides additional methods that are called by the service() method automatically. Both methods throw ServletException and IOException Methods of most concern: protected void doGet(HttpServletRequest, HttpServletResponse) protected void doPost(HttpServletRequest, HttpServletResponse)

Servlet Life Cycle Instantiation – web container creates an instance. Initialization – container calls the instance’s init(). Service – if container has request, then it calls the service() method Destroy – before reclaiming the memory (destroying the servlet), the container calls the destroy() method. Unavailable – instance is destroyed and marked for GC.

ResourceExampleServlet How do we get it to work? Using Tomcat Created the appropriate web directory structure In “Web-Apps” directory add the following: cis228/ cis228/WEB-INF cis228/WEB-INF/classes cis223/WEB-INF/lib Create Servlet (ResourceExampleServlet) which extends HttpServlet and saved in the classes directory Create web.xml and save it in the WEB-INF directory

Configuration - web.xml resourceExample ResourceExampleServlet dbUser testUser [ Repeat above for each parameter – init-param ]

ResourceExampleServlet Define the following methods: init() – initialize all member variables – safe? doGet(HttpServletRequest, HttpServletResponse) Note: You should define the doPost() method as well, even if it just calls doGet() destroy()

What about the Code? – init() public void init() throws ServletException { dbUser = getServletConfig().getInitParameter( "dbUser" ); driver = getServletConfig().getInitParameter( "driver" ); dbUrl = getServletConfig().getInitParameter( "dbUrl" ); exampleMsg = getServletConfig().getInitParameter( "exampleMsg" ); }

What about the code? – doGet() response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" "); out.println(" Resource Example Servlet "); out.println(" "); out.println(" Resource Example Servlet "); out.println(" I could really do some damage if I only knew how to use those" + " JDBC libraries! I mean I have: " ); out.println(" "); out.println(" User: " + dbUser ); out.println(" URL: " + dbUrl ); out.println(" Driver: " + driver ); out.println(" "); out.println(" " + exampleMsg + " "); out.println(" ");

What about the code? – destroy() public void destroy() { dbUser = null; driver = null; dbUrl = null; }

HttpServletRequest & HttpServletResponse Interfaces used for accessing request parameters and constructing client responses. The web container has concrete objects which implement these interfaces and passes into the servlet.

Servlet Sessions Since http protocol is stateless, Java API provides the following techniques for session tracking: URL rewriting Cookies Hidden form fields ClientServer Response with a Token Request with a Token

Servlet Sessions URL Write – Facilitated through methods in the response interface Hidden fields - Cookies Cookie c = new Cookie(“uid”, “brad”); c.setMaxAge(60); c.setDomain(“bradsmachine”); c.setPath(“/”); response.addCookie(c); Servlet API requires that web containers implement session tracking using cookies.

HttpSession Web containers provide an implementation of this interface to provide session tracking. Session objects can be retrieved from the HttpRequest object also provided by the container. HttpSession session = request.getSession(); If a session object does not exist for the client, one will be created. The duration of this session object can be configured in the web.xml file or in a servlet, setMaxInactiveInterval( int interval );

Session Example Servlet

Servlet Context Servlet API provides an interface for storing information that is relevant to all servlets being hosted in a web application. Common for facilities like application logging, access to other resources (Database Connection Pools), and request dispatching. There is one context per web application per JVM. Parameter information is configured in the web.xml file in name/value pairs.

Proposed Architecture of Web Applications Presentation Layer (JSP, HTML, WML) Logic Layer (Servlets, JavaBeans, EJBS, etc) Logic Layer (Servlets, JavaBeans, EJBS, etc) Data Store Layer (MySQL, SQL Server, File System) Data Store Layer (MySQL, SQL Server, File System)

Highly Coupled Servlets High cost of maintenance HTML and Java exist in the same file. Web Designers don’t understand java code, don’t like the java code… Programmers don’t particularly like the messing with code!!!! Better to separate JAVA code from the HTML code. if( developer == javaProgrammer) System.out.println(“Stick to Java code!”); else if( developer == webDesigner ) System.out.println(“Stick to html code!”);

Java Server Pages Java Server Pages (JSPs) provide a way to separate the generation of dynamic content (java) from its presentation (html) (???) JSP specification builds on the functionality provided by the servlet specification.

How do JSP’s Work Browser Servlet/JSP Server Generated Servlet index.jsp index.java compiles checks converts Forwards to

Basic JSP Syntax Contains html code like static html pages with the JSP tags and scripting included in the page. Three basic types of jsp tags Scripting Elements Directive Elements Action Elements

Scripting Elements Allow java code – variable or method declarations, scriptlet, and expressions. Declaration tag Scriptlet tag Expression tag

Declaration Tag Allows you to declare page wide variables and methods. Methods and variables have class scope Note, code must end with ; like any java code

Scriptlet Tag Used to include small pieces of Java code <% for(Enumeration e = beanList.elements(); e.hasMoreElements(); ) { UserBean uBean = (UserBean) e.nextElement(); out.println( uBean.getUserName() ); } %>

Expression Tag Accepts any Java expression, evaluates the expression, converts to a String, and displays. Short hand for:

JSP Directives Directives provide global information to the JSP engine For example, a directive can be used to import java classes. Directive elements have a syntax of the form

Page Directives The page directive defines a number of page dependent attributes page language=“Java” [ extends=“className” ] [ import=“importList” ] [ session= “true|false” ] [ buffer=“none|sizekb” ] [ autoFlush=“true|false” ] [ isThreadSafe=“true|false” ] … %>

Page Directive If language attribute is set, must be = “Java” Default import list is java.lang.*, javax.servlet.*, javax.servlet.jsp.* and javax.servlet.http.*. If session = “true” then default session variable of type javax.servlet.http.HttpSession references the current/new session for the page.

Include Directive The include directive is used to inline text and/or code at JSP page translation-time.

JSP Actions The syntax for action elements is based on XML(i.e. they have a start tag, a body, and an end tag). The JSP specification includes some action types that are standard. New action types are added using the taglib directive.

Standard Actions Web container implements these actions

Standard Actions Associates an instance of a bean to a variable to use with in the jsp page …

Standard Actions - useBean id – variable name to reference instance of class scope page – javax.servlet.jsp.PageContext Objects only accessible from within the page request ServletRequest Objects accessible in pages processing request where bean is created session – HttpSession Objects accessible from user session application – ServletContext Objects accessible in pages belonging to same application

Standard Actions - useBean Type (optional) Allows scripting variable to be cast to another type from implementation class, java casting rules apply. Class Fully qualified class name that defines the implementation of the object

Standard Actions - setProperty Sets the value of properties in a bean Use property=“*” to set all properties from the request

Standard Actions - setProperty Name Variable name as defined in useBean Property Name of the bean property Request Name of the request parameter (if omitted same name as bean property name) Value Value assign property (Performs necessary conversions)

Standard Actions - getProperty Gets the value of properties in a bean Name Variable name as defined in useBean Property Name of the bean property to retrieve

Bean Example Random JSP Test Next number is:

Bean Example package random; import java.util.*; public class NumberGenerator { Random rnd = new Random(); public int getNextInt() { return rnd.nextInt(); }

Standard Actions – jsp:include Allows you to include resources in the same context as the current page page: Relative url flush: If true, buffer is flushed

Standard Actions – jsp:forward Allows you to dispatch the request to a different page page: Relative url

Standard Actions - Creates HTML that contains OBJECT or EMBED constructs that result in Java Plugin download and execution of Applet Can’t display applet Fallback is used if the plugin cannot be started

Standard Actions - jsp:param Used to provide key/value information for,, and Name and value are mandatory

Access Models Two approaches to building application with JSPs Model 1: JSP page processes all input Model 2: Servlet acts as a controller and directs http traffic to appropriate responses

Model 1 JSP is responsible for processing incoming requests and replying to clients All data access is through beans browserJSP BEAN Database

Model 1 Suitable for simple applications Easier to understand May lead to lots of Java code embedded within JSP pages for complex applications (I’ve never used this model???)

Model 2 Combine use of servlets and JSP Servlet acts as controller, JSP as presentation layer browser servlet JSP Beans Database

It’s a rap! JSP aren’t total separation of logic from the presentation. Although it’s a good start. Look into Custom tags to encapsulate your application logic and move it outside of the jsps. Creation of your own custom tag libraries help to eliminate java code from being embedded in the jsp. Frameworks like WebMacro, Struts, and Velocity provide additional features to

Resources Tomcath Struts Apache J2EE Web Site Servlet 2.3 Spec JSP 1.2 Spec Free Development space for jsps/servlets Lecture available at

Resources J2EE Developer’s Guide – ocs/guides/ejb/html/DevGuideTOC.html ocs/guides/ejb/html/DevGuideTOC.html J2EE Tutorial – fcs/index.html fcs/index.html Server Side Programming –