Java Servlets & Java Server Pages

Slides:



Advertisements
Similar presentations
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Advertisements

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:
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
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 Servlets & Java Server Pages Brad Rippe Fullerton College.
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.
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
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.
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)
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.
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.
Java Server Pages (JSP)
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.
JSP. Types of JSP Scripting Elements Expressions of the form, which are evaluated and inserted into the servlet's output. Scriptlets of the form, which.
Web Technologies Java Beans & JSP By Praveen Kumar G.
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.
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.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
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)
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Chapter 4 Request and Response. Servlets are controlled by the container.
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.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
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..
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Java Servlets.
Scripted Page Web App Development (Java Server Pages)
Pre-assessment Questions
MSIS 655 Advanced Business Applications Programming
Chapter 26 Servlets.
Jagdish Gangolly State University of New York at Albany
Java Server Pages B.Ramamurthy.
Java Servlets and JSP.
CS3220 Web and Internet Programming Introduction to Java Servlets
Introduction to Java Servlets
Directories and DDs 25-Apr-19.
Introduction to JSP Dept. of B.Voc Software Development and System Administration St. Joseph’s College(Autonomous) Trichy-02 By Dr. J. Ronald Martin Introduction.
Scripted Page Web Application Development (Java Server Pages)
Directories and DDs 21-Jul-19.
Directories and DDs 14-Sep-19.
Java Chapter 7 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Servlets & Java Server Pages

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 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.

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

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 Tomcat @ Jakarta BEA’s WebLogic ATG Dynamo Allaire/MacroMedia’s JRun IONA iPortal Sun’s Java Web Server * available with the J2EE SDK

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 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 <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> <web-app> <servlet> <servlet-name>resourceExample</servlet-name> <servlet-class>ResourceExampleServlet</servlet-class> <init-param> <param-name>dbUser</param-name> <param-value>testUser</param-value> </init-param> [ Repeat above for each parameter – init-param ] </servlet> </web-app>

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("<html>"); out.println("<head><title>Resource Example Servlet</title></head>"); out.println("<body>"); out.println("<H3>Resource Example Servlet</H3>"); out.println("<p>I could really do some damage if I only knew how to use those" + " JDBC libraries!<br>I mean I have:<br>" ); out.println("<ul>"); out.println("<li>User: " + dbUser ); out.println("<li>URL: " + dbUrl ); out.println("<li>Driver: " + driver ); out.println("</ul>"); out.println("<p>" + exampleMsg + "</p>"); out.println("</body>"); out.println("</html>");

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 Response with a Token Client Server Request with a Token

Servlet Sessions URL Write – Facilitated through methods in the response interface http://bradsmachine.com?jsessionid=00988988 Hidden fields - <input type=“hidden” name=“jsessionid” value=“00988988”> 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 );

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) 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 <HTML> 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 index.jsp Servlet/JSP Server Browser Generated checks Browser converts Forwards to index.java Generated Servlet compiles

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. <%! … %> Allows you to declare page wide variables and methods. <%! int counter = 0; %> <%! Vector beanList = new Vector(); %> 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. <%= counter %> <%= uBean.getUserName() %> Short hand for: <% out.println( uBean.getUserName() ); %>

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 <%@ directive … %>

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. <%@ page include file=“relativeURL” %> <%@ page include=“/navbar.html”%>

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 <jsp:useBean> <jsp:setProperty> <jsp:getProperty> <jsp:include> <jsp:forward> <jsp:plugin> <jsp:param>

Standard Actions <jsp:useBean> Associates an instance of a bean to a variable to use with in the jsp page <jsp:useBean id=“name” scope=“page|request|session|application” class=“className” type=“typeName”> … </jsp:useBean>

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 <jsp:setProperty> Sets the value of properties in a bean <jsp:setProperty name=“beanName” property=“propertyName”|(param=“parametername”|value=“propertyValue”)/> 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 <jsp:getProperty name=“beanName” property=“propertyName”/> Name Variable name as defined in useBean Property Name of the bean property to retrieve

Bean Example <html> <title>Random JSP Test</title> <body bgcolor=“white”> <jsp:useBean id=“rnd” scope=“page” class=“random.NumberGenerator”/> <ul> <li>Next number is: <jsp:getProperty name=“rnd” property=“nextInt”/> </ul> </body> </html>

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 <jsp:include page=“url” flush=“true”/> page: Relative url flush: If true, buffer is flushed

Standard Actions – jsp:forward Allows you to dispatch the request to a different page <jsp:forward page=“url”/> page: Relative url

Standard Actions - <jsp:plugin> Creates HTML that contains OBJECT or EMBED constructs that result in Java Plugin download and execution of Applet <jsp:plugin type=“applet” code=“applet.class” codebase=“/html”> <jsp:fallback> <p>Can’t display applet</p> </jsp:fallback> </jsp:plugin> Fallback is used if the plugin cannot be started

Standard Actions - jsp:param Used to provide key/value information for <jsp:include>, <jsp:forward>, and <jsp:plugin> <jsp:param name=“name” value=“value”/> 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 browser JSP Database BEAN

Model 1 Suitable for simple applications Easier to understand May lead to lots of Java code embedded within JSP pages for complex

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

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