Top Banner
JSP Features & Syntax Scripting Elements Scripting elements allow Java code to be written directly into the JSP page. It is compiled and available within the page. There are three kinds of scripting elements: declarations expressions scriplets 1.Declarations Declarations are used to define variables and methods -- both instance and static -- that are likely to be repeated. Thus, they correspond to writing code at the Java Class level. They can also be used to overwrite jspInit or Advanced JAVA Lab Manual Dept., of MCA GRIET
48
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: JSP

JSP Features & Syntax

Scripting Elements

Scripting elements allow Java code to be written directly into the JSP page.  It is compiled and available within the page.  There are three kinds of scripting elements:

declarations expressions scriplets

1.Declarations

Declarations are used to define variables and methods -- both instance and static -- that are likely to be repeated.  Thus, they correspond to writing code at the Java Class level. They can also be used to overwrite jspInit or jspDestroy methods that are created when the JSP is compiled.

The basic form is:

<%! Java variable or method %>

Example:

<%! String message; %>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 2: JSP

or

<% String message = "Hello, World, from JSP"; %>

2. Expressions

Expressions are references to variables, methods, or composable structures of such.  They are most often used as a way of dynamically inserting a value into a parameter slot. You may also think of them as representing a call to a static method.  They are evaluated at run time and the results inserted into the output stream at the location of the expression.

The basic form is:

<%= Java expression %>

Example:

<h2><font color= " #AA0000 " > <%=message %></font></h2>

Note that expressions do not include a semicolon(;).

3. Scriplets

Scriplets are sections of Java code that are executed in place.  They can be as simple as a declaration of

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 3: JSP

a variable that is treated as an instance variable, but they can also include loops that mix Java and HTML.

The basic form is:

<% Java code %>

Example:

<% if ( sessionBean.getLoginType() == 0 ) { %>

     <p align="center"><B>Super User</B></p>

<%} else if ( sessionBean.getLoginType() == 1 ) {%>

     <p align="center"><B>Administrative User</B></p>

<%} else if ( sessionBean.getLoginType() == 2 ) {%>

     <p align="center"><B>Author User</B></p>  

<%} else {%>

     <p align="center"><B>Registered User</B></p>

<%} %>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 4: JSP

Implicit Objects

Several local variables are available to scriptlets and expressions through the ServletContext.  They include the following:

application config session request response out page pageContext exception

Most are self-explanatory.  Application, which is the ServletContext of the JSP and stores attributes for the duration of the application..  Page is the current jsp page and stores attributes associated wit the current page.  Out is a writer that can be used by scriplets to put information onto the output stream.

Directives

Directives are instructions to the JSP compiler.  The three types of directives are:

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 5: JSP

page include taglib

Only the include directive will be discussed here.

The include directive instructs the JSP compiler to fetch the file referenced in the directive and insert it into the page at that point.  Thus, it can be used to include standard boilerplate, such as headers and footers.

The basic form is:

<%@ directive %>

Example:

<%@ include file="header.html" %>

If the included file is HTML, it should not repeat any HTML HEAD or BODY tags that may already be defined in the output stream.

Actions

Actions are JSP tags that transfer control to other server objects or perform operations on other objects.  They may also generate output.  They are another means of building view objects within a M - V - C architecture.  There are some half-dozen

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 6: JSP

action tags. The three that will be discussed here are:

include forward useBean

All are marked by tags that have the following form:

<jsp:action attributes />

Include

The include tag is very similar to the include directive, discussed above.  It allows content to be included in place.  The content may be either static or dynamic. 

Here is an example:

<jsp:include page="header.html" flush="true"/>

Forward

The forward tag transfer control to a static or dynamic resource, usually referenced by a URL, that exists on the same server.

The basic form is:

<jsp:forward page="forward_page.html"/>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 7: JSP

Example:

<jsp:forward page="forward_page.html" flush="true"/>

UseBean

The useBean action is by far the most powerful and the most complex of the JSP actions.  It allows a JSP to create an instance or receive an instance of a Java Bean. 

The JSP could provide typical servlet controller functions by passing the request object to the bean and allowing it to extract user parameters and call back-end functions, just like a servlet.  However, supporting those functions in a servlet is generally considered a better practice.  However, rather than transferring result values to another type, such as a Hash table, and passing that object to a JSP, if a back-end process returned a result bean back to a controller servlet, it could simply pass this bean to the relevant JSP.

In fact, so long as the Java server supports it and is properly configured, it permits beans to be passed from servlet to JSP, to another JSP, to another servlet, etc.  This is called chaining and is an

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 8: JSP

architecture used to provide incrementally processing using filtering principles.

