Presentation is loading. Please wait.

Presentation is loading. Please wait.

WEB TECHNOLOGIES – Unit VI

Similar presentations


Presentation on theme: "WEB TECHNOLOGIES – Unit VI"— Presentation transcript:

1 WEB TECHNOLOGIES – Unit VI
By B. Ravinder Reddy Assistant Professor Department of CSE UNIT-6 WT

2 Lecture No.. Topic Name Slide No
LECTURE PLAN UNIT-6 Lecture No.. Topic Name Slide No L1 Introduction to JSP 2-73 L2 The Problem with Servlet. 74-84 L3 The Anatomy of a JSP Page 85-116 L4 JSP Processing. L5 JSP Application Design with MVC Setting Up and L6 JSP Environment: Installing the Java Software Development Kit. L7 Tomcat Server & Testing Tomcat UNIT-6 WT

3 LECTURE-1 UNIT-6 WT

4 Introduction to JSP UNIT-6 WT

5 Why JSPs? Goal: Create dynamic web content (HTML, XML, ...) for a Web Application Goal: Make it easier/cleaner to mix static HTML parts with dynamic Java servlet code JSP specification ver. 2.0 Java Servlet specification ver. 2.4 UNIT-6 WT

6 JSP: Java Server Pages UNIT-6 WT

7 Presentation Purpose The purpose of this presentation is:
To introduce JSP, To identify JSP’s unique utility in dynamic web pages, To learn how to write JSP pages through examples. UNIT-6 WT

8 Assumptions We assume you have introductory or peripheral knowledge of: HTTP/1.0 (e.g. GET and POST) HTML 4.0 (e.g. simple tags) Java 1.1.x (syntax and structure) UNIT-6 WT

9 Topics What is JSP? A Simple “Hello, World.”
A Crash Course in JavaBeans More on Syntax. Internal JSP Architecture Overview of Servlets UNIT-6 WT

10 What is JSP? http://java.sun.com/products/jsp,
A way to create dynamic web pages, Server side processing, Based on Java Technology, Large library base Platform independence Separates the graphical design from the dynamic content. UNIT-6 WT

11 First Look at JSP Code <html> <body> <b>I’m HTML code.</b><br> <% out.println(“I’m Java code.”) %> </body> </html> UNIT-6 WT

12 HelloWorld <html> <head> <%-- JSP Declarations --%> <%! String world; %> <!-- JSP Code --> <% world = “World”; %> <title>Hello <%= world %></title> </head> <body> Hello, <%= world %>. </body> </html> Run Example: UNIT-6 WT

13 JSP Syntax Comments Two Types of Comments: HTML Comments JSP Comments
For HTML tags JSP Comments For JSP tags UNIT-6 WT

14 JSP Syntax HTML Comment
Comment can be viewed in the HTML source file <!-- comment <% expression%> --> Example: <!-- this is just Html comment --> <!-- This page was loaded on <%= (new java.util.Date()).toLocaleString()%> --> View source: <!-- This page was loaded on January 1, > UNIT-6 WT

15 JSP Syntax Hidden Comment
Comment cannot be viewed in the HTML source file <% -- expression -- %> Example: <html> <body> <h2>A Test of Comments</h2> <%--This comment will be invisible in page source --%> </body> </html> UNIT-6 WT

16 JSP Syntax Declaration
Declares a variable or method <% ! declaration; %> Example: <body> <%! String name; %> <% name = request.getParameter(“name”); if ( name == null ) name = “World”; %> <h1>Hello, <%= name %>. </h1> </body> UNIT-6 WT

17 JSP Syntax Expression Contains an expression <% = expression %>
Example: <p>The map file has <%= map.size() %> entries. </p> <p> Good guess, but nope. Try <b> <% = numguess.getHint() %> </b></p> UNIT-6 WT

18 JSP Syntax Scriptlet Contains a code fragment
Example: <% String name = null; if (request.getParameter(“name”) == null ) { %> Hello, World <% } else { println.out(“Hello,” + name); } UNIT-6 WT

19 JSP Syntax Include Directive
Includes a static file include file=“relativeURL” %> Example: main.jsp: <html><body> Current date and time is: file=“date.jsp” %> </body></html> date.jsp: import =“java.util.*” %> <% =(new java.util.Date()).toLocaleString() %> Output : Current date and time is: Mar 5, :56:50 UNIT-6 WT

20 JSP Syntax Page Directive
Defines attributes that apply to an entire page page [ language=“java” ] [ extends=“package.class” ] [ import=“package.class” ] [ contentType=“mimeType” ] [ errorPage=“relativeURL” ] %> Example: page extends=“myClass” import=‘java.util.*” contentType=“text/html” errorPage=“error.jsp” %> UNIT-6 WT

21 JSP Syntax <jsp:forward>
Forwards request to another file (HTML, JSP, or Servlet) for processing <jsp:forward page =“relativeURL” %> Example: <jsp:forward page=“scripts/login.jsp” /> or <jsp:forward page=“scripts/login.jsp” > <jsp:param name=“username” value=“jsmith”/> </jsp:forward> UNIT-6 WT

22 JSP Syntax <jsp:include>
Includes a static or dynamic file <jsp:include page =“relativeURL” %> Example: <jsp:include page=“scripts/login.jsp” /> <jsp:include page=“copyright.html” /> UNIT-6 WT

23 JSP Syntax <jsp:useBean>
Locates or instantiates a JavaBeans components. <jsp:useBean id=“beanInstanceName” scope=“page| request | session | application” class=“package.class” /> Example: <jsp:useBean id=“calendar”scope=“page” class=“employee.Calendar”/> UNIT-6 WT

24 JSP Syntax <jsp:setProperty>
Sets the value of one or more properties in a Bean, using the Bean’s setter methods. Declare the Bean with <jsp:useBean> first <jsp:setProperty name=“beanInstanceName” property=“propertyName” value=“string” /> Example: <jsp:useBean id=“calendar”scope=“page” class=“employee.Calendar”/> <jsp:setProperty name=“calendar” property=“username” value=“Steve”/> UNIT-6 WT

25 JSP Syntax <jsp:setProperty>
Setting the property attribute to the magic value “*” will automatically set properties according to the request parameters. You can also use the attribute “param” to set a specific parameter from the request value. Example: <jsp:useBean id=“calendar” scope=“session” class=“employee.Calendar”/> <jsp:setProperty name=“calendar” property=“username” param=“user”/> UNIT-6 WT

