Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JSP Java Server Pages Apr 3, 2013 A “Hello World” servlet (from the Tomcat installation documentation) public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello World</H1>\n" + "</BODY></HTML>"); } This is mostly Java with a little HTML mixed in } 2 HelloWorld import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld 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("<body>"); out.println("<head>"); out.println("<title>Hello CS764!</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello CS764!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } } Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little HTML mixed in JSP (Java Server Pages) is an alternate way of creating servlets JSP is written as ordinary HTML, with a little Java mixed in The Java is enclosed in special tags, such as <% ... %> The HTML is known as the template text JSP files must have the extension .jsp The HTML is enclosed in out.println( ) statements JSP is translated into a Java servlet, which is then compiled Servlets are run in the usual way The browser or other client sees only the resultant HTML, as usual Tomcat knows how to handle servlets and JSP pages 4 JSP Introduction • JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications. • JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. • JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>. Why Use JSP? • Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files. • JSP are always compiled before it's processed by the server (unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested.) • JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc. • JSP pages can be used in combination with servlets that handle the business logic JSP - Architecture JSP Processing JSP life cycle JSP life cycle JSP Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests. public void jspInit(){ // Initialization code... } JSP Execution: This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } JSP Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. public void jspDestroy() { // Your cleanup code goes here. } The Scriptlet A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Syntax of Scriptlet: <% code fragment %> <jsp:scriptlet> code fragment </jsp:scriptlet> Example: <html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println(“Welcome to JSP”) %> </body> </html> JSP Declarations: A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Syntax of JSP Declarations: <%! declaration; [ declaration; ]+ ... %> <jsp:declaration> code fragment </jsp:declaration> <%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %> JSP Expression: A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. <%= expression %> <jsp:expression> expression </jsp:expression> Example: <html> <head><title>A Comment Test</title></head> <body> <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> </body> </html> Result: Today's date: 11-Sep-2010 21:24:25 JSP Comments: JSP comment marks text or statements that the JSP container should ignore. Syntax: <%-- This is JSP comment --%> Example: <html> <head><title>A Comment Test</title></head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html> JSP scripting elements <%= expression %> <% code %> The expression is evaluated and the result is inserted into the HTML page The code is inserted into the servlet's service method This construction is called a scriptlet <%! declarations %> The declarations are inserted into the servlet class, not into a method 15 JSP Tags Examples Comments <%-- …...text…... --%> Declaration <%! int i; %> <%! int numOfStudents(arg1,..) {} %> Expression <%= 1+1 %> Scriptlets <% … java code … %> include file <%@ include file=“*.jsp” %> …... Example JSP <HTML> <BODY> Hello! The time is now <%= new java.util.Date() %> </BODY> </HTML> Notes: The <%= ... %> tag is used, because we are computing a value and inserting it into the HTML The fully qualified name (java.util.Date) is used, instead of the short name (Date), because we haven’t yet talked about how to do import declarations 17 Variables You can declare your own variables, as usual JSP provides several predefined variables request : The HttpServletRequest parameter response : The HttpServletResponse parameter session : The HttpSession associated with the request, or null if there is none out : A JspWriter (like a PrintWriter) used to send output to the client Example: Your hostname: <%= request.getRemoteHost() %> 18 A First JSP <html> <head></head> <body> <p>Enter two numbers and click the ‘calculate’ button.</p> <form action=“calculator.jsp” method=“get”> <input type=text name=value1><br> Calculator.html <input type=text name=value2 ><br> <input type=submit name=calculate value=calculate> </form> </body> </html> <html> <head><title>A simple calculator: results</title></head> <body> <%-- A simpler example 1+1=2 --%> 1+1 = <%= 1+1 %> <%-- A simple calculator --%> <h2>The sum of your two numbers is:</h2> <%= Integer.parseInt(request.getParameter("value1")) + Integer.parseInt(request.getParameter("value2")) %> </body> </html> Calculator.jsp Scriptlets Scriptlets are enclosed in <% ... %> tags Scriptlets do not produce a value that is inserted directly into the HTML (as is done with <%= ... %>) Scriptlets are Java code that may write into the HTML Example: <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> Scriptlets are inserted into the servlet exactly as written, and are not compiled until the entire servlet is compiled Example: <% if (Math.random() < 0.5) { %> Have a <B>nice</B> day! <% } else { %> Have a <B>lousy</B> day! <% } %> 21 Declarations Use <%! ... %> for declarations to be added to your servlet class, not to any particular method Caution: Servlets are multithreaded, so nonlocal variables must be handled with extreme care If declared with <% ... %>, variables are local and OK Data can also safely be put in the request or session objects Example: <%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %> You can use <%! ... %> to declare methods as easily as to declare variables 22 Exception handling in JSP • These are nothing but the abnormal conditions which interrupts the normal flow of execution. • Mostly they occur because of the wrong data entered by user. • It is must to handle exceptions in order to give meaningful message to the user • So that user would be able to understand the issue and take appropriate action. Exception handling using exception implicit object Index.jsp <%@ page errorPage="errorpage.jsp" %> <html> <head> <title>JSP exception handling example</title> </head> <body> <% //Declared and initialized two integers int num1 = 122; int num2 = 0; //It should throw Arithmetic Exception int div = num1/num2; %> </body> </html> Errorpage.jsp <%@ page isErrorPage="true" %> <html> <head> <title>Display the Exception Message here</title> </head> <body> <h2>errorpage.jsp</h2> <i>An exception has occurred in the index.jsp Page. Please fix the errors. Below is the error message:</i> <b> <%= exception %></b> </body> </html> Exception handling using try catch blocks within scriptlets Error.jsp <html> <head> <title>Exception handling using try catch blocks</title> </head> <body> <% try { //I have defined an array of length 5 int arr[]={1,2,3,4,5}; int num=arr[6]; out.println("7th element of arr"+num); } catch (Exception exp){ out.println("There is something wrong: " + exp); } %> </body> </html> JSP Directives • JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. • A JSP directive affects the overall structure of the servlet class. It usually has the following form: • <%@ directive attribute="value" %> Directive Types DirectiveDescription <%@ page ... %>Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. <%@ include ... %>Includes a file during the translation phase. <%@ taglib ... %>Declares a tag library, containing custom actions, used in the page Directives Directives affect the servlet class itself A directive has the form: <%@ directive attribute="value" %> or <%@ directive attribute1="value1" attribute2="value2" ... attributeN="valueN" %> The most useful directive is page, which lets you import packages Example: <%@ page import="java.util.*" %> 29 The page Directive • The page directive is used to provide instructions to the container that pertain to the current JSP page. • Code page directives anywhere in your JSP page. • By convention, page directives are coded at the top of the JSP page. Syntax of page directive: <%@ page attribute="value" %> <jsp:directive.page attribute="value" /> Page Directive Attribute • • • • • • • • • • • import session isErrorPage errorPage ContentType isThreadSafe extends info language autoflush buffer Page Directive Example <%@ page import="java.util.*" %> <HTML> <BODY> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> </BODY> </HTML> The taglib Directive • The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags • A tag library is a set of user-defined tags that implement custom behavior. The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page. Syntax: <%@ taglib uri="uri" prefix="prefixOfTag" > <jsp:directive.taglib uri="uri" prefix="prefixOfTag" /> JSP Taglib Example The custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be<mytag:hello> Code: <%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %> <html> <body> <mytag:hello/> </body> </html> The include directive The include directive inserts another file into the file being parsed Syntax: <%@ include file="URL " %> The included file is treated as just more JSP, hence it can include static HTML, scripting elements, actions, and directives The URL is treated as relative to the JSP page If the URL begins with a slash, it is treated as relative to the home directory of the Web server The include directive is especially useful for inserting things like navigation bars 35 JSP Include Directive Example Index.jsp <html> <head> <title>Passing Parameters to Include directive</title> </head> <body> <%@ include file="file1.jsp" %> <%! String country="India"; String state="UP"; String city="Agra"; %> <% session.setAttribute("co", country); session.setAttribute("st", state); session.setAttribute("ci", city); %> </body> </html> Output File1.jsp <%=session.getAttribute("co") %> <%=session.getAttribute("st") %> <%=session.getAttribute("ci") %> Output: India UP Agra Actions Actions are XML-syntax tags used to control the servlet engine <jsp:include page="URL " flush="true" /> Inserts the indicated relative URL at execution time (not at compile time, like the include directive does) This is great for rapidly changing data <jsp:forward page="URL" /> <jsp:forward page="<%= JavaExpression %>" /> Jump to the (static) URL or the (dynamically computed) JavaExpression resulting in a URL 38 Directives vs Actions • Directives are used during translation phase while actions are used during request processing phase. • Unlike Directives Actions are re-evaluated each time the page is accessed. JSP Forward Example 1 – without passing parameters Index.jsp Contains <html> <head> <title>JSP forward action tag example</title> </head> <body> <p align="center">My main JSP page</p> <jsp:forward page="display.jsp" /> </body> </html> display.jsp <html> <head> <title>Display Page</title> </head> <body> Hello this is a display.jsp Page </body> </html> JSP Forward Example 2 – with parameters Index.jsp <html> <head> <title>JSP forward example with parameters</title> </head> <body> <jsp:forward page="display.jsp"> <jsp:param name="name" value="Chaitanya" /> <jsp:param name="site" value="BeginnersBook.com" /> <jsp:param name="tutorialname" value="jsp forward action" /> <jsp:param name="reqcamefrom" value="index.jsp" /> </jsp:forward> </body> </html> Display.jsp <html> <head> <title>Display Page</title> </head> <body> <h2>Hello this is a display.jsp Page</h2> My name is: <%=request.getParameter("name") %><br> Website: <%=request.getParameter("site") %><br> Topic: <%=request.getParameter("tutorialname") %><br> Forward Request came from the page: <%=request.getParameter("reqcamefrom") %> </body> </html> <jsp:include> Action • include page directive this action is also used to insert a JSP file in another file. Syntax of <jsp:include> : <jsp:include page="page URL" flush="Boolean Value" /> Example: <html> <head> <title>Demo of JSP include Action Tag</title> </head> <body> <h3>JSP page: Demo Include</h3> <jsp:include page="sample.jsp" flush="false" /> </body> </html> <jsp:forward> Action • <jsp:forward> is used for redirecting the request. • When this action is encountered on a JSP page the control gets transferred to the page mentioned in this action. Syntax of <jsp:forward> : <jsp:forward page="URL of the another static, JSP OR Servlet page" /> Example <html> <head> <title>Demo of JSP Forward Action Tag</title> </head> <body> <h3>JSP page: Demo forward</h3> <jsp:forward page="second.jsp" /> </body> </html> <jsp:param> Action • This action is useful for passing the parameters to Other JSP action tags such as JSP include & JSP forward tag. • This way new JSP pages can have access to those parameters using request object itself. • Syntax of <jsp:param>: <jsp: param name="param_name_here" value="value_of_parameter_here" /> First.jsp <html> <head> <title>Demo of JSP Param Action Tag</title> </head> <body> <h3>JSP page: Demo Param along with forward</h3> <jsp:forward page="second.jsp"> <jsp:param name ="date" value="20-05-2012" /> <jsp:param name ="time" value="10:15AM" /> <jsp:param name ="data" value="ABC" /> </jsp:forward> </body> </html> Second File: Date:<%= request.getParameter("date") %> Time:<%= request.getParameter("time") %> My Data:<%= request.getParameter("data") %> <jsp:useBean> Action This action is useful when you want to use Beans in a JSP page, through this tag you can easily invoke a bean. Syntax of <jsp:useBean>: <jsp: useBean id="unique_name_to_identify_bean" class="package_n ame.class_name> EmployeeTest.jsp <html> <head> <title>JSP Page to show use of useBean action</title> </head> <body> <h1>Demo: Action</h1> <jsp:useBean id="student" class="javabeansample.StuBean"/> <jsp:setProperty name="student" property="*"/> <h1> name:<jsp:getProperty name="student" property="name"/> <br> empno:<jsp:getProperty name="student" property="rollno"/><br> </h1> </body> </html> StudentBean.java package javabeansample; public class StuBean { public StuBean() { } private String name; private int rollno; public void setName(String name) { this.name=name; } public String getName() { return name; } public void setRollno(int rollno) { this.rollno=rollno; } public int getRollno() { return rollno; } } <jsp:plugin> Action • This tag is used when there is a need of a plugin to run a Bean class or an Applet. JSP - Database Access • Understanding on how JDBC application works. • Before starting with database access through a JSP, make sure that you have proper JDBC environment setup along with a database. Create Table mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) ); Query OK, 0 rows affected (0.08 sec) mysql> Create Data Records mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) Connecting JSP To Mysql Database Login.html <body> <form action="login.jsp" method="post"> User name :<input type="text" name="usr" /> password :<input type="password" name="pwd" /> <input type="submit" /></form></body> Reg.html <form action="reg.jsp" method="post“> Email :<input type="text" name="email" /> First name :<input type="text" name="fname" /> Last name :<input type="text" name="lname" /> User name :<input type="text" name="userid" /> password :<input type="password" name="pwd" /> <input type="submit" /></form> Login.jsp <%@ page import ="java.sql.*" %> <%@ page import ="javax.sql.*" %> <% String userid=request.getParameter("user"); session.putValue("userid",userid); String pwd=request.getParameter("pwd"); Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ test","root","root"); Statement st= con.createStatement(); ResultSet rs=st.executeQuery("select * from users where user_id='"+userid+"'"); if(rs.next()) { if(rs.getString(2).equals(pwd)) { out.println("welcome"+userid); } else { out.println("Invalid password try again"); } } else %> Reg.jsp <%@ page import ="java.sql.*" %> <%@ page import ="javax.sql.*" %><% String user=request.getParameter("userid"); session.putValue("userid",user); String pwd=request.getParameter("pwd"); String fname=request.getParameter("fname"); String lname=request.getParameter("lname"); String email=request.getParameter("email"); Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","root"); Statement st= con.createStatement(); ResultSet rs; int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"', '"+lname+"','"+email+"')"); Index.html <HTML> <HEAD> <TITLE>Database Lookup</TITLE> </HEAD> <BODY> <H1>Database Lookup</H1> <FORM ACTION="basic.jsp" METHOD="POST"> Please enter the ID of the publisher you want to find: <BR> <INPUT TYPE="TEXT" NAME="id"> <BR> <INPUT TYPE="SUBMIT" value="Submit"> </FORM> </BODY> <HTML> Basic.jsp <%@ page import="java.sql.*" %> <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); %><HTML> <HEAD> <TITLE>Fetching Data From a Database</TITLE> </HEAD> <BODY> <H1>Fetching Data From a Database</H1> <% Connection connection = DriverManager.getConnection( "jdbc:odbc:data", "YourName", "password"); Statement statement = connection.createStatement(); String id = request.getParameter("id"); ResultSet resultset = statement.executeQuery("select * from Publishers where pub_id = '" + id + "'") ; if(!resultset.next()) { out.println("Sorry, could not find that publisher. "); } else { %> Basic.jsp <TABLE BORDER="1"> <TR> <TH>ID</TH> <TH>Name</TH> <TH>City</TH> <TH>State</TH> <TH>Country</TH> </TR> <TR> <TD> <%= resultset.getString(1) %> </TD> <TD> <%= resultset.getString(2) %> </TD> <TD> <%= resultset.getString(3) %> </TD> <TD> <%= resultset.getString(4) %> </TD> <TD> <%= resultset.getString(5) %> </TD> </TR> </TABLE> <BR> <% } %> </BODY> </HTML> JSP in XML JSP can be embedded in XML as well as in HTML Due to XML’s syntax rules, the tags must be different (but they do the same things) HTML: <%= expression %> XML: <jsp:expression>expression</jsp:expression> HTML: <% code %> XML: <jsp:scriptlet>code</jsp:scriptlet> HTML: <%! declarations %> XML: <jsp:declaration>declarations</jsp:declaration> HTML: <%@ include file=URL %> XML: <jsp:directive.include file="URL"/> 62 The End 63