JSP Page Scopes

 All jsp objects exist within a particular scope or context.  There are four jsp scopes:

page request session application

Request and session should be familiar.  Page is the current jsp page.  Application is the current overall application and can include multiple sessions.  Thus, all users sharing a given application, who may be associated with different sessions, would have access to the same set of application-scope resources.

Programs

-------------

1. HelloWorld.jsp

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 9: JSP

------------------------<HTML><HEAD><TITLE>Hello Program </TITLE></HEAD> <body> <h1>Hello World message from Ganapathi Raju</h1> <!-- This is JSP comment --> <%out.println("Hello World");%> </body><html>

2. a.jsp----------- <body> <% @ page language="Java" %> <% out.println("hello world");%> </body>

Note: example of Declarations of var:- ---------------------------------------------- <%! int a; %> <%! int a=50; %> <%! int a=50,b=100; %> <%! int a=75;String s="Ganesh"; %> <%! int a=50;float f=10.2f;%>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 10: JSP

4.decl.jsp--------<HTML><HEAD><TITLE>JSP Declarations</TITLE></HEAD>

<BODY><H1>JSP Declarations</H1>

<%! private int accessCount = 0; %><H2>Accesses to page since server reboot: <%= ++accessCount %></H2>

</BODY></HTML>

5.Loop.jsp-------------

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 11: JSP

<body> <% for (int i=0;i<5;i++){%> <b>Hello</b><br> <%}%></body>

(or)

<body> <% for (int i=0;i<5;i++){ out.println("<b>Hello</b><br>"); }%></body>

6.Expr1.jsp-------------

<body> <h1>Data in various sizes</h1> <%for(int i=1;i<7;i++){%> <font size=<%=i%>>Hello in size<%=i%> </font> <br> <%}%> </body>

7.Expr2.jsp

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 12: JSP

-----------------<% String c[]={"red","green","blue","yellow"};%><% for(int i=0;i<c.length;i++){%> <font size=<%=i+1%>Color=<%=c[i]%>>Hello</font> <br> <%}%>

// program with page directive8.Excel.jsp--------<%@ page contentType="application/vnd.ms-excel" %><%-- Note that there are tabs, not spaces, between columns. --%>1997 1998 1999 2000 2001 (Anticipated)12.3 13.4 14.5 15.6 16.7

9.Ex.html----------<body> here specify the format either "excel" or "html" <form name="f1" action="ApplesAndOranges.jsp"> <br><input type="text" name="format" ><br>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 13: JSP

<input type="submit"></body>

Ex.jsp-----------<HTML><HEAD><TITLE>Comparing Apples and Oranges</TITLE></HEAD><BODY><CENTER><H2>Comparing Apples and Oranges</H2>

<% String format = request.getParameter("format");if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel");} %><TABLE BORDER=1> <TR><TH></TH><TH>Apples<TH>Oranges

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 14: JSP

<TR><TH>First Quarter<TD>2307<TD>4706 <TR><TH>Second Quarter<TD>2982<TD>5104 <TR><TH>Third Quarter<TD>3011<TD>5220 <TR><TH>Fourth Quarter<TD>3055<TD>5287</TABLE></CENTER></BODY></HTML>

//Program with Method Declaration and call10 met.jsp ------------ <body> <%! public int mysum(int a,int b)

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 15: JSP

{ return a+b; }

%> <%out.println("<h1>sample method invocation</h1>"); int a=mysum(10,20); out.println("data is "+a);%><br><b> <%out.println(" sum is "+mysum(100,300);%> </b> </body>

// HTML TO JSP INTERACTION.

11. page1.html --------- <body> <form action="rec.jsp"> Name:-<input type="text" name="t1"><br> <input type="submit" name=b1 value="send"> </form> </body>

rec.jsp -----------

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 16: JSP

<body> <h1>JSP TO RECEIVE DATA FROM HTML</h1> <% String s1=request.getParameter("t1";%> <% if(s1.equal("")) response.sendRedirect("error.jsp");%> <b> Data received is <%=s1%>from html</b> </body>

// 12.JSP to Database Connectity-------------------------------------------------

a) JSP PROGRAM to insert data into the data base using method:-

Html prg:-<html> <head> <title> Insert data into the database </title> </head> <body bgcolor="grey" background="a.jpg"> <form name="f1" action="r.jsp"> <div align="center"> <h2>Inserting Data into the data base</h2><hr>

<table border=0 >

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 17: JSP

<tr><td>No:- <input type="text" name="t1"></td>

<tr><td>Name:- <input type="text" name="t2"></td>

<tr> <td><input type="submit" value="insert"><td></tr> </div> </form> </body> </html>

JSP prg:-

<body background="a.jpg"><%@ page language="java" contentType="text/html" %><%@ page import ="java.sql.*" %><%! public int insertRec (String a,String b) {try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection c = DriverManager.getConnection("jdbc:odbc:mydsn1");Statement st = c.createStatement();int i = st.executeUpdate("insert into e values("+a+",'"+b+"')");

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 18: JSP

st.close();c.close();return i;}catch(Exception e){System.out.println("exception "+e);return 0;}} %><% String s1 = request.getParameter("t1"); String s2=request.getParameter("t2"); int i = insertRec(s1,s2);