26 JSP Syntax <jsp:getProperty>
Gets a Bean property value, using the Bean’s getter methods. Declare the Bean with <jsp:useBean> first <jsp:getProperty name=“beanInstanceName” property=“propertyName” /> Example: <jsp:useBean id=“calendar”scope=“page” class=“employee.Calendar”/> <H1>Calendar of <jsp:getProperty name=“calendar” property=“username”/> </H1> UNIT-6 WT

27 How the JSP Engine Works: Overview
UNIT-6 WT

28 How the JSP Engine Works: Internals
UNIT-6 WT

29 Servlets in the Server Servlet Engine HelloServlet MapServlet
GET /index.html HelloServlet GET /index.html MapServlet GET /map.html UNIT-6 WT

30 A Basic Servlet public class ExampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { out.setContentType(“text/html”); PrintWriter out = request.getWriter(); out.println(“Hello NYC!<BR>”); Date rightNow = new Date(); out.println(“The time is: “ + rightNow); } } UNIT-6 WT

31 Servlet Basics Servlets have a well defined Lifecycle.
Servlets load on demand and can be unloaded by the server at any time. Multiple threads of execution can run through a Servlet unless otherwise specified. UNIT-6 WT

32 Servlet Lifecycle init method called exactly once upon load
service method called 0-multiple times destroy method is called when Servlet is unloaded from host server UNIT-6 WT

33 JSP/ASP/PHP vs CGI/Servlets
CGI & Servlets -- Mostly Code with some HTML via print & out.println JSP/ASP/PHP -- Mostly HTML, with code snippets thrown in No explicit recompile Great for small problems Easier to program Not for large computations UNIT-6 WT

34 What is JSP? Mostly HTML page, with extension .jsp
Include JSP tags to enable dynamic content creation Translation: JSP → Servlet class Compiled at Request time (first request, a little slow) Execution: Request → JSP Servlet's service method UNIT-6 WT

35 What is a JSP? <html> <body> <jsp:useBean.../>
<jsp:getProperty.../> </body> </html> UNIT-6 WT

36 Advantages Code -- Computation HTML -- Presentation
Separation of Roles Developers Content Authors/Graphic Designers/Web Masters Supposed to be cheaper... but not really... UNIT-6 WT

37 Model-View-Controller
A Design Pattern Controller -- receives user interface input, updates data model Model -- represents state of the world (e.g. shopping cart) View -- looks at model and generates an appropriate user interface to present the data and allow for further input UNIT-6 WT

38 Model-View-Controller
JSP View Bean Servlet Controller Model UNIT-6 WT

