Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.

Similar presentations


Presentation on theme: "Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion."— Presentation transcript:

1 Servlets, JSP and JavaBeans Joshua Scotton

2  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion

3  Install JDK 5.0 ◦ etwork/java/javase/downloads/index-jdk5-jsp html etwork/java/javase/downloads/index-jdk5-jsp html  Install Tomcat 6.0 ◦  Install Eclipse EE IDE ◦ se-ide-java-ee-developers/heliossr1 se-ide-java-ee-developers/heliossr1

4 Handling Client Requests

5  Servlets are modules of Java code that run in a server application  Servlets handle client requests  Although not exclusively, most servlets are used to answer HTTP requests and hence extend the javax.servlet.http.HttpServlet class

6 1. Server Application loads the Servlet and creates an instance by calling the null constructor. 2. Servlet’s init(ServletConfig config) method is called. HttpServlet’s should call super.init(config) if overriding. 3. Once initialized, service(ServletRequest req, ServletResponse res) is called concurrently for every request. 4. When the servlet is unloaded, the destroy() method is called. This may be run concurrently with service so must be thread-safe.

7 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" Hello World!" + " Hello World!" + " "); out.close(); }

8  Request data is sent to the servlet in an HttpServletRequest object  To access a parameter use the getParameter method. For example: String = req.getParameter(“ ”);

9  If you are not going to be sure of which request type you are going to be handling, or if you want to handle both in the same manner. You can forward one to the other as shown below: protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //response code goes here... }

10 JavaServer Pages

11  JSP = JavaServer Pages  Puts Java inside a HTML page  JSP files are recognised by the extension.jsp  JSP’s are compiled on the first time that they are loaded  Needs a JSP supporting web server like Tomcat, Glassfish and Blazix etc TomcatGlassfishBlazix

12 Hello World! The time is:

13 <% //System.out prints to the server log System.out.println( “Getting the Date" ); java.util.Date date = new java.util.Date(); %> The time is: <% //The out object prints to the response out.println(date.toString()); %>

