Introduction to JSP.

Presentation on theme: "Introduction to JSP."— Presentation transcript:

1 Introduction to JSP

2 Introduction JSP is based on the Java technology and is an extension of the Java Servlet technology Platform independence and extensibility of servlets are easily incorporated in JSP Using the Java server-side modules, JSP can fit effortlessly into the framework of a Web server with minimal overhead The use of XML-like tags and Java-like syntax in JSP facilitate building Web- based applications

3 Benefits Platform independence. The use of JSP adds versatility to a Web application by enabling its execution on any computer Enhanced performance. The compilation process in JSP produces faster results or output Separation of logic from display. The use of JSP permits the HTML- specific static content and a mixture of HTML, Java, and JSP to be placed in separate files Ease of administration. The use of JSP eliminates the need for high- level technical expertise Ease of use. All JSP applications run on major Web servers and operating systems

4 Competition JSP versus ASP. The dynamic content of JSP is written in Java, in contrast to that of ASP, which is written using an ASP-specific language JSP versus PHP. PHP is similar to ASP and JSP to a certain extent. With basic HTML knowledge, however, a VBScript programmer can write ASP applications and a Java programmer can create JSP applications, whereas PHP requires learning an entirely new language JSP versus JavaScript. JavaScript is a client-side programming language used to build parts of HTML Web pages while the browser loads a document. As a result, the pages generated in JavaScript create dynamic content that is solely based on the client environment

5 JSP Characteristics JSP is an extension of the Java Servlet technology
It uses Java objects to receive Web requests and subsequently builds and sends back appropriate responses to the browser The compilation of an JSP page generates a servlet that incorporates all servlet functionality

6 Request-Response Cycle

7 JSP and Servlets A JSP file, when compiled, generates a servlet
A JSP file is much easier to deploy because the JSP engine performs the recompilation for the Java code automatically JSP also aims to relieve the programmers from coding for servlets by auto- generation of servlets Servlets and JSP share common features, such as platform independence, creation of database-driven Web applications, and server-side programming capabilities

8 JSP and Servlets Servlets tie up files to handle the static presentation logic and the dynamic business logic independently An HTML file is used for the static content and a Java file for the dynamic content A change made to any file requires the recompilation of the corresponding servlet JSP allows Java code to be embedded directly into an HTML page by using special tags The HTML content and the Java content can also be placed in separate files

9 Compilation Process The compilation of a JSP page builds a request and a response cycle with two phases: the translation phase the request-processing phase When the client requests a JSP page, the server sends a request to the JSP Engine The JSP container compiles the corresponding translation unit Then, the JSP engine automatically generates a servlet This results in the creation of a class file for the JSP page The response is generated according to the request specifications The servlet then sends back the response corresponding to the request received

11 Installation Download an implementation of the Java Software Development Kit (SDK) Set the PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir A number of Web Servers that support JavaServer Pages and Servlets development Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies After a successful startup, the default web-applications included with Tomcat will be available by visiting

12 Creating a JSP Page A JSP page is very similar to an HTML document except for the addition of some tags containing Java code These tags, known as JSP tags, help to differentiate and segregate Following is the syntax of Scriptlet You can write the XML equivalent of the above syntax as follows code fragment

14 Contents of a JSP Page You can categorize the contents of a JSP page as follows: HTML components consisting of HTML tags JSP components consisting of JSP tags The JSP tags can also be broadly classified into the following groups Translation-time tags Comments that are used to provide information about code snippets Directives that are used to convey overall information about a JSP page Request-time tags Scripting elements such as scriplets, expressions, and declarations that consist of Java code snippets Actions that are used to influence the runtime behavior of a JSP

15 Code Execution Copy the code for the page with the acknowledgment message into a text file and save it as e.g., main.jsp Copy main.jsp in the appropriate folder e.g., CATALINA_HOME/webapps/ROOT - c:/Tomcat8/webapps/ROOT Start the Tomcat server Start your browser if it is not already running In the address area of the browser, type The output of your JSP page will be displayed

18 Directives directive attribute="value" %>

24 Requests The request object is an instance of a javax.servlet.http.HttpServletRequest object Each time a client requests a page, the JSP engine creates a new object to represent that request The request object provides methods to get HTTP header information including form data, cookies, HTTP methods, etc

25 Requests Request object methods (examples)
Cookie[] getCookies(). Returns an array containing all of the Cookie objects the client sent with this request Enumeration getAttributeNames(). Returns an Enumeration containing the names of the attributes available to this request HttpSession getSession(). Returns the current session associated with the this request, or if the request does not have a session, creates one Object getAttribute(String name). Returns the value of the named attribute as an Object, or null if no attribute of the given name exists String getParameter(String name). Returns the value of a request parameter as a String, or null if the parameter does not exist

27 Server Response When a Web server responds to a HTTP request, the response typically consists of a status line, some response headers, a blank line, and the document A typical response looks like this HTTP/ OK Content-Type: text/html Header2: HeaderN: . (Blank Line) . .

28 Server Response The response object is an instance of a javax.servlet.http.HttpServletResponse object Just as the server creates the request object, it also creates an object to represent the response to the client The response object also defines the interfaces that deal with creating new HTTP headers

