Servlets And (JSP)

2y ago
22 Views
2 Downloads
776.09 KB
49 Pages
Last View : 6d ago
Last Download : 3m ago
Upload by : Emanuel Batten
Transcription

T A K EServletsandJava Server Pages (JSP)ITT OT H EN T H

T A K EITT OT H EN T HAndrew s/evangcentralSenior Software EngineerSun Microsystems

Agenda What are Servlets?What are JSPs?Design issuesResources and Summary

T A K EWhat are Servlets?ITT OT H EN T H

What Are Servlets?Servlets are Java’s answer to CGI/Perl.Server side Java program That respond to web server requests Used to generate dynamic HTML

Servlets vs. CGI Scalable, uses Lightweight threads: Doesn’t start new process for each request,Initialized once and persists in memory for multiplerequests, cached Multi-threadedRequest CGI1Request CGI2Request CGI1Request Servlet1Request Servlet2Request Servlet1Child for CGI1CGIBasedWebserverChild for CGI2Child for CGI1Servlet Based WebserverJVMServlet1Servlet2

Why Servlets? Superior alternative to CGI:– Multi-threaded, Cached, better security Easy to program, Simple APIs for inputarguments, cookies Written in Java– Can take advantage of JDBC, EJB,JMS, JavaMail, JavaIDL, RMI,APIs.

Servlet and JSP Run inWeb JBJNDIJavaMailRMIJDBCJTAApp ClientContainerServletJSPJNDIJ2SEEJB ContainerRMI/IIOPHTTP/HTTPSJMSAppletWeb ContainerJTAAppletContainer

Servlet APIsServlet letextendsHttpServletextendsHelloWorldServletYour Servlet

Servlet )Response

Servlet LifecycleCalled by the servletengine onceCalled by the servletengine to allow theinit()servlet to respond to arequest.service()- doGet()- doPost()destroy()Called when theservlet is removed.

Anatomy of a Request The servlet’s service() method isinvoked with a Request andResponse object The servlet provides a responseto the request

Request and ResponseParametersRequest : Encapsulates all information from the client HTTP request headers InputStream or reader Input parameters: Form data, cgi dataResponse: Encapsulates all communication back to theclient HTTP response headers OutputStream or writer Setting cookies, redirects, error pages

A Simple ServletSample Codepublic class ExampleServlet extends HttpServlet{public void sponseresponse)throws ServletException, �);PrintWriter out (“Hello! BR ”);}}

T A K EITWhat are Java Server Pages?T OT H EN T H

What is a Java Server Page?JSP turns servlets inside out– Presentation centric– Java code embedded in a HTMLpage– JSP is for formatting outputsuch as HTML and XML

HTML to Java Bean MappingJava BeanHTTPRequestsJSP PageHTTPResponseJava BeanJava BeanJSP (Developer View)Check if page needsto be recompiled.HTTPRequestsJSP PageWeb ServerCompile pageinto servletHTTPResponseLoad ifneededAnd runJSP servletView)JAVAServletJava BeanJava BeanJava Bean(Physical

Example Servletpublic class HelloServlet extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse intWriter out response.getWriter();out.println(" html ");out.println("Hello World!");out.println(" br ");JspCalendar clock new JspCalendar();out.println("Today is");out.println(" ul ");out.println(" li Day of month: (" /ul ");out.println(" /html ");}}

Example JSPJava Bean html Hello World! br jsp:useBean id "clock"class “calendar.JspCalendar” / Today is ul li Day of month: % clock.getDayOfMonth() % /ul /html JSP Page

Usage models of JSPsIntent from the original JSP specifications:– Model 1:JSP all the way! Browser calls JSP directly JSP uses JavaBeans to encapsulate business logic JSP delivers the response to the browserMVC is here to stay!– Model 2: Browser calls servlet as coordinatorServlet invokes contains business logic or delegates to JavaBeansServlet stores result of business logic in embedded objects in ResponseJSP interrogates the Response and creates a page to send the browser

JSP Syntax Basics The JavaServer Pages specificationincludes:– Directives– Standard JSP Tags– Scripting elements– Implicit Objects– tag extensions

JSP Standard TagsExample JSP standard tags: jsp:useBean id "clock"class “calendar.JspCalendar” / jsp:getProperty name “customer”property “name” / jsp:setProperty name “customer”property “name” param “username” /

JSP Standard Action Tags Standard Action tags used to access Javaobjects from the JSP page. Example JSP standard tag:Java BeanJSP Page jsp:useBean id "clock" class “calendar.JspCalendar” / Like JspCalendar clock new JspCalendar();The JSP page accesses a bean object via a tag.– If a bean doesn’t exist, it is instantiated.– If bean already exists, it is retrieved from thesession or the request context.

What is a JavaBean?public class AccountBean {private String firstName;private String lastName;public AccountBean() {}public String getFirstName() {return firstName;}public void setFirstName(String f) {firstName f;}.}JavaBeans components are Java objects which follow a well-defineddesign/naming patternJava Bean

JSP Standard TagsJava BeanJSP PageExample JSP standard tags: html jsp:useBean id "accountBean"accountBean scope "session"class "AccountBean" / SetProperty: Automatically execute all setters inaccountBean that match values provided as input jsp:setProperty name "accountBean"accountBean property "*"/ form method POST action Account.jsp First Name INPUT type text name "firstName"firstName INPUT type submit name "submit" value "Submit" /form

JSP Standard TagsJava BeanJSP PageExample JSP standard tags: html jsp:useBean id "accountBean"accountBeanscope "session" class "AccountBean" / First Name getProperty: Retrieve value of named attribute jsp:getPropertygetProperty name "accountBeanaccountBean"property “firstName" / " /html

JSP Scripting Elements Declarations: define page level variablesand methods %! QuoteBean q; % Scriptlets: JSP Java code fragments % q new QuoteBean(); % Expressions: results of evaluating theexpression are converted to a string % q.getQuote(“SUNW”); %

Implicit Objects The JSP page has access to certainimplicit objects that are alwaysavailable They are the following:– request - HttpServletRequest– Response –HttpServletResponse– pageContext, HTTP session,– out, config, page, exception

JSP SampleDirective %@ page info "My JSP example“ import "myclasses.*% jsp:useBean id "event“ class "com.sun.jspdemo.webImpl.Eventscope "session" / html ActionTag br h3 The event name is: jsp:getProperty name "event" property "name" / /h3 Expression h3 The event description is: % event.getDescription() % /h3 br br Scriptlet % if (event.getName().equalsIgnoreCase("appointment")) name”); % jsp:include page "appointment.html" / % }else { % jsp:include page "regular.html" / % } % /html ImplicitObject