14  The HttpServletRequest can be accessed by JSP as shown in the following example: out.println( “Your machine's address is: " ); out.println( request.getRemoteHost());

15  session.setAttribute( “user", username ); 

16  Page Directive: importing packages  Include Directive: including other JSP’s inline

17  A JSP is turned into a class definition.  To add variables and method declarations to the class you use a JSP declaration using tags as shown in the following example: <%! Date theDate = new Date(); Date getDate() { System.out.println(“Returning the Date...”); return theDate; } %> The time is now

18  ${1 > (4/2)} returns false  ${3 div 4} or ${3 / 4} return 0.75  ${pageContext.request.contextPath} returns the context path  ${sessionScope.cart.numberOfItems} gets the property “numberOfItems” from the session scoped bean “cart”  ${param['mycom.productId']} returns the mycom.productId parameter from the request  ${header["host"]} returns the host value from the page header

19  pageScope: Maps page-scoped variable names to their values  requestScope: Maps request-scoped variable names to their values  sessionScope: Maps session-scoped variable names to their values  applicationScope: Maps application-scoped variable names to their values  pageScope: Maps page-scoped variable names to their values  requestScope: Maps request-scoped variable names to their values  sessionScope: Maps session-scoped variable names to their values  applicationScope: Maps application-scoped variable names to their values

20 Business Logic Blocks

21  Java Class  Implements java.io.Serialiazable interface  Has a nullary constructor  Provides getter and setter methods for accessing it’s properties

22 package webdev.examples; public class UserInfo implements java.io.Serializable { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }

23

24 Example:

25  page – Default scope, the JavaBean is created and destroyed every time a page is loaded.  request – The created object is bound to the request object.  session – The bean is bound to the session object, which means that this will be unique to the user.  application – An object bound to the application will stay as long as the application is loaded. Can be used for counting page views.

26 Example:

27 Example:

28 Enter your name: Enter your age:

29

30 Hello, you are years old.

31 Model, View, Controller

32  Model  View  Controller

33  The Model represents the business logic of the application  Encapsulating business rules into components: ◦ Facilitates testing ◦ Improves quality ◦ Promotes reuse  The model can be partitioned into State and Action components

34  Define the current set of values in the Model and includes methods to update these values.  Should be protocol independent.  JavaBeans are a logical choice for implementing State Components.

35  Define allowable changes to the State in response to events  In simpler systems this function may be absorbed into the Controller, however this is not generally recommended.

36  Represents the presentation logic of the application.  Retrieves the State from the Model and provides the user interface for the specific protocol.  Separating the View from the Model enables the independent construction of user interfaces with different look and feels.  JSPs are a good choice for implementing the View.

37  Provides the glue to MVC  In a MVC system the Controller must handle the following tasks: ◦ Security ◦ Event Identification ◦ Prepare the Model ◦ Process the Event ◦ Handle Errors ◦ Trigger the Response  Servlets are an ideal choice for the Controller

38  You can use just JSP to create a web application  This makes it hard to separate out the web design and the business code  Using JSP just for the View and Servlets for the Controller can simplify the development process

39  Search Example: ArrayList searchResultsList = // get from the query RequestDispatcher disp; disp = getServletContext().getRequestDispatcher("searchresults.jsp"); request.setAttribute("my.search.results", searchResultsList); disp.forward(request, response);  searchResultsList is populated from a query handled by the servlet  searchresults.jsp is selected as the handler for the response  We add the search result array to the request so that it is accessible to the JSP

40  The JSP can retrieve the result set using this code: ArrayList myList = (ArrayList) request.getAttribute("my.search.results");  You can then use a for loop to print the contents of the search request.

41

42 package webdev.examples.address; public class Person implements java.io.Serializable { private String name; private int age; private Address address; public Person() { setName("A N Other"); setAge(21); this.address = new Address(); } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public void setAddress(Address address) { this.address = address; } public Address getAddress() { return address; } }

43 package webdev.examples.address; import java.util.Collection; public class Address implements java.io.Serializable { private String line1; private String town; private String county; private String postcode; private Collection phoneNumbers; public Address() { this.line1 = "line1"; this.town = "a town2"; this.county = "a county"; this.postcode = "postcode"; } public void setLine1(String line1) { this.line1 = line1; } public String getLine1() { return line1; } … public Collection getPhoneNumbers() { return phoneNumbers; } public void setPhoneNumbers(Collection phoneNumbers) { this.phoneNumbers = phoneNumbers; }

44 package webdev.examples.address; public class PhoneNumber implements java.io.Serializable { private String std; private String number; public String getNumber() { return number; } public String getStd() { return std; } public void setNumber(String number) { this.number = number; } public void setStd(String std) { this.std = std; } }

45 package webdev.examples.address; import java.io.IOException; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class handlerServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException { Person p = new Person(); p.setName("Sam Dalton"); p.setAge(26); Address a = new Address(); a.setLine1("221b Baker Street"); a.setTown("London"); a.setCounty("Greater London"); a.setPostcode("NW1 1AA"); ArrayList al = new ArrayList(); PhoneNumber ph = new PhoneNumber(); ph.setStd("01895"); ph.setStd("678901"); al.add(ph); ph = new PhoneNumber(); ph.setStd("0208"); ph.setStd(" "); al.add(ph); a.setPhoneNumbers(al); p.setAddress(a); req.setAttribute("person", p); RequestDispatcher rd = req.getRequestDispatcher(“show.jsp"); rd.forward(req, res); }

46 req.setAttribute("person", p); RequestDispatcher rd = req.getRequestDispatcher(“show.jsp"); rd.forward(req, res);

47 MVC Example MVC Example ${person.name} ${person.age} ${person["address"].line1} ${person["address"].town} ${person.address.phoneNumbers[0].std} ${person.address.phoneNumbers[0].number} ${person.address.phoneNumbers[1].std} ${person.address.phoneNumbers[1].number}

48

49


Download ppt "Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion."

Similar presentations


Ads by Google