Download presentation
Presentation is loading. Please wait.
Published byMorris Mitchell Modified over 8 years ago
1
JSP Presented by K.Venkata Ratnam HOD MCA (Dept) Newton’s Institute of Engineering
2
JSP: Java Server Page JSP helps in generating dynamic content, based on user input, time of day, or any other runtime conditions. Web application: a program on the server processes requests and generates response. Problems with servlets: 1. Detailed Java programming knowledge is needed. 2. To change the look and feel, change the servlet code and recompile. recompile. 3. Restart the server and run the servlet program
3
Hello world servlet public class HelloWorldServlet implements Servlet{ public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType(“text/html”); PrintWriter out=response.getWriter(); out.println(“ ”); out.println (“ Hello world ”); out.println(“ ”); out.println(“ Hello World ”); out.println(“ It's ”+ (new java.util.date().toString()) + “and all is well”); out.println(“ ”); }
4
Hello world JSP Page Hello world Hello World It,s and all is well.
5
What is JSP? Mostly HTML page, with extension.jsp Include JSP tags to enable dynamic content creation Translation: JSP → Servlet class Compiled at Request time (first request, a little slow) Execution: Request → JSP Servlet's service method
6
Anatomy of a JSP Page A JSP page is a regular web page with JSP elements for generating the parts of the page that differ for each request. JSP separates the request processing and the business logic code from the presentation. In servlet, HTML is embedded, here JSP elements are added to genearate the dynamic content.
7
Life Cycle A JSP page is translated into a Java Servlet And then compiled On Tomcat, the compilation happens the first time a page is requested Above three requests are processed in first request Afterwards, just as fast as a Servlet (because it is then a servlet)
8
Hello World <html> Hello JSP Hello JSP <body> Hello World: Hello World: </p></body></html> See also: Date_jsp.java – the Servlet this page is translated to Date_jsp.java
9
Date_jsp.java (extract) This extract shows the part that produces the output – compare it with the JSP: out = pageContext.getOut(); out = pageContext.getOut(); _jspx_out = out; _jspx_out = out; out.write(" \r\n"); out.write(" \r\n"); out.write(" "); out.write(" "); out.write(" Hello JSP "); out.write(" Hello JSP "); out.write(" "); out.write(" "); out.write(" \r\n"); out.write(" \r\n"); out.write(" Hello World:\r\n "); out.write(" Hello World:\r\n "); out.print( new java.util.Date() ); out.print( new java.util.Date() ); out.write("\r\n"); out.write("\r\n");
10
Produced
11
JSP scripting elements 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 The declarations are inserted into the servlet class, not into a method Used to declare variables and methods
12
Example for Expression Hello! The time is now Note: 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)
13
Scriptlets: It is difficult to do much programming just by putting Java expressions inside HTML. JSP also allows you to write blocks of Java code inside the JSP, by placing your Java code between characters (without the = sign at the start of the sequence.) This block of code is known as a "scriptlet". A scriptlet contains Java code that is executed every time the JSP is invoked. <% // This is a scriptlet. Notice that the "date" // variable we declare here is available in the // embedded expression later on. System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now
14
Mixing Scriptlets and HTML <% int n=5; for ( int i = 0; i < n; i++ ) { %> Number <% } %>
15
Example for JSP Declarations Square root of (x)= <% for(int i=1;i<=10;i++) { out.print("Hello JSP World! "); } %> <%! int mat(int x, int y) { return x*y; }%> <% out.println("Multiplication of(x,y)="); out.println(mat(3,4)+" "); %> Example for Declarations
16
Directives Instructions to the compiler Directives affect the servlet class itself A directive has the form: A directive has the form: The most useful directive is page, which lets you import packages Example: Example:
17
Example for page directive <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now
18
The include directive The include directive inserts another file into the file being parsed The included file is treated as just one more JSP, hence it can include static HTML Syntax: 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 The include directive is used to physically include the contents of another file (compile-time). Example:
19
Example for include directive Going to include time.jsp...
20
Actions Actions are XML-syntax tags used to control the servlet engine Inserts the indicated relative URL at execution time (not at compile time, like the include directive does) This is great for rapidly changing data " /> Jump to the (static) URL or the (dynamically computed) JavaExpression resulting in a URL
21
Example for Example for Example for the
22
login.jsp Login User Authentication User Login <form name=f1 action=“http://localhost:8080/ITWEB/logincheck.jsp”“http://localhost:8080/ITWEB/logincheck.jsp method="post"> UserName : Password :
23
Variables 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:
24
Request and Response Each JSP page has access to two special objects The Request object carries information passed by the HTTP request (e.g. made by the browser) This includes any submitted form data The Response object is used to pass information back to the Client (browser) E.g. response.getWriter() provides an output stream for direct writing to the client
25
Example for Request and Response login.html Login User Authentication User Login UserName : Password :
26
logincheck.jsp Login User Authentication <% response.setContentType(“text/html”); String name=request.getParameter(“uname”); String pass=request.getParameter(“pwd”); if(name==“venkat” && pass==“sneha”) { %> <% } else{ %>
27
JSP to Servlet Communication Example login.jsp Login User Authentication User Login <form name=f1 action=http://localhost:8080/ITWEB/LoginServlet”http://localhost:8080/ITWEB/LoginServlet method=“get"> <table border=1 borderstyle=rigid width=20% cellpadding=5 cellspacing=0 bordercolor=“white”> UserName : Password :
28
LoginServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String name=request.getParameter("uname"); out.println(" "); out.println(" Hello World! "); out.println(" "); out.println(" Welcome Mr/Ms:"+name+“ to our website "); out.println(" "); }
29
JDBC – Java Database Connectivity JDBC is used for accessing databases from Java applications Information is transferred from relations to objects and vice-versa databases optimized for searching/indexing objects optimized for engineering/flexibility JDBC Architecture Java Application JDBC Oracle DB2 MySQL Oracle Driver DB2 Driver MySQL Driver Network We will use this one…
30
ApplicationJDBCDriver Java code calls JDBC library JDBC loads a driver Driver talks to a particular database An application can work with several databases by using all corresponding drivers Ideal: can change database engines without changing any application code (not always in practice)
31
Seven Steps Load the driver Define the connection URL Establish the connection Create a Statement object Execute a query using the Statement Process the result Close the connection
32
Loading the Driver We can register the driver indirectly using the statement Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName loads the specified class When OracleDriver is loaded, it automatically creates an instance of itself registers this instance with the DriverManager Hence, the driver class can be given as an argument of the application
33
An Example // A driver for imaginary1 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // A driver for Oracle Driver driver = new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver(driver); //A driver for MySQL Class.forName("com.mysql.jdbc.Driver"); Oracle MS-Access Registered Drivers MySQL
34
JDBC DRIVERS Type 1 Driver JDBC-ODBC Bridge driver The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. Type 2 Driver Native-API/partly Java driver The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Ex: Oracle will have oracle native API. Type 3 Driver All Java/Net-protocol driver Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers. Type 4 Driver Native-protocol/all-Java driver The Type 4 uses java networking libraries to communicate directly with the database server.
35
Get the user details from the Database getusers.jsp Department of IT Registered User Details <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:itweb"); PreparedStatement psmt =con.prepareStatement("select * from registration"); ResultSet rs=psmt.executeQuery(); out.println(" "); out.println("<table width=65% border=0 cellpadding=0 cellspacing=2 bgcolor=lightblue>"); out.println(" Name Password "); out.println(" Email ID Phone No Sex "); out.println(" Date of Birth Language Address /tr>");
36
while(rs.next()) { out.println(" "); out.println(rs.getString(1)); out.println(" "); out.println(rs.getString(2)); out.println(" "); out.println(rs.getString(3)); out.println(" "); out.println(rs.getString(4)); out.println(" "); out.println(rs.getString(5)); out.println(" "); out.println(rs.getString(6)); out.println(" "); out.println(rs.getString(7)); out.println(" "); out.println(rs.getString(8)); out.println(" "); } out.println(" "); %>
37
addcart.html Welcome to Amazon.com Enter Book Details BookName: Price: Quantity: Amount:  
38
addcart.jsp <% Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:mca"); PreparedStatement psmt =con.prepareStatement("insert into books values(?,?,?,?)"); String bname=request.getParameter("bname"); String price=request.getParameter("price"); String quantity=request.getParameter("quant"); String amount=request.getParameter("amt"); psmt.clearParameters(); psmt.setString(1,bname); psmt.setString(2,price); psmt.setString(3,quantity); psmt.setString(4,amount); psmt.executeUpdate(); out.println("Your Books are added to the Cart successfully"); %>
39
THANKQ TO ALL For Any queries please contact: K.VenkataRatnam MCA, M.Tech(CSE) Assoc.Prof & HOD MCA Email: venkatratnam@newtoninstitutes.com Mobile:+91 9494470845
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.