29 Server Response Response object methods (examples)
void addCookie(Cookie cookie). Adds the specified cookie to the response void sendError(int sc). Sends an error response to the client using the specified status code and clearing the buffer void sendRedirect(String location). Sends a temporary redirect response to the client using the specified redirect location URL void setHeader(String name, String value). Sets a response header with the given name and value

30 Server Response

Auto Refresh Header Example


31 Forms JSP handles form data parsing automatically using the following methods getParameter() − You call request.getParameter() method to get the value of a form parameter getParameterValues() − Call this method if the parameter appears more than once and returns multiple values, for example checkbox getParameterNames() − Call this method if you want a complete list of all parameters in the current request getInputStream() − Call this method to read binary data stream coming from the client

36 Cookies A JSP that sets a cookie might send headers that look something like this HTTP/ OK Date: Fri, 04 Feb :03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT; path = /; domain = blabla.com Connection: close Content-Type: text/html If the browser is configured to store cookies, it will then keep this information until the expiry date A JSP script will then have access to the cookies through the request method request.getCookies() which returns an array of Cookie objects

37 Cookies Setting cookies with JSP involves three steps
Step 1: Creating a Cookie object You call the Cookie constructor with a cookie name and a cookie value Cookie cookie = new Cookie("key","value"); Keep in mind, neither the name nor the value should contain white space or any of the following characters [ ] ( ) = , " / : ; Step 2: Setting the maximum age You use setMaxAge to specify how long (in seconds) the cookie should be valid The following code will set up a cookie for 24 hours cookie.setMaxAge(60*60*24); Step 3: Sending the Cookie into the HTTP response headers You use response.addCookie to add cookies in the HTTP response header as follows response.addCookie(cookie);

39 Cookies To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest Use getName() and getValue() methods to access each cookie and associated value Found Cookies Name and Value"); for (int i = 0; i < cookies.length; i++) < cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+"
"); > > else < out.println("

No cookies founds

"); > %>

40 Cookies If you want to delete a cookie, then you simply need to follow these three steps Read an already existing cookie and store it in a Cookie object Set cookie age as zero using the setMaxAge() method to delete an existing cookie Add this cookie back into the response header

41
Sessions JSP makes use of the servlet provided HttpSession Interface By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically Disabling session tracking requires explicitly turning it off by page session = "false" %>

43 Access to Databases Java Server Pages has Standard Tag Library which includes the number of actions for the database access In Java, the retrieval of data from a database is achieved using the Java Database Connectivity (JDBC) API. With the addition of JDBC, Java applications can communicate with a database by using SQL statements

44 Access to Databases The initiation of a connection with the database is a process involving two steps loading the driver and then making a connection Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); Connection con = Drivermanager.getConnection(“url, username, password”); After a connection between the application and the database is established, you use various SQL statements to send simple queries to the database You can create the Statement object by using the createStatement() method Statement stat = con.createStatement();

45 Access to Databases The statement object uses the following methods for querying the database: The execute() method is used to execute a SQL statement that may return multiple results. The executeQuery() method is used to execute a simple select query and return a ResultSet object. The executeUpdate() method is used to execute a SQL INSERT, UPDATE, or DELETE statements

46 Access to Databases The following code snippet illustrates the use of the executeQuery() method of the statement object and the other methods used to establish connectivity with a database Class.forName (“sun.jdbc.odbc.JdbcOdbcdriver”); Connection con=DriverManager.getConnection(“jdbc:odbc:DB”, “sa”, ””); Statement stat=con.createStatement(); stat.executeQuery(“Select * from Counter”);

47 Access to Databases The methods of the ResultSet object can be used to access data from a table Executing a SQL statement usually generates a ResultSet object The API adopts a cursor over the returned data The cursor points to the first row The next() method is used to move the cursor to the next row

48 Access to Databases Create a database
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); con = DriverManager.getConnection(“jdbc:odbc:MyDataSource”,”sa”, “”); Statement stat = con.createStatement(); stat.executeUpdate(“CREATE TABLE Registration” + “( firstName VARCHAR(30), “ + “lastName VARCHAR(30), “ + “ socialsecurity VARCHAR(30), “ + “ apt VARCHAR(30), “ + “ street VARCHAR(30), “ + “ city VARCHAR(20), “ + “ state VARCHAR(20), “ + “ zip VARCHAR(10), “ + “ Homephone VARCHAR(10), “ + “ Id VARCHAR(20), “ + “ annualIncome VARCHAR(20), “ + “ source VARCHAR(30), “ + “ accType VARCHAR(30))”);

49 Access to Databases You can retrieve data from the ResultSet rows by calling the getXX(int cn) Boolean getBoolean() Date getDate() Integer getInt() Short getShort() Long getLong() Float getFloat() String getString() Double getDouble()

50 Access to Databases Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); Connection con = DriverManager.getConnection(“jdbc:odbc:MyDataSource”, “sa”,””); Statement stat=con.createStatement(); ResultSet result=stat.executeQuery(“Select * from Counter”); while(result.next()) < //Retrieves the second column from the result set System.out.println(result.getString(2)); >

51 Access to Databases Connection con = null; try < Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:CoolStocks"); Statement statement = con.createStatement(); ResultSet rs=statement.executeQuery("SELECT * FROM customer"); while ( rs.next() ) < out.println("\n" + rs.getString("id") + ""); out.println("" + rs.getString("lname") + ""); out.println("" + rs.getString("fname") + "\n

52 Thank you for your attention!