Portable Tag ExtensionMechanismDesigning tag libraries allows content developersto use custom tags instead of java code. %@ taglib uri "/WEB-INF/sqltaglib.tld" prefix "ora" % HTML HEAD TITLE SQL Tags Example /TITLE /HEAD BODY BGCOLOR "#FFFFFF" HR ora:dbOpen URL "jdbc:oracle:oci8:@" user "scott"password "tiger" connId "con1" /ora:dbOpen ora:dbQuery connId "con1" !-- generates HTML table -- select * from EMP /ora:dbQuery ora:dbClose connId "con1" / HR /BODY /HTML

T A K EDesign IssuesITT OT H EN T H

View Design Issues View Consists of two parts– Request Processing (Part of the controller)– Response Generation Presenation Layout

Tasks in Web Layer Validation of Input– Is form data complete and well-formed?RequestValidationBusiness LogicControl Interaction withBusiness LogicPresentation Presentation of content–Get Data from Model Value Object–Present data to client

ViewView: present User Interface (screenrepresentation of model)RequestCu stome te Query(read only)JSPCustom JSP ActionsJavaBeans Components

When Servlets, When JSP? Use servlets for dispatching between theWeb tier and EJB tier– Request processing use servletand/or JavaBeans Use JSP technology for responsegeneration– Displaying HTML, XML useJSP technology

How Do I Use All These ? separation between contentand application logic:– Move requestprocessing out ofJSP page.– JSP page is primarilypresentation layout.1. Parse RequestHTTPRequestsvaaJns SevletaBe (Controller)reaep3. Forward Requestto JSP PagerP2.JSPJava BeanPage(Model)(View)HTTPResponse

View Design Guidelines BuildView in the Web-tier– Use JavaServer Pages (JSP )components for presentationlayout– Custom tags and JavaBeans components for presentationlogic

#AAll working togetherPresentationLogicLayoutApplication LogicBusinessServicesBusinessDataInventoryEntity BeanControllermainServletSession BeanView SelectionValidates inputCalls session bean.Calls JSP passingValue Model objectupdate()Manages dataShowConfirmationPagepurchaseItems()controls processEnforces transactionsOrderEJBJSPEntity BeanFormats HTMLResponds to clientcreate()Manages data

#AExample Servletpublic void doPost (HttpServletRequest req, HttpServletResponse res) {String userId me accountHome;IAccountBean account;Context initCtx new InitialContext();accountHome initCtx.lookup(“com/AccountHome”);account accountHome.findByPrimaryKey(userId);AccountBean accountBean account.getAccountDetails();Writer out res.getWriter();This is ugly — we need some help!out.println(“ HTML HEAD TITLE Your account /TITLE /HEAD ”);out.println(“ BODY Name “ accountBean.getName() ”. br ”);out.println(“Address: “ accountBean.getAddress() ); }X