out.println(i+"record(s) posted to the database"); %></body>

12 b) JSP PROGRAM TO SELECT DATA FROM DATABASE

HTML PRG:-

<html> <head> <title> Read data from data base </title> </head> <body bgcolor="grey" background="a.jpg">

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 19: JSP

<form name="f2" action="r1.jsp"> <div align="center"> <h2>getting data from database</h2><hr>

<table border=0 > <tr> <td><input type="submit"

value="select"><td></tr> </div> </form> </body> </html>

JSP PRG:-

<html><head><title >Table values are</title></head><body background="a.jpg"><%@ page language="java" contentType="text/html" %><%@ page import ="java.sql.*" %><h1><center> Tables values are</h1><hr><table border="2" cellspacing="10" cellpadding="10"><tr><th>Eno</th><th>Ename</th></tr><%{try

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 20: JSP

{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection c = DriverManager.getConnection("jdbc:odbc:mydsn1");Statement st = c.createStatement();ResultSet rs=st.executeQuery("select eno,ename from e");while(rs.next()) {System.out.println("1"); %><tr><td><%=rs.getString("eno")%></td><td><%=rs.getString("ename")%><br></td></tr><% }st.close();c.close();}catch(Exception e){System.out.println("exception "+e);}} %></center></table></body>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 21: JSP

<%--13. Example on JSP design pattern: Composite Viewused elements are:include directive & jsp:include--%><!--Header.html--><HTML><BODY><TABLE><TR><TD width="20%"><IMG src="IBM-logo.jpg"/></TD><TD>Home|AppServer|Examples|About Us</TD></TR>

<!--Menu.html--><OL> <LI>Home</LI> <LI>AppServer</LI> <LI>Examples</LI> <LI>About Us</LI></OL>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 22: JSP

<!--BodyContent.html--><P><CENTER>Sample text placed in body content area</CENTER></P>

<!--Footer.html--><TR><TD><CENTER>Griet</CENTER></TD></TR></TABLE></BODY></HTML>

<!--CompositeView.jsp--><%@ include file="Header.html"%><TR><TD width="20%"><%@ include file="Menu.html"%></TD><TD><%@ include file="BodyContent.html"%></TD></TR><jsp:include page="Footer.html"/>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 23: JSP

JSP Programs with Beans--------------------------------

// 14. program shows how to use beans with JSP

//This application combines seperates control layers and presentation layers of MVC.

/*Example on jsp:useBean*/jsp\EmpQuery.jsp\WEB-INF\classes\beans\EmpBean.java

<!--EmpQuery.html--><FORM action="./EmpQuery.jsp">Empno <INPUT type="text" name="empno" value=""><INPUT type="submit" name="submit" value="Submit"></FORM>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 24: JSP

<!--EmpQuery.jsp--><jsp:useBean id="emp" class="beans.EmpBean"><jsp:setProperty name="emp" property="empno" value="<%=Integer.parseInt(request.getParameter(\"empno\").trim())%>"/><jsp:getProperty name="emp" property="ename"/><BR><jsp:getProperty name="emp" property="job"/><BR><jsp:getProperty name="emp" property="sal"/><BR></jsp:useBean>

// EmpBean.javaimport java.io.*;public class EmpBean implements Serializable{private int empno;private String ename, job;private double sal;public EmpBean(){}

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 25: JSP

