JSP JSP stands for Java Servlet Pages , and is a shorthand way of writing simple Servlets, more akin to other web scripting languages like PHP and ASP. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. When you request a .jsp file in a suitable way (see servlet engine and context information below), the JSP file is automatically translated into a proper Java servlet, compiled, and if successful, loaded into the servlet engine and "run" by performing a method call into the servlet class. The generated servlet code (both source and executable forms) is cached to avoid having to regenerate it unnecessarily. Just like a full blown servlet, the servlet generated from a JSP file is able to store context between invocations. In order to understand the JSP framework, we have to clearify two concepts: Java Servlets Java Servlets are special Java classes that can integrate with an enhanced web server and enable you to dynamically generate web pages by executing Java code - effectively running your code "inside the web server". Essentially, a web server can be configured to hand some/all web page requests over to a servlet engine which translates these requests into method calls into Java servlet classes, dynamically loading and initialising them as necessary. The web server and servlet engine may be a single integrated piece of software, or be two separate communicating processes. As such, servlets are a bit similar to other dynamic web page generation programming technologies such as PHP scripts, ASP scripts and the old faithful CGI scripts [written in any language you like]. However, Java Servlets are obviously lots better than any of them because there are lots and lots of lovely "J" words involved. To be serious, there are significant differences - most other web technologies (CGI scripts especially) are one-shot - that is, each time the web server handles a page request, it runs the appropriate CGI script - actually starts executing it, waits for it to finish (gathering all its output) and then returns the output as the result of the page request. This means that a complex web application which involves many steps of filling in web forms ends up running the CGI script many times in different modes or states . Thus, one of the most important aspects of CGI programming is tracking each extended (multi-state) session - making sure that the CGI program can retrieve sufficient information at each stage to know which session it's part of, what stage it's at in that session, and what to do next. Servlets have a fundamentally different lifecycle. Once initialised, a servlet object can handle multiple successive requests while storing per-session information inside instance variables - thus quite neatly solving the session management problem. A servlet engine A servlet engine is a large chunk of Java code that can communicate with a suitably configured web server and handle dynamic loading of servlet classes, compilation of JSP files, initialisation of servlet instances and handling of page requests. Several servlet engines exist - often embedded into commercial middleware software which may include a specialised web server, database access logic, and the servlet engine itself. However, there is an open-source reference implementation servlet engine - Jakarta Tomcat. Tomcat can operate as a full blown web server, or under control of Apache. CSG is running Apache's Jakarta Tomcat engine, version 5.0. This is available on the webserver www-jsp.doc.ic.ac.uk only. In order to make use of this server, you will first have to register a context. It is a directory that contains a single web application - envisaged as a set of related html files, JavaBeans, JSP files, and/or servlets that form a single user experience. CSG allows you to either add a personal context or a group context. The basic idea is that you choose a name and desired location for your new context. Let's suppose that you decide on a context called fred in your ~/public_html directory, Create a ~/public_html/fred directory Create WEB-INF, WEB-INF/lib and WEB-INF/classes subdirectories under ~/public_html/fred. Go to http://www-jsp.doc.ic.ac.uk/csg/servlet/TCContext Add add a new context and simply type your chosen context name (fred) into the textbox in the Add a Personal Context section. After you've registered a context directory and placed some JSP files in it, you must ensure that you access the context via our Tomcat webserver http://www-jsp.doc.ic.ac.uk/. Now you can create .JSP files under ~/public_html/fred. Here are some examples: Put the following text in Hello.jsp and place it into your JSP directory, and browse it from http://www-jsp.doc.ic.ac.uk/~fred: Hello! The time is now <%= new java.util.Date() %> The JSP "request" variable is used to obtain information from the request as sent by the browser. For instance, you can find out the name of the client's host (if available, otherwise the IP address will be returned.) Let us modify the code as shown: <% // This scriptlet declares and initializes "date" 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()); %> A similar variable is "response". This can be used to affect the response being sent to the browser. For instance, you can call response.sendRedirect( anotherUrl ); to send a response to the browser that it should load a different URL. This response will actualy go all the way to the browser. The browser will then send a different request, to "anotherUrl". This is a little different from some other JSP mechanisms we will come across, for including another page or forwarding the browser to another page. Forms are a very common method of interactions in web sites. JSP makes forms processing specially easy. 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. For instance, let us modify our GetName.html to also collect email address and age. To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter" method is just a method that starts with "set" followed by the name of the field. The first character of the field name is upper-cased. So if the field is "email", its "setter" method will be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that the setters (and getters) must be public. Write a java class to collect data 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; } } Compile it in command line by: javac UserData.java And Make sure it is available in the web-server's classpath. Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named user under the classpath entry. Write the following code into SaveName.jsp, which uses a bean to collect the data.
Continue All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag. The useBean tag will look for an instance of the "user.UserData" in the session. If the instance is already there, it will update the old instance. Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it 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! Let us write NextPage.jsp to retrieve the data from bean.
You entered
Name: <%= user.getUsername() %>
Email: <%= user.getEmail() %>
Age: <%= user.getAge() %>
Notice that the same useBean tag is repeated. The bean is available as the variable named "user" of class "user.UserData". The data entered by the user is all collected in the bean. The final step is to put everything into GetName.html: