3 December 2021 1 JSP – Java Server Page Name :: Mallikarjuna G D Reach me @ Training :: Email :: gdmallikarjuna@gmail.com
3 December 2021 2 • It is referred as Java Server Pages and it is server side technology. • Separates the graphical design from the dynamic content. • It is helps to develop dynamic web applications • It allows to insert java code within html pages • it first converts to servlet to process the client request and it may be referred as advanced technology of servlet. What is JSP ?
3 December 2021 3 • Web designers can design and update pages without learning java language. • Programmers for java can write code without dealing with web page design. • Allows java to be embedded directly into an HTML page. • Change in the code of JSP compiles automatically. • Using custom tags and tag libraries length of code is reduced. Benefits of JSP
3 December 2021 4 • In servlets, - HTML code is printed from java code. vs • In JSP pages - Java code is embedded in HTML code. JAVA Java HTML HTML Relationships
3 December 2021 5 • JSP-enabled web server: – picks up .jsp page – parses it – converts it to runnable form – runs it. • Converts page to a Java servlet (JspPage), with your code inside the _jspService() method – compiles it – runs servlet protocol. General Lines
3 December 2021 6 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form> <% out.println("welcome to Jsp"); %> </form> </body> </html> Example
3 December 2021 7 JSP Request and Response Cycle User Request Web Server JSP Container Execute Existing Servlet Servlet Container Compile Servlet Generate Servlet code Execute Servlet File Changed Response Response No Yes
3 December 2021 8 JSP Life Cycle _jspService() jspInit() jspDestroy() Request Response Phase Name Description Page Translation The page is parsed and a java file containing the corresponding servlet created. Page Compilation The java file is compiled. Load Class The compiled class is loaded. Create instance An instance of the servlet is created. Call jspInit() This method is called before any other method to allow initialization. Call _jspService() This method is called for each request Call jspDestroy() Called when the servlet container decides to take the servlet out of service. • Has Seven phases. • Slow in loading first time since it has to be translated into servlet, but becomes subsequently faster.
3 December 2021 9 <H1>Current Date</H1> <%= new Date()%> public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType ("text/html"); HttpSession session = request.getSession (true); JspWriter out = response.getWriter(); out.println("<H1>Current Date</H1>"); out.println (new Date()); ... } Translation
3 December 2021 10 • Script language declarations, scriptlets, and expressions for including Java fragments that embed dynamic content • Standard directives guiding translation of a JSP page to a servlet • Standard actions in the form of predefined JSP tags • A portable tag extension mechanism, for building tag libraries— effectively extending the JSP language JSP Features
3 December 2021 11 • Code snippet <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Welcome to JSP World</title> </head> <body> <form> <% out.println("welcome to Jsp"); %> </form> </body> </html> Sample examples
3 December 2021 12 • JSP scripting elements lets you insert Java code into the servlet that will be generated from the JSP page. • There are three forms: 1. Expressions of the form <%= expression %> that are evaluated and inserted into the output, 2. Scriplets of the form <% code %> that are inserted into the servlet's service method, and 3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods JSP Scripting Elements
3 December 2021 13 • A JSP expression is used to insert Java values directly into the output. • It has the following form: <%= Java Expression %> • The Java expression is – evaluated, – converted to a string, and – inserted into the page – Not terminated by “ ; ” • This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request. JSP Expressions
3 December 2021 14 • Code snippet <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.util.Date"%> <html> <head> <title>welcome</title> </head> <body> Current Date : <%=new Date()%> </body> </html> Sample examples
3 December 2021 15 • The following predefined variables can be used: – request, the HttpServletRequest. – response, the HttpServletResponse. – session, the HttpSession associated with the request (if any) – out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client. Predefined Variables
3 December 2021 16 Predefined Variables • Code Snippet pv_login.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1 pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); %> <form name="pvform" method="post" action='<%=path%>/jsp/pv_usage.jsp'> <Table> <th bgcolor=red colspan=2> </th> <tr> <td>Username</td> <td><input type="text" name="txtUsername"></td> </tr> <tr> <td>Password</td><td><input type="text" name="txtPassword"></td> </tr> </Table> <input type="submit" value="submit"> </form> </body> </html>
3 December 2021 17 Predefined Variables • Code Snippet pv_usage.jsp <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>JSP PREDEFINED VARIABLES</title> </head> <body> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.util.Date"%> <form name="pvForm" method="post" action=""> <h2>Predefined Expression Usage</h2> <hr><UL> <LI>CURRENT DATE TAND TIME() : <%=new Date()%></LI> <LI>REQUEST PARAMETER Remote Host : <%=request.getRemoteHost()%></LI> <LI>SESSION ID : <%=session.getId()%></LI> <LI>REQUEST FROM PREVIOUS PAGE : <%=request.getParameter("txtUsername")%> <LI>REQUEST FROM PREVIOUS PAGE : <%=request.getParameter("txtPassword")%> </UL> </form> </body> </html>
3 December 2021 18 • JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page ( _jspService ) • Scriptlets have the following form: <% Java Code %> • Scriptlets have access to the same automatically defined variables as expressions. JSP Scriplets • Scriplets produce output HTML by printing into the out variable • Example: <% String queryData = request.getQueryString(); out.println ("Attached GET data: " + queryData); %>
3 December 2021 19 HTML code before and after the scriplets is converted to print methods: <% if (true) { %> You <B>Are Rocking</B> the game! <% } else { %> Better <B>Luck </B> Next time! <% } %> if (true) { out.println (" You <B>Are Rocking</B> the game! "); } else { out.println (" Better <B>Luck </B> Next time! "); } HTML Code in Scriplets
3 December 2021 20 < %= calculate() %> < % calculate(); % > public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType ("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(calculate()); bar(); ... } (Contd..)
3 December 2021 21 Example <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Scriptlet example</title> </head> <body> <form name="usageScriptletFRM" id="usageScriptletFRM" method="post" action="./usage_scriptlet.jsp"> <% if (request.getParameter("hidCond") == null) { %>
3 December 2021 22 (Contd..) <table> <th colspan="2">Login</th> <tr> <td>USER NAME ::</td> <td><input type="text" name="txtUserName" id="txtUserName“ value=""></td> </tr> <tr> <td>PASSWORD ::</td><td><input type="text" name="txtPassword" id="txtPassword“ value=""></td> </tr> <tr> <td colspan='2'><input type="submit" value="submit"></td> </tr> <input type="hidden" name="hidCond" id="hidCond" value="true"> </table> <% } else { String userName = request.getParameter("txtUserName"); String password = request.getParameter("txtPassword"); out.println("USERNAME :: " + userName + "PASSWORD ::" + password); } %> </form> </body> </html>
3 December 2021 23 Output
3 December 2021 24 • A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request) • It has the following form: <%! Variable or method %> • Declarations do not produce output JSP Declaration
3 December 2021 25 Code Snippet <b>Declaration of Variable</b> <%! int varCount=1000; %> <%= "Value is:"+varCount %> <br> <b>Declaration of Method</b> <%! int add(int firstNum, int secondNum){ return (firstNum+secondNum); }; %> <%= "Additional Value is:"+add(10,20) %> </body> JSP Declaration
3 December 2021 26 • As we have seen before, there are variables that can be used in the code. • There are eight automatically defined variables, sometimes called implicit objects . • The available variables are request, response, out, session, application, config, pageContext, and page. Predefined Variables
3 December 2021 27 Predefined Variables <a href="./jsp/pre_implicit.jsp">Implicit objects</a> Pre_implicit.jsp <form name="pre_implicitFrm" id="pre_implicitFrm" method="post" action="./implicitobjects.jsp"> <% session.setAttribute("userSession", "Mallikarjuna"); pageContext.setAttribute("USER", "Mallik", PageContext.APPLICATION_SCOPE); pageContext.setAttribute("PASSWORD", "Arjun", PageContext.REQUEST_SCOPE); %> <Table> <caption>LOGIN ::</caption> <th bgcolor=red colspan=2></th> <tr><td>Username</td><td><input type="text" name="txtUsername"></td> </tr> <tr><td>Password</td><td><input type="text" name="txtPassword"></td> </tr></Table> <input type="submit" value="submit"> </form> </body> </html> Code snippet
3 December 2021 28 Predefined Variables <style> table, th, td { border: 1px solid black; border-collapse: collapse; } <Table> <caption>IMPLICIT OBJECTS ::</caption> <tr><td>out</td><td>JspWriter</td><td><% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %></td></tr> <tr><td>request</td><td>HttpServletRequest</td><td><%= request.getParameter("txtUsername") %></td></tr> <tr><td>response</td><td>HttpServletResponse</td><td><a href="./implicit_send_redirect.jsp">Test SendRedirect</a></td></tr> <tr><td>session</td><td>HttpSession</td><td><%= (String)session.getAttribute("userSession") %></td></tr> <tr><td>config</td><td>ServletConfig</td><td><a href="../sampleImplicitObj">Test Config</td></tr> <tr><td>application</td><td>ServletContext</td><td><%= application.getInitParameter("DBConn") %></td></tr> <tr><td>pageContext</td><td>pageContext</td><td><%= (String)pageContext.getAttribute("USER",PageContext.APPLICATION_SCOPE) %></td></tr> <tr><td>exception</td><td>Throwable</td><td><a href="./working_implicitobj.jsp">Test Error Page</a></td></tr> </Table> </body> Code snippet
3 December 2021 29 Predefined Variables implicit_send_redirect.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <% response.sendRedirect("https://www.google.com"); %> </body> </html> Code snippet
3 December 2021 30 Predefined Variables web.xml <servlet> <servlet-name>sampleImplicitObj</servlet-name> <jsp-file>/jsp/implicit_config.jsp</jsp-file> <init-param> <param-name>Driver</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>sampleImplicitObj</servlet-name> <url-pattern>/sampleImplicitObj</url-pattern> </servlet-mapping> implicit_config.jsp Implicit Config: <%= config.getInitParameter("Driver") %> Code snippet
3 December 2021 31 Predefined Variables working_implicitobj.jsp <form action="./working.jsp"> Number1:<input type="text" name="first" > Number2:<input type="text" name="second" > <input type="submit" value="divide"> </form> Working.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" errorPage="./error.jsp"%> <% String num1 = request.getParameter("first"); String num2 = request.getParameter("second"); // extracting numbers from request int x = Integer.parseInt(num1); int y = Integer.parseInt(num2); int z = x / y; // dividing the numbers out.print("division of numbers is: " + z); // result %> error.jsp <%@ page isErrorPage="true" %> h3>Sorry an exception occured!</h3> Exception is: <%= exception.getMessage() %> Code snippet
3 December 2021 32 • This is the HttpServletRequest associated with the request • It lets you – look at the request parameters (via getParameter), – the request type (GET, POST, HEAD, etc.), and – the incoming HTTP headers (cookies, etc.) request: • This is the HttpServletResponse associated with the response to the client • The output stream is buffered, • Thus, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client response: (Contd..)
3 December 2021 33 • This is the PrintWriter used to send output to the client. • However, in order to make the response object useful, this is a buffered version of PrintWriter called JspWriter. • Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. out: • This is the HttpSession object associated with the request • Sessions are created automatically, so this variable is bound even if there was no incoming session reference (unless session was turned off using the session attribute of the page directive) session: (Contd..)
3 December 2021 34 • This is the ServletContext as obtained via getServletConfig(). getContext() • Servlets and JSP pages can hold constant data in the ServletContext object • Getting and setting attributes is with getAttribute and setAttribute • The ServletContext is shared by all the servlets in the server application: (Contd..)
3 December 2021 35 • JSP introduced a new class called PageContext. • It encapsulate use of server-specific features like higher performance JspWriters. • The idea is that, if you access the server-specific features through this class rather than directly, your code will still run on "regular" servlet/JSP engines. pageContext: page: • This is simply a synonym for this. • page is not very useful in Java codes in JSP pages. • It was created as a placeholder for the time when the scripting language could be something other than Java. (Contd..)
3 December 2021 36 • A JSP directive affects the overall structure of the servlet class that is created from the JSP page • It usually has the following form: <%@ directive attribute="value" %> • Multiple attribute settings for a single directive can be combined: <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %> JSP Directives
3 December 2021 37 • There are three main types of directive: • page, which lets you do things like: – import classes – customize the servlet superclass • include, which lets you: – insert a file into the servlet class at the time the JSP file is translated into a servlet • taglib directive: – indicates a library of custom tags that the page can include (Contd..)
3 December 2021 38 The page directive lets you define the following attributes: – import="package.class“ <%@ page import="java.util.*" %> – contentType="MIME-Type" <%@ page contentType="text/plain" %> (it is the same as <% response.setContentType("text/plain"); %>) Page Directives
3 December 2021 39 • isThreadSafe=“true|false” – Normal servlet processing or implementing SingleThreadModel • session=“true|false” – Allowing/disallowing sessions • buffer=“sizekb|none” – specifies the buffer size for the JspWriter out • autoflush=“true|false” – Flush buffer when full or throws an exception when buffer isfull • extends=“package.class” • info=“message” – A message for the getServletInfo method • errorPage=“url” – Define a JSP page that handles uncaught exceptions • isErrorPage=“true|false” • language=“java” (Contd..)
3 December 2021 40 • This directive lets you include files at the time the JSP page is translated into a servlet. • Content of the include file is parsed by the JSP at translation time. • Includes a static file. • The directive looks like this: <%@ include file="relative url" %> Include Directive
3 December 2021 41 We can replace the JSP tags with XML tags that represent – Expressions – Scriptles – Declarations – Directives Writing JSP in XML <%= Java Expression %> <% Code %> <%! declaration %> <%@ directive %> <jsp:expression> Java Expression </jsp:expression> <jsp:scriptlet> Code Java </jsp:scriptlet> <jsp:declaration> Java Declaration </jsp:declaration> <jsp:directive.type Attribute = value/>
3 December 2021 42 • JSP actions use constructs in XML syntax to control the behavior of the servlet engine. • You can – dynamically insert a file, – reuse JavaBeans components, – forward the user to another page, or – generate HTML for the Java plugin Actions
3 December 2021 43 Actions Available actions include: – jsp:include :: Include a file at the time the page is requested. – jsp:useBean :: Find or instantiate a Java Bean. – jsp:setProperty:: Set the property of a JavaBean. – jsp:getProperty:: Insert the property of a JavaBean into the output. – jsp:forward :: Forward the requester to a new page . – jsp:plugin :: Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
3 December 2021 44 • This action lets you insert files into the page being generated. • The file inserted when page is requested • The syntax looks like this: <jsp:include page="relative URL" flush="true" /> include Action
3 December 2021 45 • Forwards request to another page. • Syntax: <jsp:forward page="relative URL"/> • It has a single attribute, page, which should consist of a relative URL. • This could be a static value, or could be computed at request time. • Examples: <jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward page="<%= someJavaExpression %>" /> forward Action
3 December 2021 46 • JavaBeans are reusable software components that can be manipulated visually in a builder tool. – Introspaction – analyze how the bean works – Customization – the user can customize the look of the bean – Events support – Properties support – Persistence – allowing saving the bean on a persistent mechanism and loading it Using Beans • The bean Class should include a constructor with no arguments • The bean class should not include public variables (fields) • Access to the attributes of the bean is through methods that look like – getName / setName for non-boolean fields – isName / setName for boolean fields
3 December 2021 47 • This action lets you load in a JavaBean to be used in the JSP page. • The simplest syntax for specifying that a bean should be used is: <jsp:useBean id="name“ class="package.class" /> useBean Action • Create an object of the given class. • Bind the object to a variable with the given name.
3 December 2021 48 <jsp:useBean id=“db” class=“dbiClasses.WebDatabase" /> <% dbiClasses.WebDatabase db = new dbiClasses.WebDatabase(); %> <jsp:useBean id=“handler“ class=“ConnectionHandler" type=“Runnable”/> <% Runnable handler = new ConnectionHandler(); %> (Contd..)
3 December 2021 49 • Creating a Bean with jsp:useBean is like creating an object • The scope of the bean can be beyond the page where it is declared • Beans are used for resource collaboration • Use jsp:getProperty to get a property of a bean • Use the attributes name and property to get the requested property <jsp:getProperty name=“db” property=“login” /> <%= db.getLogin() %> (Contd..)
3 December 2021 50 • Use jsp:setProperty to set a property of a bean. • Use the attributes name, property and value to set the value to the property. <%= db.setLogin (“snoopy”); %> <jsp:setProperty name=“db” property=“login” value=“snoopy”/> (Contd..)
3 December 2021 51 Example package dbiTests; public class SimpleBean { private String message="No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }
3 December 2021 52 (Contd..) <HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> </HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP </TABLE> </CENTER> <P> <jsp:useBean id="test" class=“dbiTest.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello WWW" /> <H1>Message: <I> <jsp:getProperty name="test" property="message" /> </I></H1> </BODY> </HTML>
3 December 2021 53 <jsp:setProperty name=“db” property=“login” value=‘<%= request.getParameter (“login”)%>’ /> Getting value from Request
3 December 2021 54 If we want the value of the parameter dblogin of the request will be set to the bean db automatically we can use: <jsp:setProperty name=“db” property=“login” param=“dblogin” /> Getting Parameter Automatically What will the following do? <jsp:setProperty name=“db” property=“*” /> All Input Parameters:
3 December 2021 55 Sample-include <%out.println("Welcome to " +request.getParameter("companyName")); %> <jsp:forward page="welcome.jsp"></jsp:forward> <jsp:include page="header.jsp" flush="true"> <jsp:param name="companyName" value=“E box training"/> </jsp:include> header.jsp Forward in standard action

Jspprogramming

  • 1.
    3 December 20211 JSP – Java Server Page Name :: Mallikarjuna G D Reach me @ Training :: Email :: gdmallikarjuna@gmail.com
  • 2.
    3 December 20212 • It is referred as Java Server Pages and it is server side technology. • Separates the graphical design from the dynamic content. • It is helps to develop dynamic web applications • It allows to insert java code within html pages • it first converts to servlet to process the client request and it may be referred as advanced technology of servlet. What is JSP ?
  • 3.
    3 December 20213 • Web designers can design and update pages without learning java language. • Programmers for java can write code without dealing with web page design. • Allows java to be embedded directly into an HTML page. • Change in the code of JSP compiles automatically. • Using custom tags and tag libraries length of code is reduced. Benefits of JSP
  • 4.
    3 December 20214 • In servlets, - HTML code is printed from java code. vs • In JSP pages - Java code is embedded in HTML code. JAVA Java HTML HTML Relationships
  • 5.
    3 December 20215 • JSP-enabled web server: – picks up .jsp page – parses it – converts it to runnable form – runs it. • Converts page to a Java servlet (JspPage), with your code inside the _jspService() method – compiles it – runs servlet protocol. General Lines
  • 6.
    3 December 20216 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form> <% out.println("welcome to Jsp"); %> </form> </body> </html> Example
  • 7.
    3 December 20217 JSP Request and Response Cycle User Request Web Server JSP Container Execute Existing Servlet Servlet Container Compile Servlet Generate Servlet code Execute Servlet File Changed Response Response No Yes
  • 8.
    3 December 20218 JSP Life Cycle _jspService() jspInit() jspDestroy() Request Response Phase Name Description Page Translation The page is parsed and a java file containing the corresponding servlet created. Page Compilation The java file is compiled. Load Class The compiled class is loaded. Create instance An instance of the servlet is created. Call jspInit() This method is called before any other method to allow initialization. Call _jspService() This method is called for each request Call jspDestroy() Called when the servlet container decides to take the servlet out of service. • Has Seven phases. • Slow in loading first time since it has to be translated into servlet, but becomes subsequently faster.
  • 9.
    3 December 20219 <H1>Current Date</H1> <%= new Date()%> public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType ("text/html"); HttpSession session = request.getSession (true); JspWriter out = response.getWriter(); out.println("<H1>Current Date</H1>"); out.println (new Date()); ... } Translation
  • 10.
    3 December 202110 • Script language declarations, scriptlets, and expressions for including Java fragments that embed dynamic content • Standard directives guiding translation of a JSP page to a servlet • Standard actions in the form of predefined JSP tags • A portable tag extension mechanism, for building tag libraries— effectively extending the JSP language JSP Features
  • 11.
    3 December 202111 • Code snippet <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Welcome to JSP World</title> </head> <body> <form> <% out.println("welcome to Jsp"); %> </form> </body> </html> Sample examples
  • 12.
    3 December 202112 • JSP scripting elements lets you insert Java code into the servlet that will be generated from the JSP page. • There are three forms: 1. Expressions of the form <%= expression %> that are evaluated and inserted into the output, 2. Scriplets of the form <% code %> that are inserted into the servlet's service method, and 3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods JSP Scripting Elements
  • 13.
    3 December 202113 • A JSP expression is used to insert Java values directly into the output. • It has the following form: <%= Java Expression %> • The Java expression is – evaluated, – converted to a string, and – inserted into the page – Not terminated by “ ; ” • This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request. JSP Expressions
  • 14.
    3 December 202114 • Code snippet <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.util.Date"%> <html> <head> <title>welcome</title> </head> <body> Current Date : <%=new Date()%> </body> </html> Sample examples
  • 15.
    3 December 202115 • The following predefined variables can be used: – request, the HttpServletRequest. – response, the HttpServletResponse. – session, the HttpSession associated with the request (if any) – out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client. Predefined Variables
  • 16.
    3 December 202116 Predefined Variables • Code Snippet pv_login.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1 pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); %> <form name="pvform" method="post" action='<%=path%>/jsp/pv_usage.jsp'> <Table> <th bgcolor=red colspan=2> </th> <tr> <td>Username</td> <td><input type="text" name="txtUsername"></td> </tr> <tr> <td>Password</td><td><input type="text" name="txtPassword"></td> </tr> </Table> <input type="submit" value="submit"> </form> </body> </html>
  • 17.
    3 December 202117 Predefined Variables • Code Snippet pv_usage.jsp <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>JSP PREDEFINED VARIABLES</title> </head> <body> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.util.Date"%> <form name="pvForm" method="post" action=""> <h2>Predefined Expression Usage</h2> <hr><UL> <LI>CURRENT DATE TAND TIME() : <%=new Date()%></LI> <LI>REQUEST PARAMETER Remote Host : <%=request.getRemoteHost()%></LI> <LI>SESSION ID : <%=session.getId()%></LI> <LI>REQUEST FROM PREVIOUS PAGE : <%=request.getParameter("txtUsername")%> <LI>REQUEST FROM PREVIOUS PAGE : <%=request.getParameter("txtPassword")%> </UL> </form> </body> </html>
  • 18.
    3 December 202118 • JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page ( _jspService ) • Scriptlets have the following form: <% Java Code %> • Scriptlets have access to the same automatically defined variables as expressions. JSP Scriplets • Scriplets produce output HTML by printing into the out variable • Example: <% String queryData = request.getQueryString(); out.println ("Attached GET data: " + queryData); %>
  • 19.
    3 December 202119 HTML code before and after the scriplets is converted to print methods: <% if (true) { %> You <B>Are Rocking</B> the game! <% } else { %> Better <B>Luck </B> Next time! <% } %> if (true) { out.println (" You <B>Are Rocking</B> the game! "); } else { out.println (" Better <B>Luck </B> Next time! "); } HTML Code in Scriplets
  • 20.
    3 December 202120 < %= calculate() %> < % calculate(); % > public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType ("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(calculate()); bar(); ... } (Contd..)
  • 21.
    3 December 202121 Example <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Scriptlet example</title> </head> <body> <form name="usageScriptletFRM" id="usageScriptletFRM" method="post" action="./usage_scriptlet.jsp"> <% if (request.getParameter("hidCond") == null) { %>
  • 22.
    3 December 202122 (Contd..) <table> <th colspan="2">Login</th> <tr> <td>USER NAME ::</td> <td><input type="text" name="txtUserName" id="txtUserName“ value=""></td> </tr> <tr> <td>PASSWORD ::</td><td><input type="text" name="txtPassword" id="txtPassword“ value=""></td> </tr> <tr> <td colspan='2'><input type="submit" value="submit"></td> </tr> <input type="hidden" name="hidCond" id="hidCond" value="true"> </table> <% } else { String userName = request.getParameter("txtUserName"); String password = request.getParameter("txtPassword"); out.println("USERNAME :: " + userName + "PASSWORD ::" + password); } %> </form> </body> </html>
  • 23.
    3 December 202123 Output
  • 24.
    3 December 202124 • A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside of the service method processing the request) • It has the following form: <%! Variable or method %> • Declarations do not produce output JSP Declaration
  • 25.
    3 December 202125 Code Snippet <b>Declaration of Variable</b> <%! int varCount=1000; %> <%= "Value is:"+varCount %> <br> <b>Declaration of Method</b> <%! int add(int firstNum, int secondNum){ return (firstNum+secondNum); }; %> <%= "Additional Value is:"+add(10,20) %> </body> JSP Declaration
  • 26.
    3 December 202126 • As we have seen before, there are variables that can be used in the code. • There are eight automatically defined variables, sometimes called implicit objects . • The available variables are request, response, out, session, application, config, pageContext, and page. Predefined Variables
  • 27.
    3 December 202127 Predefined Variables <a href="./jsp/pre_implicit.jsp">Implicit objects</a> Pre_implicit.jsp <form name="pre_implicitFrm" id="pre_implicitFrm" method="post" action="./implicitobjects.jsp"> <% session.setAttribute("userSession", "Mallikarjuna"); pageContext.setAttribute("USER", "Mallik", PageContext.APPLICATION_SCOPE); pageContext.setAttribute("PASSWORD", "Arjun", PageContext.REQUEST_SCOPE); %> <Table> <caption>LOGIN ::</caption> <th bgcolor=red colspan=2></th> <tr><td>Username</td><td><input type="text" name="txtUsername"></td> </tr> <tr><td>Password</td><td><input type="text" name="txtPassword"></td> </tr></Table> <input type="submit" value="submit"> </form> </body> </html> Code snippet
  • 28.
    3 December 202128 Predefined Variables <style> table, th, td { border: 1px solid black; border-collapse: collapse; } <Table> <caption>IMPLICIT OBJECTS ::</caption> <tr><td>out</td><td>JspWriter</td><td><% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %></td></tr> <tr><td>request</td><td>HttpServletRequest</td><td><%= request.getParameter("txtUsername") %></td></tr> <tr><td>response</td><td>HttpServletResponse</td><td><a href="./implicit_send_redirect.jsp">Test SendRedirect</a></td></tr> <tr><td>session</td><td>HttpSession</td><td><%= (String)session.getAttribute("userSession") %></td></tr> <tr><td>config</td><td>ServletConfig</td><td><a href="../sampleImplicitObj">Test Config</td></tr> <tr><td>application</td><td>ServletContext</td><td><%= application.getInitParameter("DBConn") %></td></tr> <tr><td>pageContext</td><td>pageContext</td><td><%= (String)pageContext.getAttribute("USER",PageContext.APPLICATION_SCOPE) %></td></tr> <tr><td>exception</td><td>Throwable</td><td><a href="./working_implicitobj.jsp">Test Error Page</a></td></tr> </Table> </body> Code snippet
  • 29.
    3 December 202129 Predefined Variables implicit_send_redirect.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <% response.sendRedirect("https://www.google.com"); %> </body> </html> Code snippet
  • 30.
    3 December 202130 Predefined Variables web.xml <servlet> <servlet-name>sampleImplicitObj</servlet-name> <jsp-file>/jsp/implicit_config.jsp</jsp-file> <init-param> <param-name>Driver</param-name> <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>sampleImplicitObj</servlet-name> <url-pattern>/sampleImplicitObj</url-pattern> </servlet-mapping> implicit_config.jsp Implicit Config: <%= config.getInitParameter("Driver") %> Code snippet
  • 31.
    3 December 202131 Predefined Variables working_implicitobj.jsp <form action="./working.jsp"> Number1:<input type="text" name="first" > Number2:<input type="text" name="second" > <input type="submit" value="divide"> </form> Working.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" errorPage="./error.jsp"%> <% String num1 = request.getParameter("first"); String num2 = request.getParameter("second"); // extracting numbers from request int x = Integer.parseInt(num1); int y = Integer.parseInt(num2); int z = x / y; // dividing the numbers out.print("division of numbers is: " + z); // result %> error.jsp <%@ page isErrorPage="true" %> h3>Sorry an exception occured!</h3> Exception is: <%= exception.getMessage() %> Code snippet
  • 32.
    3 December 202132 • This is the HttpServletRequest associated with the request • It lets you – look at the request parameters (via getParameter), – the request type (GET, POST, HEAD, etc.), and – the incoming HTTP headers (cookies, etc.) request: • This is the HttpServletResponse associated with the response to the client • The output stream is buffered, • Thus, it is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client response: (Contd..)
  • 33.
    3 December 202133 • This is the PrintWriter used to send output to the client. • However, in order to make the response object useful, this is a buffered version of PrintWriter called JspWriter. • Note that you can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive. out: • This is the HttpSession object associated with the request • Sessions are created automatically, so this variable is bound even if there was no incoming session reference (unless session was turned off using the session attribute of the page directive) session: (Contd..)
  • 34.
    3 December 202134 • This is the ServletContext as obtained via getServletConfig(). getContext() • Servlets and JSP pages can hold constant data in the ServletContext object • Getting and setting attributes is with getAttribute and setAttribute • The ServletContext is shared by all the servlets in the server application: (Contd..)
  • 35.
    3 December 202135 • JSP introduced a new class called PageContext. • It encapsulate use of server-specific features like higher performance JspWriters. • The idea is that, if you access the server-specific features through this class rather than directly, your code will still run on "regular" servlet/JSP engines. pageContext: page: • This is simply a synonym for this. • page is not very useful in Java codes in JSP pages. • It was created as a placeholder for the time when the scripting language could be something other than Java. (Contd..)
  • 36.
    3 December 202136 • A JSP directive affects the overall structure of the servlet class that is created from the JSP page • It usually has the following form: <%@ directive attribute="value" %> • Multiple attribute settings for a single directive can be combined: <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %> JSP Directives
  • 37.
    3 December 202137 • There are three main types of directive: • page, which lets you do things like: – import classes – customize the servlet superclass • include, which lets you: – insert a file into the servlet class at the time the JSP file is translated into a servlet • taglib directive: – indicates a library of custom tags that the page can include (Contd..)
  • 38.
    3 December 202138 The page directive lets you define the following attributes: – import="package.class“ <%@ page import="java.util.*" %> – contentType="MIME-Type" <%@ page contentType="text/plain" %> (it is the same as <% response.setContentType("text/plain"); %>) Page Directives
  • 39.
    3 December 202139 • isThreadSafe=“true|false” – Normal servlet processing or implementing SingleThreadModel • session=“true|false” – Allowing/disallowing sessions • buffer=“sizekb|none” – specifies the buffer size for the JspWriter out • autoflush=“true|false” – Flush buffer when full or throws an exception when buffer isfull • extends=“package.class” • info=“message” – A message for the getServletInfo method • errorPage=“url” – Define a JSP page that handles uncaught exceptions • isErrorPage=“true|false” • language=“java” (Contd..)
  • 40.
    3 December 202140 • This directive lets you include files at the time the JSP page is translated into a servlet. • Content of the include file is parsed by the JSP at translation time. • Includes a static file. • The directive looks like this: <%@ include file="relative url" %> Include Directive
  • 41.
    3 December 202141 We can replace the JSP tags with XML tags that represent – Expressions – Scriptles – Declarations – Directives Writing JSP in XML <%= Java Expression %> <% Code %> <%! declaration %> <%@ directive %> <jsp:expression> Java Expression </jsp:expression> <jsp:scriptlet> Code Java </jsp:scriptlet> <jsp:declaration> Java Declaration </jsp:declaration> <jsp:directive.type Attribute = value/>
  • 42.
    3 December 202142 • JSP actions use constructs in XML syntax to control the behavior of the servlet engine. • You can – dynamically insert a file, – reuse JavaBeans components, – forward the user to another page, or – generate HTML for the Java plugin Actions
  • 43.
    3 December 202143 Actions Available actions include: – jsp:include :: Include a file at the time the page is requested. – jsp:useBean :: Find or instantiate a Java Bean. – jsp:setProperty:: Set the property of a JavaBean. – jsp:getProperty:: Insert the property of a JavaBean into the output. – jsp:forward :: Forward the requester to a new page . – jsp:plugin :: Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
  • 44.
    3 December 202144 • This action lets you insert files into the page being generated. • The file inserted when page is requested • The syntax looks like this: <jsp:include page="relative URL" flush="true" /> include Action
  • 45.
    3 December 202145 • Forwards request to another page. • Syntax: <jsp:forward page="relative URL"/> • It has a single attribute, page, which should consist of a relative URL. • This could be a static value, or could be computed at request time. • Examples: <jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward page="<%= someJavaExpression %>" /> forward Action
  • 46.
    3 December 202146 • JavaBeans are reusable software components that can be manipulated visually in a builder tool. – Introspaction – analyze how the bean works – Customization – the user can customize the look of the bean – Events support – Properties support – Persistence – allowing saving the bean on a persistent mechanism and loading it Using Beans • The bean Class should include a constructor with no arguments • The bean class should not include public variables (fields) • Access to the attributes of the bean is through methods that look like – getName / setName for non-boolean fields – isName / setName for boolean fields
  • 47.
    3 December 202147 • This action lets you load in a JavaBean to be used in the JSP page. • The simplest syntax for specifying that a bean should be used is: <jsp:useBean id="name“ class="package.class" /> useBean Action • Create an object of the given class. • Bind the object to a variable with the given name.
  • 48.
    3 December 202148 <jsp:useBean id=“db” class=“dbiClasses.WebDatabase" /> <% dbiClasses.WebDatabase db = new dbiClasses.WebDatabase(); %> <jsp:useBean id=“handler“ class=“ConnectionHandler" type=“Runnable”/> <% Runnable handler = new ConnectionHandler(); %> (Contd..)
  • 49.
    3 December 202149 • Creating a Bean with jsp:useBean is like creating an object • The scope of the bean can be beyond the page where it is declared • Beans are used for resource collaboration • Use jsp:getProperty to get a property of a bean • Use the attributes name and property to get the requested property <jsp:getProperty name=“db” property=“login” /> <%= db.getLogin() %> (Contd..)
  • 50.
    3 December 202150 • Use jsp:setProperty to set a property of a bean. • Use the attributes name, property and value to set the value to the property. <%= db.setLogin (“snoopy”); %> <jsp:setProperty name=“db” property=“login” value=“snoopy”/> (Contd..)
  • 51.
    3 December 202151 Example package dbiTests; public class SimpleBean { private String message="No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }
  • 52.
    3 December 202152 (Contd..) <HTML> <HEAD> <TITLE>Reusing JavaBeans in JSP</TITLE> </HEAD> <BODY> <CENTER> <TABLE BORDER=5> <TR><TH CLASS="TITLE"> Reusing JavaBeans in JSP </TABLE> </CENTER> <P> <jsp:useBean id="test" class=“dbiTest.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello WWW" /> <H1>Message: <I> <jsp:getProperty name="test" property="message" /> </I></H1> </BODY> </HTML>
  • 53.
    3 December 202153 <jsp:setProperty name=“db” property=“login” value=‘<%= request.getParameter (“login”)%>’ /> Getting value from Request
  • 54.
    3 December 202154 If we want the value of the parameter dblogin of the request will be set to the bean db automatically we can use: <jsp:setProperty name=“db” property=“login” param=“dblogin” /> Getting Parameter Automatically What will the following do? <jsp:setProperty name=“db” property=“*” /> All Input Parameters:
  • 55.
    3 December 202155 Sample-include <%out.println("Welcome to " +request.getParameter("companyName")); %> <jsp:forward page="welcome.jsp"></jsp:forward> <jsp:include page="header.jsp" flush="true"> <jsp:param name="companyName" value=“E box training"/> </jsp:include> header.jsp Forward in standard action