/*public void setEmpno(int empno){this.empno=empno;}*/public void setEname(String ename){this.ename=ename;}public void setJob(String job){this.job=job;}public void setSal(double sal){this.sal=sal;}public int getEmpno(){return empno;}public String getEname(){return ename;}public String getJob(){

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 26: JSP

return job;}public double getSal(){return sal;}public void setEmpno(int empno){this.empno=empno;try{Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

java.sql.Connection con=java.sql.DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger");

java.sql.Statement stmt=con.createStatement();

java.sql.ResultSet rs=stmt.executeQuery("select empno, ename, job, sal from emp where empno="+empno);

if(rs.next()){this.ename=rs.getString(2);this.job=rs.getString(3);this.sal=rs.getDouble(4);

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 27: JSP

}// if()rs.close();stmt.close();con.close();}// trycatch(Exception e){e.printStackTrace();}// catch()}// setEmpno()}// class

<!--15.This application seperates business logic and control layers from presentation layer-->

<!--EmpQuery.html--><FORM action="./EmpQuery1.jsp">Empno <INPUT type="text" name="empno" value=""><INPUT type="submit" name="submit" value="Submit"></FORM>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 28: JSP

<!--EmpQuery1.jsp--><jsp:useBean id="emp" class="beans.EmpBean" scope="session"><jsp:setProperty name="emp" property="empno" value='<%=Integer.parseInt(request.getParameter("empno").trim())%>'/><jsp:forward page="EmpResult1.jsp"/></jsp:useBean>

<!--EmpResult1.jsp--><%beans.EmpBean emp=(beans.EmpBean)pageContext.getAttribute("emp",pageContext.SESSION_SCOPE);%><TABLE border="1" align="center"><TR><TH>EMPNO</TH><TH>ENAME</TH><TH>SAL</TH><TH>JOB</TH></TR><TR>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 29: JSP

<TD><%=emp.getEmpno()%></TD><TD><%=emp.getEname()%></TD><TD><%=emp.getSal()%></TD><TD><%=emp.getJob()%></TD></TR></TABLE>

// EmpBean.javaimport java.io.*;public class EmpBean implements Serializable{private int empno;private String ename, job;private double sal;public EmpBean(){}/*public void setEmpno(int empno){this.empno=empno;}*/public void setEname(String ename){this.ename=ename;}public void setJob(String job)

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 30: JSP

{this.job=job;}public void setSal(double sal){this.sal=sal;}public int getEmpno(){return empno;}public String getEname(){return ename;}public String getJob(){return job;}public double getSal(){return sal;}public void setEmpno(int empno){this.empno=empno;try{

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 31: JSP

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

java.sql.Connection con=java.sql.DriverManager.getConnection("jdbc:odbc:mydsn", "scott", "tiger");

java.sql.Statement stmt=con.createStatement();

java.sql.ResultSet rs=stmt.executeQuery("select empno, ename, job, sal from emp where empno="+empno);

if(rs.next()){this.ename=rs.getString(2);this.job=rs.getString(3);this.sal=rs.getDouble(4);}// if()rs.close();stmt.close();con.close();}// trycatch(Exception e){e.printStackTrace();}// catch()}// setEmpno()}// class

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 32: JSP

16. Program to implement strict MVC architecture .MVC:View: Presentation logicBusiness logic: validates user I/P data with all required conditionsControl: which controls flow of execution between MVBModel: access DB

Note1: In MVC arch business logic and control layers are combined into one layerNote2: In classic MVC Model 2 arch business logic seperated from control control

Preferable way of utilizing web components in MVC & MVC 2:JSP/HTML - ViewServlets - ControlJavaBeans - Business logic & model

jsp\EmpQuery.htmlEmpResult.jsp\WEB-INF\web.xml.\classes\EmpQueryServlet

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 33: JSP

.\beans\EmpBean.java

<!--EmpQuery.html--><FORM action="./empQueryServlet">Empno <INPUT type="text" name="empno" value=""><INPUT type="submit" name="submit" value="Submit"></FORM>

<!--EmpResult.jsp--><%beans.EmpBean bean=(beans.EmpBean)session.getAttribute("emp");%><TABLE border="20" align="center"><TR><TD><%=bean.getEmpno()%></TD><TD><%=bean.getEname()%></TD><TD><%=bean.getSal()%></TD><TD><%=bean.getJob()%></TD></TR></TABLE>

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 34: JSP

// EmpQueryServlet.javaimport javax.servlet.*;import javax.servlet.http.*;import java.io.*;import beans.*;public class EmpQueryServlet extends HttpServlet{public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{int empno=Integer.parseInt(req.getParameter("empno").trim());EmpBean bean=new EmpBean();bean.setEmpno(empno);

req.getSession().setAttribute("emp", bean);getServletContext().getRequestDispatcher("/EmpResult.jsp").forward(req,resp);

}// service()}// class

web.xml---------

Advanced JAVA Lab Manual Dept., of MCA GRIET

Page 35: JSP

<web-app><servlet><servlet-name>empQueryServlet</servlet-name><servlet-class>EmpQueryServlet</servlet-class></servlet><servlet-mapping><servlet-name>empQueryServlet</servlet-name><url-pattern>/empQueryServlet</url-pattern></servlet-mapping></web-app>

Advanced JAVA Lab Manual Dept., of MCA GRIET