Download presentation
Presentation is loading. Please wait.
Published byAusten Roberts Modified over 8 years ago
1
Java Server Pages Yes it is Java
2
What you should know HTML Java
3
Getting Familiar with your JSP server There are many such servers available – Blazix from Desiderata Software (1.5 Megabytes, JSP, Servlets and EJBs) TomCat from Apache (Approx 6 Megabytes) WebLogic from BEA Systems (Approx 40 Megabytes, JSP, Servlets and EJBs) WebSphere from IBM (Approx 100 Megabytes, JSP, Servlets and EJBs) Blazix TomCat WebLogic WebSphere
4
Installing Tomcat Download Tomcat Extract content to a convenient location Set CATALNA_HOME, CATALNA_BASE, JAVA_HOME, and JRE_HOME Execute start.bat and shutdown.bat to start and shutdown the tomcat server respectively.
5
First JSP page Hello Save this as first.jsp in CATALINA_HOME/webapps folder You may create subfolders as necessary
6
Adding Dynamic Contents Hello! The time is now The character sequences enclose Java expressions, which are evaluated at run time.
7
How to put more codes in JSP? Scriptlets Scriptlet allows you to write blocks of Java code inside the JSP. <% System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now
8
How to output text from Scriptlet? <% System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% // This scriptlet generates HTML output out.println( String.valueOf( date )); %> out variable is already defined in Scriptlet. The "out" variable is of type javax.servlet.jsp.JspWriter.
9
Yet another pre-defined: request Variable is "request". It is of type javax.servlet.http.HttpServletRequest <% System.out.println( "Evaluating date now" ); java.util.Date date = new java.util.Date(); %> Hello! The time is now <% out.println( date ); out.println( " Your machine's address is “); out.println( request.getRemoteHost()); %>
10
Response pre-defined variable response.sendRedirect( anotherUrl );
11
Mixing HTML and Scriptlet Using out variable to output all the HTML is a tedious task. Use a mixture of HTML and Scriptlet instead Ex: Number
12
JSP Directives We used java.util.Date. Right? Why not this? import java.util.*; and then Date It is possible to use "import" statements in JSPs. How? <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now First Statement is a directive
13
Directives Cont’d A JSP "directive" starts with <%@ characters. Page directive – Include directive – The include directive is used to physically include the contents of another file. – – Going to include hello.jsp... –
14
JSP Declarations The JSP you write turns into a class definition. All the scriptlets you write are placed inside a single method of this class. You can also add variable and method declarations to this class. You can then use these variables and methods from your scriptlets and expressions.
15
How to put declarations To add a declaration, you must use the sequences to enclose your declarations <%! Date theDate = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return theDate; } %> Hello! The time is now
16
Check Servelet Generated for a JSP file by Tomcat Path: if my folder is first – C:\Tomcat7\work\Catalina\localhost\first\org\apa che\jsp public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) throws java.io.IOException, javax.servlet.ServletException { …. } This is the function that includes all your scriptlets Declarations directly go into the class
17
Declarations go in the class as variables and methods
18
Why not changing the values when I refresh the page? Good question Lets study Tomcat class container – By the way what is a container?? Tomcat has three parts – Catalina Catalina is Tomcat's servlet container. Catalina implements Sun Microsystems' specifications for servlet and JavaServer Pages (JSP).servlet containerSun MicrosystemsservletJavaServer Pages – Coyote Coyote is a Connector component for Tomcat that supports the HTTP 1.1 protocol as a web server. This allows Catalina, nominally a Java Servlet or JSP container, to also act as a plain web server that serves local files as HTTP documents – Jasper Jasper is Tomcat's JSP Engine. Jasper parses JSP files to compile them into Java code as servlets (that can be handled by Catalina). At runtime, Jasper detects changes to JSP files and recompiles them.JSP files
19
Web Container A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rightsURL Container manages the life cycle of a Servlet – This will be discussed later when we talk about Servlets
20
Include and forward Tags Going to include hello.jsp... Use and see the difference
21
Sessions HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. JSP provides an object named session in each JSP page You can use session object to keep track of the user
22
Session Cont’d By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. You can disable sessions explicitly –
23
Example 1 2
24
Beans and Form Processing The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. You just need to define a class that has a field corresponding to each field in the form. The class fields must have "setters" that match the names of the form fields. Setters????
25
Setter (Yes Java Class!) public class TestSetter{ Private String name; Private int age; public void setName(String tname) // this is the setter { this.name=tname; } public String getName() // this is the getter { return this.name; }
26
Example What's your name? What's your e-mail address? What's your age?
27
Corresponding Bean Package user; public class UserData { String username; String email; int age; public void setUsername( String value ) { username = value; } public void setEmail( String value ) { email = value; } public void setAge( int value ) { age = value; } Public String getUsername() { return username; } public String getEmail() { return email; } public int getAge() { return age; } } Once you have defined the class, compile it and make sure it is available in the web-server's classpath
28
Where to save this Bean? Put it in WEB-INF\classes folder in your application folder Ex: If you create an application called blog – Create a sub folder in your blog folder as WEB-INF – Create a sub folder in WEB-INF called classes – Put your package in corresponding folders Here UserData.class must be in {Tomcat_home\webapps\blog\}WEB- INF\classes\user\UserData.class
29
"SaveName.jsp“ which handles the request Continue Note: jsp:useBean tag and the jsp:setProperty tag! The useBean tag will look for an instance of the "UserData" in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!
30
Bean Scope Page - accessible only on the page Request – can access within the same requets forwarded page can access it too. Session – throughout the session Application – whole application
31
Scopes cont’d //Example of JSP Page Scope //Example of JSP Request Scope //Example of JSP Session Scope //Example of JSP Application Scope
32
Access the user bean anywhere You entered Name: Email: Age:
33
Controllers pre-processing needs to be done after the user has submitted a form Such pre-processing code is frequently referred to as a "controller“
34
Simple Controller <% String tgtPage = null; if ( user.choice.equals( "choice1" )) tgtPage = "tgt1.jsp"; else if ( user.choice.equals( "choice2" )) tgtPage = "tgt2.jsp"; else tgtPage = "tgtDefault.jsp"; response.sendRedirect( tgtPage ); %>
35
Techniques for Form Editing What's your name? "> What's your e-mail address? "> What's your age? >
36
Servlet Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.
37
dbc@csit.fsu.edu37 Architecture HTTP request HTTP response Web server JSP page JSP container compiles to a servlet URL request JavaBean Library DB properties, call methods HTTP page response Browser
38
Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction. – The servlet is initialized by calling the init () method. – The servlet calls service() method to process a client's request. – The servlet is terminated by calling the destroy() method. – Finally, servlet is garbage collected by the garbage collector of the JVM.
39
The init() method : The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request Used for one time initialization – public void init() throws ServletException { // Initialization code... }
40
The service() method : The service() method is the main method to perform the actual task When requests come from clients, servlet container invokes this method for each request – public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { //Code goes here.}
41
Service Method: Cont’d The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
42
The doGet(), doPost() Methods: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }
43
The destroy() method : The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities – public void destroy() { // Finalization code... }
44
Overview
45
Hello World
46
Explanation Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface Compile – As usual javac HelloWorld.java Servlet Deployment: – Place the class file in …./WEB-INF/classes – Modify web.xml in WEB-INF folder
47
Add this to web.xml Web.xml is in WEB-INF folder. If it is not availabe, create one. HelloWorld HelloWorld HelloWorld /HelloWorld
48
Sample web.xml file
49
Example
50
Example-GET
51
Example-POST
52
Examle-CheckBox
54
Database Connection
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.