39 Servlet Pure Servlet JSP Java Bean Public class OrderServlet … {
public void doGet(…){ if(bean.isOrderValid(…)){ bean.saveOrder(req); forward(“conf.jsp”); } Servlet Pure Servlet public class OrderServlet … { public void dogGet(…){ if(isOrderValid(req)){ saveOrder(req); out.println(“<html><body>”); } private void isOrderValid(…){ private void saveOrder(…){ <html> <body> <c:forEach items=“${order}”> </c:forEach> </body> </html> JSP isOrderValid() saveOrder() private state Java Bean UNIT-6 WT

40 JSP Big Picture Hello.jsp HelloServlet.java Server w/ JSP Container
GET /hello.jsp HelloServlet.java <html>Hello!</html> Server w/ JSP Container HelloServlet.class UNIT-6 WT

41 A JSP File UNIT-6 WT

42 <%@ Directive %>
page contentType="text/html" %> taglib prefix="c" uri= %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of dynamically --%> = <c:out value="${ }" /> </body> </html> UNIT-6 WT

43 <%-- JSPComment -->
page contentType="text/html" %> taglib prefix="c" uri= %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of dynamically --%> = <c:out value="${ }" /> </body> </html> UNIT-6 WT

44 Template Text <%@ page contentType="text/html" %>
taglib prefix="c" uri= %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of dynamically --%> = <c:out value="${ }" /> </body> </html> UNIT-6 WT

45 <%= expr > Java expression whose output is spliced into HTML
<%= userInfo.getUserName() %> <%= %> <%= new java.util.Date() %> Translated to out.println(userInfo.getUserName()) ... UNIT-6 WT

46 <% code %> Scriptlet: Add a whole block of code to JSP...
passed through to JSP's service method UNIT-6 WT

47 <%@ page language="java" contentType="text/html" %>
page import="java.util.*" %> taglib prefix="c" uri=" %> <% // Create an ArrayList with test data ArrayList list = new ArrayList( ); Map author1 = new HashMap( ); author1.put("name", "John Irving"); author1.put("id", new Integer(1)); list.add(author1); UNIT-6 WT

48 Map author2 = new HashMap( ); author2
Map author2 = new HashMap( ); author2.put("name", "William Gibson"); author2.put("id", new Integer(2)); list.add(author2); Map author3 = new HashMap( ); author3.put("name", "Douglas Adams"); author3.put("id", new Integer(3)); list.add(author3); pageContext.setAttribute("authors", list); %> UNIT-6 WT

49 <title>Search result: Authors</title> </head>
<html> <head> <title>Search result: Authors</title> </head> <body bgcolor="white"> Here are all authors matching your search critera: <table> <th>Name</th> <th>Id</th> <c:forEach items=“${authors}” var=“current”> UNIT-6 WT

50 <%@ page language="java" contentType="text/html" %> <html>
<head> <title>Browser Check</title> </head> <body bgcolor="white"> <% String userAgent = request.getHeader("User-Agent"); UNIT-6 WT

51 if (userAgent.indexOf("MSIE") != -1) { %>
You're using Internet Explorer. <% } else if (userAgent.indexOf("Mozilla") != -1) { %> You're probably using Netscape. % } else { %> You're using a browser I don't know about. <% } %> </body> </html> UNIT-6 WT

52 <%! decl > Turned into an instance variable for the servlet
What did I tell you about instance variables & multithreaded servlets? Serious Race Conditions Here! UNIT-6 WT

53 Declarations have serious multithreading issues!
page language="java" contentType="text/html" %> <%! int globalCounter = 0; %> <html> <head> <title>A page with a counter</title> </head> <body bgcolor="white"> Declarations have serious multithreading issues! UNIT-6 WT

54 This page has been visited: <%= ++globalCounter %> times.
int localCounter = 0; %> This counter never increases its value: <%= ++localCounter %> </body> </html> UNIT-6 WT

55 <jsp:include …>
<jsp:include page="trailer.html“ flush="true" /> UNIT-6 WT

56 Big Picture – Web Apps Database Legacy Applications End User #1
Java Applications Web Service Other…? Web Server (Servlets/JSP) End User #2 UNIT-6 WT

57 Invoking Dynamic Code (from JSPs)
Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags) UNIT-6 WT

58 Invoking Dynamic Code (from JSPs)
Simple Application or Small Development Team Call Java Code Directly (Expressions, Declarations, Scriptlets) Call Java Code Indirectly (Separate Utility Classes, JSP calls methods) Use Beans (jsp:useBean, jsp:getProperty, jsp:setProperty) Use MVC architecture (servlet, JSP, JavaBean) Use JSP expression Language (shorthand to access bean properties, etc) Use custom tags (Develop tag handler classes; use xml-like custom tags) Complex Application or Big Development Team UNIT-6 WT

59 Servlets and JSPs Core Servlets and JavaServer Pages, 2nd Edition, Volumes 1 & 2. Marty Hall & Larry Brown UNIT-6 WT

60 Java Beans Purpose: Store Data Simple Object,
requires no argument constructor Properties accessible via get & set methods UNIT-6 WT

61 Java Beans For a "foo" property, a java bean will respond to
Type getFoo() void setFoo(Type foo) For a boolean "bar" property, a java bean will respond to boolean isBar() void setBar(boolean bar) UNIT-6 WT

62 Java Bean int getCount() void setCount(int c) String getS()
void setS(String s) int[] getFoo() void setFoo(int[] f) int count; String s; int[] foo; UNIT-6 WT

63 UNIT-6 WT

64 /* A simple bean that contains a single * "magic" string. */
// MagicBean.java /* A simple bean that contains a single * "magic" string. */ public class MagicBean { private String magic; public MagicBean(String string) { magic = string; } public MagicBean() { magic = "Woo Hoo"; // default magic string public String getMagic() { return(magic); public void setMagic(String magic) { this.magic = magic; UNIT-6 WT

65 Java Beans <jsp:useBean id="myBean" class="com.foo.MyBean“ scope="request"/> <jsp:getProperty name="myBean“ property="lastChanged" /> <jsp:setProperty name="myBean“ property="lastChanged" value="<%= new Date()%>"/> Example <jsp:usebean id="bean" class="MagicBean" /> <jsp:getProperty name="bean" property="magic" /> UNIT-6 WT

66 <h3>Bean JSP</h3>
<hr> <h3>Bean JSP</h3> <p>Have all sorts of elaborate, tasteful HTML ("presentation") surrounding the data we pull off the bean. <p> Behold -- I bring forth the magic property from the Magic Bean... <!-- bring in the bean under the name "bean" --> <jsp:usebean id="bean" class="MagicBean" /> <table border=1> <tr> <td bgcolor=green><font size=+2>Woo</font> Hoo</td> <td bgcolor=pink> <font size=+3> <!-- the following effectively does bean.getMagic() --> <jsp:getProperty name="bean" property="magic" /> </font> </td> <td bgcolor=yellow>Woo <font size=+2>Hoo</font></td> </tr> </table> <!-- pull in content from another page at request time with a relative URL ref to another page --> <jsp:include page="trailer.html" flush="true" /> UNIT-6 WT

67 public class HelloBean extends HttpServlet
{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); String title = "Hello Bean"; out.println("<title>" + title + "</title>"); out.println("</head>"); out.println("<body bgcolor=white>"); out.println("<h1>" + title + "</h1>"); out.println("<p>Let's see what Mr. JSP has to contribute..."); request.setAttribute("foo", "Binky"); MagicBean bean = new MagicBean("Peanut butter sandwiches!"); request.setAttribute("bean", bean); RequestDispatcher rd = getServletContext().getRequestDispatcher("/bean.jsp"); rd.include(request, response); out.println("<hr>"); out.println("</body>"); out.println("</html>"); } // Override doPost() -- just have it call doGet() public void doPost(HttpServletRequest request, HttpServletResponse response) doGet(request, response); UNIT-6 WT

68 JSP Tags Found in JSP Pages Look like HTML Tags Single Tag Format
<blah attr=val>Foo</blah> Single Tag Format <blah attr=val/> UNIT-6 WT

69 <%-- JSPComment --%>
page contentType="text/html" %> taglib prefix="c" uri=" %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of dynamically --%> = <c:out value="${ }" /> </body> </html> UNIT-6 WT

70 <%@ Directive %>
page contentType="text/html" %> taglib prefix="c" uri=" %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> <%-- Calculate the sum of dynamically --%> = <c:out value="${ }" /> </body> </html> UNIT-6 WT

71 Page Directive <%@ page import="package.class" %>
page import="java.util.*" %> page contentType="text/html" %> <% response.setContentType("text/html"); %> UNIT-6 WT

72 Include Directive <%@ include file="Relative URL">
Included at Translation time May contain JSP code such as response header settings, field definitions, etc... that affect the main page UNIT-6 WT

73 <jsp:include …>
Include Files at Request Time <jsp:include page="news/Item1.html"/> page attribute must point to a page that is HTML or a page that produces HTML (via JSP, CGI, etc)... UNIT-6 WT

74 Scripting Element Tags
<%= expr %> <%! decl %> <% code %> UNIT-6 WT

75 LECTURE-2 UNIT-6 WT

76 Problem of a Servlet Request
When a request is resolved to a servlet a Request and Response object are created and handed to the Servlet.service method. The Request Object contains all the information coming from the client. The Response Object encapsulates communication back the the client. UNIT-6 WT

77 Servlet Request Illustration
Server Request Servlet Response UNIT-6 WT

78 The Request Object Access to request headers
Access to an InputStream containing data from the client Access to CGI Like information Access to query parameters (form data) Access to server specific parameters such as SSL Cipher Suite UNIT-6 WT

79 Frequently Used Request Methods
javax.servlet.ServletRequest { Enumeration getParameterNames(); String getParameter(String parameterName); String getRemoteAddr(); } javax.servlet.http.HttpServletRequest { String getRequestURI(); Enumeration getHeaderNames(); String getHeader(String headerName); HttpSession getSessiOn(); Cookie[] getCookies(); } UNIT-6 WT

80 The Response Object Access to response headers such as Content-Type, Character-Encoding, etc. Access to an OutputStream for returning data to the client Access to setting cookies Convenience methods for sending errors, redirects, etc. UNIT-6 WT

81 Response Methods javax.servlet.ServletResponse { PrintWriter getWriter(); ServletOutputStream getOutputStream(); void setContentType(String type); void setContentLength(int length); } javax.servlet.http.HttpServletResponse { void addCookie(Cookie cookie); void setStatus(int statusCode); void sendError(int statusCode); void sendRedirect(String url); } UNIT-6 WT

82 JSP versus Servlets But JSP pages are converted to Servlets? Aren’t they the same? Similarities Provide identical results to the end user JSP is an additional module to the Servlet Engine UNIT-6 WT

83 JSP versus Servlets (cont’d)
Differences Servlets: “HTML in Java code” HTML code inaccessible to Graphics Designer Everything very accessible to Programmer JSP: “Java Code Scriptlets in HTML” HTML code very accessible to Graphics Designer Java code very accessible to Programmer UNIT-6 WT

84 Conclusion Robust server side dynamic web page generator.
Easy to Implement Implemented on a variety of reliable servers and platforms Based on the Java language Easy to Manage Separates graphical design requirements and programming requirements. Free UNIT-6 WT

85 Servlet Pros/Cons Pros Full access to all Java APIs
Full control of output (text, binary, etc) Great as a web application "controller". Cons Programmatic HTML output is hard to maintain: out.println(“<html>…”); Requires manual compilation (unless using Eclipse) Low-level; harder to work with (similar to ISAPI DLL) Easier to use JSP for building HTML display output. UNIT-6 WT

86 LECTURE-3 UNIT-6 WT

87 The Anatomy of a JavaServerPage
The Java Platform, Enterprise Edition 5 (Java EE 5) has two different but complementary technologies for producing dynamic web content in the presentation tier—namely Java Servlet and JavaServer Pages (JSP). Java Servlet, the first of these technologies to appear, was initially described as extensions to a web server for producing dynamic web content. JSP, on the other hand, is a newer technology but is equally capable of generating the same dynamic content. However, the way inwhich a servlet and a JSP page produce their content is fundamentally different; Servlets embed content into logic, whereas JSP pages embed logic into content. UNIT-6 WT

88 JSP pages contain markup interlaced with special JSP elements that provide logic for controlling the dynamic content. Servlets are built using Java classes that contain statements tooutput markup code. Of these two paradigms, JSP pages are preferred for presenting dynamic content in the presentation tier due to their greater readability, maintainability, and simplicity. Further increasing the simplicity and ease of use of JSP pages was one of the main objectives of the JSP 2.0 specification, which included several new features to make it easier than ever to embrace JSP technology, especially for developers who aren’t fluent in the Java syntax. UNIT-6 WT

89 The inclusion of a new expression language (EL) enables JavaScript-style JSP code to be embedded within pages, which makes it much easier for web developers not familiar with theJava syntax to understand the JSP logic. A library of standard actions known as the JavaServerPages Standard Tag Library (JSTL) is also included to provide a host of useful, reusable actions such as conditional statements, iteration, and XML integration to name a few. These actions are applicable in some shape or form to most JSP web applications, and their use will greatly improve the reliability and ease of development for JSP page authors. Custom actions (also known as custom tags) also benefit from changes in the JSP specification, and it’s now possible to write a custom action entirely in JSP syntax instead of Java syntax! UNIT-6 WT

90 • The JSP 2.1 expression language (EL)
JSP 2.1 further eases the development of JSP pages by unifying the JSP expression language with the JavaServer Faces (JSF) expression language. These new features will help make JSP pages easier to write and maintain and are discussed in detail in the following topics: • The JSP 2.1 expression language (EL) • The JavaServer Pages Standard Tag Library (JSTL) • The JavaServer Faces custom tags • JSP custom tags UNIT-6 WT

91 The JSP Expression Language (EL): Goals and principles
The major goal: simplicity. The language should be usable by nonprogrammers. Inspirations: JavaScript, XPath But it’s much simpler than even these basic expression languages. Quick: what does //foo = ‘bar’ mean in XPath? Or what happens with age + 3 in ECMAScript? UNIT-6 WT

92 The JSP Expression Language (EL): Key syntax
Expressions appear between ${ and }. Note that ${ and } may contain whole expressions, not just variable names, as in the Bourne shell (and its dozen derivatives.) E.g., ${myExpression + 2} Expressions’ default targets are scoped attributes (page, request, session, application) ${duck} ≡ pageContext.findAttribute(“duck”) UNIT-6 WT

93 The JSP Expression Language (EL): Key syntax
The . and [] operators refer to JavaBean-style properties and Map elements: ${duck.beakColor} can resolve to ((Duck) pageContext.getAttribute(”duck”)).getBeakColor() Note the automatic type-cast. This is one of the great features of the EL: users do not need to concern themselves with types in most cases (even though the underlying types of data objects are preserved.) UNIT-6 WT

94 The JSP Expression Language (EL): advanced data access
Expressions may also refer to cookies, request parameters, and other data: ${cookie.crumb} ${param.password} ${header[“User-Agent”]} ${pageContext.request.remoteUser} UNIT-6 WT

95 The JSP Expression Language (EL): more syntax
The EL supports Arithmetic ${age + 3} Comparisons ${age > 21} Equality checks ${age = 55} Logical operations ${young or beautiful} Emptiness detection ${empty a} ‘a’ is empty String (“”), empty List, null, etc. Useful for ${empty param.x} UNIT-6 WT

96 The JSP Expression Language: Uses
JSTL 1.0 introduced the EL, but it could be used only within tags. In JSP 2.0, it can be used almost anywhere <font color=”${color}”> Hi, ${user}. You are <user:age style=”${style}”/> years old. </font> UNIT-6 WT

97 The JavaServer Pages Standard Tag Library (JSTL)
Standard set of tag libraries . Encapsulates core functionality common to many JSP applications – iteration and conditionals – XML – database access – internationalized formatting . Likely to evolve to add more commonly used tags in future versions UNIT-6 WT

98 Why JSTL? You don't have to write them yourself
. You learn and use a single standard set of tag libraries that are already provided by compliant Java EE platforms . Vendors are likely to provide more optimized implementation . Portability of your applications are enabled UNIT-6 WT

99 JSTL Tag Libraries Core (prefix: c)
– Variable support, Flow control, URL management . XML (prefix: x) – Core, Flow control, Transformation . Internationalization (i18n) (prefix: fmt) – Local, Message formatting, Number and date formatting . Database (prefix: sql) – SQL query and update . Functions (prefix: fn) – Collection length, String manipulation UNIT-6 WT

100 Declaration of JSTL Tag Libraries
. Variable support – <c:set> – <c:remove> . Conditional – <c:if> – <c:choose> . <c:when> . <c:otherwise> . Iteration – <c:forEach> – <c:forTokens> UNIT-6 WT

101 JSP custom tags A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on a tag handler. The web container then invokes those operations when the JSP page’s servlet is executed. Custom tags have a rich set of features. They can be customized by means of attributes passed from the calling page. Pass variables back to the calling page. Access all the objects available to JSP pages. UNIT-6 WT

102 <tt:tag /> or <tt:tag></tt:tag>
Communicate with each other. You can create and initialize a JavaBeans component, create a public EL variable that refers to that bean in one tag, and then use the bean in another tag. Be nested within one another and communicate by means of private variables. Types of Tags Simple tags are invoked using XML syntax. They have a start tag and an end tag, and possibly a body: <tt:tag> body</tt:tag>A custom tag with no body is expressed as follows: <tt:tag /> or <tt:tag></tt:tag> UNIT-6 WT

103 Tags with Attributes A simple tag can have attributes. Attributes customize the behavior of a custom tag just as parameters customize the behavior of a method. There are three types of attributes: Simple attributes Fragment attributes Dynamic attributes UNIT-6 WT

104 Simple Attributes Simple attributes are evaluated by the container before being passed to the tag handler. Simple attributes are listed in the start tag and have the syntax attr="value". You can set a simple attribute value from a String constant, or an expression language (EL) expression, or by using a jsp:attribute element (see jsp:attribute Element). The conversion process between the constants and expressions and attribute types follows the rules described for JavaBeans component properties in Setting JavaBeans Component Properties. UNIT-6 WT

105 <sc:catalog bookDB ="${bookDB}" color="#cccccc">
The Duke’s Bookstore page tut-install/javaeetutorial5/examples/web/bookstore3/web/bookcatalog.jsp calls thecatalog tag, which has two attributes. The first attribute, a reference to a book database object, is set by an EL expression. The second attribute, which sets the color of the rows in a table that represents the bookstore catalog, is set with a String constant. <sc:catalog bookDB ="${bookDB}" color="#cccccc"> UNIT-6 WT

106 Fragment Attributes A JSP fragment is a portion of JSP code passed to a tag handler that can be invoked as many times as needed. You can think of a fragment as a template that is used by a tag handler to produce customized content. Thus, unlike a simple attribute which is evaluated by the container, a fragment attribute is evaluated by a tag handler during tag invocation. UNIT-6 WT

107 Action Elements Standard Actions JSTL (tag library) Actions
Custom Actions UNIT-6 WT

108 Standard Actions <jsp:useBean> Makes a JavaBeans component available in a page <jsp:getProperty> Gets a property value from a JavaBeans component and adds it to the response <jsp:setProperty> Set a JavaBeans property value <jsp:include> Includes the response from a servlet or JSP page during the request processing phase UNIT-6 WT

109 Standard Actions <jsp:forward>
Forwards the processing of a request to servlet or JSP page <jsp:param> Adds a parameter value to a request handed off to another servlet or JSP page using <jsp:include> or <jsp: forward> <jsp:plugin> Generates HTML that contains the appropriate client browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software UNIT-6 WT

110 Custom Actions (Tag Libraries)
Can Define Your own! Description Define Install Declare Use Details in JavaServer Pages 2nd ed found on Safari Techbooks UNIT-6 WT

111 JSTL Tags taglib prefix="c" uri=" %> ... <c:out value="${ }" /> UNIT-6 WT

112 JSP Standard Tag Library
Built on custom tag infrastructure page contentType="text/html" %> taglib prefix="c" uri=" %> <html> <head> <title>JSP is Easy</title> </head> <body bgcolor="white"> <h1>JSP is as easy as ...</h1> = <c:out value="${ }" /> </body> </html> UNIT-6 WT

113 JSTL Control Tags <%@ page contentType="text/html" %>
taglib prefix="c “uri=" %> <c:if test="${2>0}"> It's true that (2>0)! </c:if> <c:forEach items="${paramValues.food}" var="current"> <c:out value="${current}" />  </c:forEach> UNIT-6 WT

114 Expression Language Motivation
Limitations of MVC <%= ... %>, <% ... %>, <%! ... %> jsp:useBean, jsp:getProperty verbose clumsy scripting & expression elements to do more complicated Java things With Expression Language ${expression} Short and readable and fluid, like JavaScript UNIT-6 WT

115 Advantages of Expression Language (EL)
Simple & Concise Flexible (use in conjunction with tag libraries & custom tags) Robust against Error UNIT-6 WT

116 Basic Arithmetic ${1.2 + 2.3} => 3.5 <%= 1.2 + 2.3 %>
${ } => 3.5 <%= %> ${3/0} => Infinity \${1} => ${1} ${10 mod 4} => 2 UNIT-6 WT

117 EL Examples <input name="firstName“ value="${customer.firstName}"> <c:out value="${order.amount + 5}"/> ${order.amount + 5} {order['amount'] + 5} UNIT-6 WT

118 LECTURE-4 UNIT-6 WT

119 JSP Processing Beans and Form processing
Forms are a very common method of interactions in web sites.  JSP makes forms processing specially easy. The standard way of handling forms in JSP is to define a "bean".  This is not a full Java bean.  You just need to define a class that has a field corresponding to each field in the form.  The class fields must have "setters" that match the names of the form fields.  For instance, let us modify our GetName.html to also collect address and age. The new version of GetName.html is UNIT-6 WT

120 <HTML> <BODY> <FORM METHOD=POST ACTION="SaveName
<HTML> <BODY> <FORM METHOD=POST ACTION="SaveName.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> <BR>What's your address? <INPUT TYPE=TEXT NAME= SIZE=20> <BR>What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4><P> <INPUTTYPE=SUBMIT></FORM></BODY></HTML> UNIT-6 WT

121 Getter methods are defined similarly, with "get" instead of "set".
To collect this data, we define a Java class with fields "username", " " and "age" and we provide setter methods "setUsername", "set " and "setAge", as shown.  A "setter" method is just a method that starts with "set" followed by the name of the field.  The first character of the field name is upper-cased.  So if the field is " ", its "setter" method will be "set ".  Getter methods are defined similarly, with "get" instead of "set".    Note that the setters  (and getters) must be public. package user;public class UserData UNIT-6 WT

122 public class UserData { String username; String email; int age;
package user; public class UserData {    String username;    String ;    int age;    public void setUsername( Stringvalue )    {        username = value;    }    public void set ( String value )    {        = value;    UNIT-6 WT

123 public void setAge( int value ) { age = value; } public String getUsername() { return username; } public String get () { return ; public int getAge() { return age; UNIT-6 WT

124 The method names must be exactly as shown
The method names must be exactly as shown.  Once you have defined the class, compile it and make sure it is available in the web-server's classpath.  The server may also define special folders where you can place bean classes, e.g. with Blazix you can place them in the "classes" folder.  If you have to change the classpath, the web-server would need to be stopped and restarted if it is already running.  (If you are not familiar with setting/changing classpath, see notes on changing classpath.) Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named user under the classpath entry. UNIT-6 WT

125 Now let us change "SaveName.jsp" to use a bean to collect the data.
<jsp:useBean id="user" class="user.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/>  <HTML><BODY> <A HREF="NextPage.jsp">Continue </A></BODY></HTML> UNIT-6 WT

126 All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag! 
The useBean tag will look for an instance of the "user.UserData" in the session.  If the instance is already there, it will update the old instance.  Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!  UNIT-6 WT

127 Let us modify NextPage.jsp to retrieve the data from bean..
<jsp:useBean id="user" class="user.UserData" scope="session"/> <HTML> <BODY>You entered <BR>Name: <%= user.getUsername() %> <BR> <%= user.get () %> <BR>Age: <%= user.getAge() %><BR> </ BODY></HTML> UNIT-6 WT

128 Notice that the same useBean tag is repeated
Notice that the same useBean tag is repeated.  The bean is available as the variable named "user" of class "user.UserData".  The data entered by the user is all collected in the bean. We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag.  UNIT-6 WT

129 LECTURE-5 UNIT-6 WT

130 JSP Application Design
UNIT-6 WT

131 contents JSP Model 1 Page-View Page-View with bean
2 Page-View 3 Page-View with bean 4 JSP Model 2- Front Controller Pattern 5 How to make all the request go to one servlet ? 6 Identifying the Operation to Perform 7 Advantage of Front Controller Pattern UNIT-6 WT

132 Know The JSP Model 1 & Model 2 architectures
Implement JSPs using the Model 1 and Model 2 approaches UNIT-6 WT

133 JSP Model 1 Requests are made directly to the JSP page or servlets that produce the response. JSP or servlet access the enterprise resources through a java bean and generate response themselves. Two variants: Page-View Page-View with bean UNIT-6 WT

134 JSP Model 1 Advantage: simple to program and allows page author to generate content easily, based upon the request and the state of the resources. Disadvantage: the page complexity increases with the increase of application complexity – excessive java code embedded within JSP page. UNIT-6 WT

135 Page-View Business Processing JSP
All the business processing is done in the jsp UNIT-6 WT

136 Page-View with bean JSP Business Processing Worker Bean
Bean functionality can be modified without affecting jsp code. Some JSP code will sometimes have to manipulate sessions ,application-wide resource or state before response can be generated. This will lead to more of java code embedded in the JSP code. Also the flow of the application logic is embedded in the JSP. UNIT-6 WT

137 JSP Model 2- Front Controller Pattern
Underlying idea of MVC architecture UNIT-6 WT

138 Model 2 Architecture/ Front Controller Pattern
Single control point for presentation tier response View Model request Controller request Model response View Model 2 Architecture/ Front Controller Pattern UNIT-6 WT

139 Having one servlet as a single point of entry into whole application
This entry point produces no output by itself but processes the request optionally manipulates session and application state redirects requests to appropriate JSP view or a sub-controller that knows how to handle a subset of requests to the application. Models are provided by java beans created or managed by the controller and made available to JSP views Preferred approach. UNIT-6 WT

140 How to make all the requests go to one servlet ?
Make url pattern for the servlet as: <url-pattern>/*</url-pattern> Problem with this is that when the servlet tries to forward to another url then the request again goes back to the same servlet <url-pattern>*.xxx</url-pattern> provided we don’t have any such pages in our application with that extension. For instance we could have pattern as <url-pattern>*.html</url-pattern> UNIT-6 WT

141 In that case, we make all the view pages as jsp pages so that servlet can forward to jsp pages.
Implies that all the url links that we make in our HTML pages will link to another html page even though we don’t have even a single html page in our application. This shouldn't be a problem because in any case the servlet can get the requested path and analyze what is required and then forward to another JSP. UNIT-6 WT

142 Identifying the Operation to Perform
Indicate the operation in a hidden form field, which a POST operation delivers to the controller; for example: <FORM METHOD="POST" ACTION="myServlet"> <INPUT TYPE="HIDDEN" NAME="OP" VALUE="createUser"/> … </FORM> Indicate the operation in a HTTP GET query string parameter; for example: UNIT-6 WT

143 String path=request.getServletPath();
Through requested url paths : Servlet can extract the requested operation's name from the request URL. Servlet myServlet can extract the requested operation's name from the request URL. String path=request.getServletPath(); The BluePrints recommendation is to use servlet mappings when they are available. Servlet mappings provide the most flexible way to control where to route URLs based on patterns in the URL UNIT-6 WT

144 requests Servlet JSP Page 1 Model Class 1 Model Class 2 JSP Page 2
RequestHandler String handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException returns URL requests Servlet handleRequest() Sub-Controller Class 1 Sub-Controller Class 2 url JSP Page 1 data Model Class 1 Model Class 2 JSP Page 2 UNIT-6 WT

145 Example request Servlet_C Emp_C Dept_C EmpInsert Employee Department
RequestHandler returns URL String handleRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException request Servlet_C handleRequest() Emp_C Dept_C url EmpInsert data Employee Department DeptInsert UNIT-6 WT

146 public class ControllerServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException { String path=request.getServletPath(); RequestHandler rh; if(path.equals(“\empIns.html”)){ rh=(RequestHandler) new Emp_C; UNIT-6 WT

147 if(path.equals(“\deptIns.html”)){ rh=(RequestHandler) new Dept_C;
else if(path.equals(“\deptIns.html”)){ rh=(RequestHandler) new Dept_C; String view=rh.handleRequest(request,response); request.getRequestDispatcher(view).forward(request,response);} } UNIT-6 WT

148 Model classes view classes Employee Department -empno -empName -dept
-deptName -managerid <Setters> <Getters> boolean insert() static Vector findAll() static Department findDept(String dept) <Setters> <Getters> boolean insert() static Employee findByName(String name) static Employee findById(String id) static Vector findAll() view classes Index InsertEmployee FindEmployee InsertDepartment FindDepartment UNIT-6 WT

149 Controller classes ControllerServlet doGet() EmpHandler DeptHandler
Vector findAllDepartments() Employee findEmployees(String name,String empno) boolean insertEmployee(String name,String empno, String dept) boolean validateEmployee() Department findDept(String name ) boolean insertDept(String deptname,String managerid) boolean validateDept() Vector findAllEmployees() UNIT-6 WT

150 Advantage of Front Controller Pattern
A Model 1 architecture is best when the page navigation is simple and fixed, and when a simple directory structure can represent the structure of the pages in the application. Over time, as the application grows and changes, page flow logic accumulates. T The application becomes difficult to maintain because the page flow logic is distributed across multiple pages. This causes maintenance problem. All the flow is handled by a single servlet. UNIT-6 WT

151 Advantage of Front Controller Pattern
Servlet code and the controller code is decoupled from sub-controller so any change in one does not effect another. The same set of classes (sub-controller and entity classes) and can be used for a different types of client. UNIT-6 WT

152 LECTURE-6 UNIT-6 WT

153 Installing the Java Software Development Kit.
JSP Environment: Installing the Java Software Development Kit. UNIT-6 WT

154 Double-click on the install file and
it should open an installer (Fig. 1). Figure 1: The installer (JDK 6) running. UNIT-6 WT

155 On the next screen you will encounter some options
On the next screen you will encounter some options. Just leave these alone and click next unless you know what you are doing. (Because this is being read it is assumed that you do not.)(Fig. 2) UNIT-6 WT

156 Figure 2: The options you should not touch.
UNIT-6 WT

157 The next page you encounter should install (and in some cases download) the Java Development Kit. (Fig. 3) UNIT-6 WT

158 Figure 3: Installing the JDK.
UNIT-6 WT

159 In the text box, type "cmd" and click "OK".
After the installer is finished, open run by clicking Start > Run... or by typing Windows Key + R. In the text box, type "cmd" and click "OK". A simple window should be opened with a black background and a text prompt. This is called the "Command Prompt." My command prompt background is red, but it could really be any color. (Fig. 4 UNIT-6 WT

160 Figure 4: The command prompt running
UNIT-6 WT

161 After focusing the window, type "javac" and press enter
After focusing the window, type "javac" and press enter. If the prompt returns something along the lines of: "'javac' is not recognized as an internal or external command, operable program or batch file" then continue with the next step. If it shows many more options and lines, skip to step 15. Open the properties of "My Computer" by either right-clicking the icon on the desktop or right-clicking Start > My Computer. When the pop up menu opens, scroll to the bottom and select "Properties". UNIT-6 WT

162 This should open a window named "System Properties"
This should open a window named "System Properties". Click on the "Advanced" tab and then click "Environment Variables". (Fig. 5) UNIT-6 WT

163 Figure 5: Editing system properties
UNIT-6 Figure 5: Editing system properties WT

164 Next, another window opens with a lot of confusing sentences and letters. Double-click on the "Path" variable on either of the option boxes. It is recommended to edit the variable in the box "User variables for (your username)". Once the variable is opened, a text box in yet another window appears. Careful not to delete anything in this box. At the end of the text box, add a semi-colon if there is not one already, and add "C:\Program Files\Java\jdk1.6.0\bin" to the text box. This is assuming you did not change the file path of the installation. UNIT-6 WT

165 Click "Apply" and "OK" to all the windows you have just opened
Click "Apply" and "OK" to all the windows you have just opened. Open the command prompt again, while following steps 6-9 to see if that "javac" command works. Congratulations! You have taken your first step to starting Java programming. UNIT-6 WT

166 LECTURE-8 UNIT-6 WT

167 Number one server in the world
- a HTTP webserver :65% of the web sites in the world powered by Apache - the name ‘Apache’ was chosen from ... Why so polular? - FREE ! - highly configurable - implements many features (e.g., security/access control, virtual hosting, CGI script execution) - extensible with third-party modules (e.g., servlet engine, security, …) - flatform independent (support all kinds of machines) Windows, Unix, Linux, Solaris, Mac, etc. UNIT-6 WT

168 Apache -Web Server Apache Software Foundation
- non profit organization - maintains and develops open source programs - protects ‘apache’ brand For more information go to: - UNIT-6 WT

169 Tomcat and Testing Java-based Servlet container with JSP environment
Sublet is in JAVA Apache Foundation's reference implementation of the JavaServer Pages and Servlet technologies Two modes - standalone: default mode for Tomcat - add-on: works as delegator Official Website - UNIT-6 WT

170 What are Java Servlets? Java Technology to address issues in CGI (Common Gateway Interface) Useful when creating the web page on the fly - for web page based on clients’ requests (search engine) - when the data changes frequently (weather report) - when cooperating with database Runs on web server Written in Java and follow a well-standardized API. Fast, efficient, easy Dynamic web contents UNIT-6 WT

171 Processes vs Threads UNIT-6 WT

172 What is JSP? Stands for JavaServlet Page
Extension to the Java servlet technology that allows regular, static HTML (XML) with dynamically-generated HTML(or XML) JSP pages are text documents that have a jsp extension and contain a combination of static HTML and XML like tags and scriptlets. The tags and scriptlets encapsulate the logic that generates the content for the page. JSP pages are pre-processed and compiled into a Java servlet which runs in a webcontainer (e. g. Tomcat). UNIT-6 WT

173 Cons and Pros Tomcat has a lot of pros
However, there are still are cons as a standalone server. - not as fast as Apache for static pages - not as configurable as Apache - not as robust as Apache - may not support functionality found only in Apache modules (e.g., Perl, PHP, security) - mainly for development and debugging UNIT-6 WT

174 Integrating Apache and Tomcat
Apache for a server + Tomcat for Servlet and JSP -> fast and reliable web server Main idea: -let Tomcat listen to Apache - let Apache to talk to Tomcat -apache delegates processing of JSPs, and servlets to the Tomcat instance Problem -how do they communicate? Apache was written in C but Tomcat is written 100% Java -> we need something between them UNIT-6 WT

175 JK Connector Communication mechanism between Tomcat and Apache:
- termed “web server adapter” or “connector” - implemented as library (e.g., mod_jk.dll, mod_jk.so) - uses/manages TCP connections - uses the ajp13 communication protocol (defined in server.xml file in tomcat subdirectory) UNIT-6 WT

176 AND 1 Client 80 Tomcat ajp13 TCP/8009 2 resource 5 3 4 Apache adapter Request Apache delegates Tomcat servicing of JSPs, and servlets 3. Tomcat performs JSPs, and Servlets services 4. Tomcat sends results to Apache 5. Apache sends respond to client UNIT-6 WT

177 Five steps to Install in Windows XP
1. Install Java SDK 2. Build/Install Apache server 3. Build/Install Tomcat 4. Install connector (mod_jk.dll ) 5. Configure 6. Test *assumption: - we want Apache and Tomcat installed as services - we do not want multiple virtual host - you have administrator privileges UNIT-6 WT

178 1. Install JDK Download the latest version of SDK
- Setup the JAVA_HOME environment variable to the root directory where Java SDK is installed (e.g., c:\j2sdk1.4.2_07) Test it in C command prompt by typing “echo %JAVA_HOME%” and make sure it returns the correct value (e.g., j2sdk1.4.2_07) UNIT-6 WT

179 2. Build/Install Apache HTTP
Versions - Apache (since Dec. 2000) and Apache - known as the current stable and the historical stable releases - a full setup package is available as .exe file Download an Apache file for Windows at (e.g., apache_ win32-x86-no_ssl.msi) Follow the instructions provided by installation wizard UNIT-6 WT

180 2. Build/Install Apache HTTP
Specify: - network Domain as “localhost” - server Name as - your address - for All Users, “on Port 80” UNIT-6 WT

181 2. Build/Install Apache HTTP
To test successful installation open your webrowser and type You should see the default Apache webpage running on the port 80 localhost. UNIT-6 WT

182 3. Build/Install Tomcat The latest version is Tomcat 5.5.x.
Grab the Windows EXE distribution for Tomcat at (e.g. tomcat exe) Follow wizard’s instruction Specify: - HTTP/1.1 Connector Port as 8080 - User Name and Passward UNIT-6 WT

183 3. Build/Install Tomcat To test successful installation
open your web browser and type If you can see the default Tomcat webpage running on the port 8080 localhost, bingo! UNIT-6 WT

184 4. Install Connector Download the connector binary at for Windows from a Jakarta mirror site Rename the file to mod_jk.dll (e.g., mod_jk_1.2.5_ dll to mod_jk.dll) Save the rename file in the “modules” directory under where the Apache is installed (e.g., C:\Program Files\Apache Group\modules\mod_jk.dll ) UNIT-6 WT

185 5. Configuation Let the Tomcat listen to Apache
- open server.xml in Tomcat's TOMCAT_HOME/conf directory - all the configuration is done to Tomcat by this file - look for a line that says "Server" and has a port of 8005 - add the following <Listener className="org.apache.ajp.tomcat4.config.ApacheConfig" modJk= UNIT-6 WT

186 "C:\Program Files\ApacheGroup\Apache2\modules/mod_jk.dll" \>
- add the following in the Host container <Listener className="org.apache.ajp.tomcat4.config.ApacheConfig" append="true" forwardAll="false" modJk="C:\Program Files\Apache Group\Apache2\modules\mod_jk.dll" \> UNIT-6 WT

187 5. Configuration 2. Tell Apache to work with Tomcat - run Tomcat and see if a file, “mod_jk.conf” is created in TOMCAT_HOME\conf\auto\mod_jk.conf - mod_jk.conf is an Apache configuration directives for mod_jk - automatically generated by Tomcat each time Tomcat runs due to two lines we added to server.xml - edit httpd.conf in APACHE_HOME/conf by adding Include "C:\Program Files\Apache Group\Tomcat\ Tomcat-4.1\conf\auto\mod_jk.conf” UNIT-6 WT

188 5. Configuration 3. Create a file called workers.properties
- add following in C:\Program Files\Apache Group\Tomcat\Tomcat-4.1\conf\jk worker.list=ajp13 worker.ajp13.port=8009 worker.ajp13.host=localhost worker.ajp13.type=ajp13 - UNIT-6 WT

189 Tomcat instance (running process )waiting to execute servlets for
Apache - multiple Tomcat workers are possible - provides necessary information to mod_jk such as where to find Tomcat and what port to use when connecting. UNIT-6 WT

190 6. Test Start Tomcat Start Apache In the web browser
- verify time stamp on mod_jk.conf Start Start Apache In the web browser - type Apache is working correctly, and JSP and servlet requests are being passed to Tomcat -note that without “:8080” we accessed to Tomcat subdirectory UNIT-6 WT

191 Tomcat File Structure anotherapp TOMCAT webapps index.html WEB-INF
web.xml classes lib examples jsp UNIT-6 WT

192 References Apache Server: http://apache.org
Tomcat: JAVA: Installation: Sublet and JSP Overview: UNIT-6 WT


Download ppt "WEB TECHNOLOGIES – Unit VI"

Similar presentations


Ads by Google