Example JSPJSPs are a presentation layer for Servlets. HTML HEAD TITLE Your account /TITLE /HEAD BODY %AccountBean accountBean tBean”);% Name : % accountBean.getName()% br Address: % accountBean.getAddress()% br /BODY /HTML #A

#AExample JSPJSPs are a presentation layer for Servlets. HTML HEAD TITLE Your account /TITLE /HEAD BODY jsp:useBeanuseBean id "accountBeanaccountBean" scope “request"class "AccountBean"/ Name : jsp:getPropertygetProperty name "accountBeanaccountBean" property “name" / “Address: jsp:getPropertygetProperty name "accountBeanaccountBean “property “address"/ “ /BODY /HTML

Example Servlet Dispatchingto JSP Servlets are Java’s answer to CGI/Perl.public void doPost (HttpServletRequest req, HttpServletResponse res) {String userId me accountHome;IAccountBean account;Context initCtx new InitialContext();accountHome initCtx.lookup(“com/AccountHome”);account accountHome.findByPrimaryKey(userId);AccountBean accountBean account.getAccountDetails();Writer out res.getWriter();Javatothesomerescue!This Serveris ugly Pages— we needhelp!out.println(“ HTML HEAD TITLE Youraccount /TITLE /HEAD ”);out.println(“ BODY WelcomeRequestDispatcherdispatcher; “ accountBean.getName ”. br ”);out.println(“Address: “ accountBean.getAddress() );ServletContext context getServletContext(); dispatcher ”); care? hy do I Enablesseparation of presentation logic from presentation layout}dispatcher.forward(req, res); Enable your experts to play to their strengths#A

T A K EResources and SummaryITT OT H EN T H

Resources ava.sun.com/products/servlet

Additional Resources J2EE java.sun.com/j2eeSun ONE www.sun.com/sunoneJava Community Process (JCP) jcp.orgJava and XML java.sun.com/xmlWeb Services www.webservices.org

SummaryThis Section Discussed design andimplementation of the VIEW. Youshould now understand: View Design Issues Guidelines for Architecting the "View"or Presentation logic Servlets for presentation requests JSP s for presentation layout

Call for Action! Download J2EE 1.3 ReferenceImplementationStart developing Servlets and JSPstoday!

www.sun.com/developers/evangcentralIn pursuit of the best software in the universe All presentationsAudiocastsCodecamp materialsTechnology briefingscode/articles/links/chats/resources

T A K EAndrew Gilbertandrew.gilbert@sun.comITT OT H EN T H

Servlets vs. CGI Scalable, uses Lightweight threads: Doesn’t start new process for each request, Initialized once and persists in memory for multiple requests, cached Multi-threaded CGI Based Webserver Request CGI

Related Documents:

1 Difference between Servlets and JSP 2 Basic JSP Architecture 3 Life Cycle of JSP 4 JSP Tags and Expressions 5 Scriptlets, Declarations, Expressions & Directives 6 Action Tags and Implicit Objects 7 JSP to Servlets & Servlets to JSP . 11 St

JSF has nothing to do with JSP per se. JSF works with JSP through a JSP tag library bridge. However, the life cycle of JSF is very different from the life cycle of JSP. Facelets fits JSF much better than JSP because Facelets was designed with JSF in mind, whereas integrating JSF and JSP has

Servlets/JSP 1/24/2001 19 What is a Java Server Page? A JSP is a text-based document that describes how to process a request to create a respons e. The description intermixes template data with some dynamic actions and leverages the Java 2 Platform. E.g. a HTML page that contains Java code

JSP page is a simple web page which contains the JSP elements and template text. The template text can be scripting code such as Html, Xml or a simple plain text. Various Jsp elements can be action tags, custom tags, JSTL library elements. These JSP elements are responsible for generating dynamic contents. Pure Servlet

Podemos editar más de una clase o página JSP en la ventana de edición, cada una en su propio panel, como se muestra en la figura 4.13 en la que tenemos en la ventana de edición de NetBeans dos páginas JSP: index.jsp y control.jsp. Las pestañas en la parte superior nos permiten seleccionar la clase o página JSP que se desea editar. Figura .

Servlets have well defined lifecycle Servlets are managed objects that are loaded on demand and can be unloaded by the server at any time Servlets can be mapped to any part of the URL namespace that a servlet engine has control over Multiple threads of execution can run through a servlet unless otherwise specified

A crash course on Servlets. Servlets Servlets are modules that extend Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form . The web.xml file CAN contain many additional info. For instance, it can contain a section defining an alias

SERVLETS SERVLETS (SANS JSP) Les servlets s’exécute coté serveur alors que les applets coté client. Création d’une servlet sous eclipse Cliquez sur File New Dynamic Web Project Choisir un nom de projet et cliqu