Templates for JSP

Source: Internet
Author: User
Tags comments include advantage
js| Template Author: jspfuns
by Scott Ferguson

Introduction
Model frame: Hello, World
Servlet Review
Display Message Board
The mode of the message board
The message board as the attribute of the application
The logic of the message board
Conclusion



Introduction

The powerful advantage of JSP is that it separates the business logic of an application from its introduction. In Smalltalk object-oriented terminology, JSP encourages MVC (Model-view-controller) Web applications. The classes or beans of the JSP is the model, the JSP is the view, and the servlet is the controller.

This example is a simple walls. User login and message. It is also available in the Resin demos

Role implementation
Model A Guestbook of Guests.
View login.jsp for new users
add.jsp for logged-in users.
Controller guestjsp, a servlet to manage.


Model frame: Hello, World

The guestjsp frame passes the "Hello, World" string to the Login.jsp page. This framework establishes the structure for the message board. Specific details will be added below.

This example is compiled to browse to:

Http://localhost:8080/servlet/jsp.GuestJsp

You can see a page like this:

Hello, World

The JSP template is formatted with the processing of the servlet and then passes the processing results to the JSP page.

Forwarding uses a Servlet 2.1 feature of the ServletContext, Getrequestdispatcher (). The request dispatcher lets Servlets forward and include any subrequests on the server. It´s a more flexible replacements for SSI includes. The requestdispatcher can include the results of any page, servlet, or JSP page in a servlet´s page. Guestjsp would use Dispatcher.forward () to the JSP page for formatting.

GuestJsp.java:Skeleton package JSP. guestjsp;

Import java.io.*;
Import java.util.*;

Import javax.servlet.*;
Import javax.servlet.http.*;

/**
* Guestjsp is a servlet controlling user
* Interaction with the guest book.
*/
public class Guestjsp extends HttpServlet {
/**
* Doget handles GET requests
*/
public void Doget (HttpServletRequest req,
HttpServletResponse Res)
Throws Servletexception, IOException
{
Save the message in the request for login.jsp
Req.setattribute ("message", "Hello, World");

Get the Application Object
ServletContext app = Getservletcontext ();

Select Login.jsp as the template
RequestDispatcher disp;
DISP = App.getrequestdispatcher ("login.jsp");

Forward the request to the template
Disp.forward (req, res);
}
}


The servlet and the JSP page communicate with attributes in the HttpRequest object. The skeleton Stores "Hello, World" in the "message" attribute. When Login.jsp starts, it would grab the string and print it.

Since Resin´s JavaScript understands extended Bean patterns, it translates the Request.getattribute ("message") into the Ja Vascript equivalent request.attribute.message.

Login.jsp:Skeleton <%@ page Language=javascript%>

<title><%= Request.attribute.message%></title>

<body bgcolor=´white´>
</body>



Servlet Review
For those coming to JSP from a ASP or CGI background servlets replace CGI scripts taking advantage of java´s strength in Dynamic class loading. A servlet is just a Java class which extends servlet or httpservlet and placed in the proper directory. Resin would automatically load the servlet and execute it.

Doc
Index.html
login.jsp
add.jsp
Web-inf
Classes
Jsp
Guestjsp.class
Guestbook.class
Guest.class
The Url/servlet/classname forwards the request to the servlet invoker. The invoker would dynamically load the Java class classname from Doc/web-inf/classes and try to execute the servlet´s servi Ce method.

Resin checks the class file periodically to the If the class has changed. If So, it would replace the old servlet with the new servlet.

displaying the Guest book

The next step, after getting the basic framework running, are to create the model.

The guestbook model
The guest book are straightforward so I´ve just included the APIs here. It conforms to beans patterns to simplify the JavaScript. The same API would work for HashMap, file-based, and database implementations.

JSP files only have access to the public methods. So a JSP file cannot create a new guestbook and it can´t add a new guest. That´s the responsibility of the guestjsp servlet.

Jsp. Guest.java API package JSP;

public class Guest {
Guest ();
Public String getName ();
Public String getcomment ();
}


Resin´s JavaScript recognizes Bean patterns. So JSP pages using JavaScript can access GetName () and Getcomment () as properties. For example, can simply use Guest.name and guest.comment

Jsp. Guestbook.java API package JSP;

public class Guestbook {
Guestbook ();
void Addguest (string name, string comment);
Public iterator iterator ();
}


Resin´s JavaScript also recognizes the iterator () call-so-can-use-javascript for ... the guests:

For (Var guest in guestbook) {
...
}



Guestbook as application attribute
To keep the example simple, guestjsp stores the guestbook in the application (ServletContext). As a example, storing data in the application are acceptable but for full-fledged applications, it´s better just to use th e application to cache data stored elsewhere.

Jsp. Guestjsp.java//Get the Application object
ServletContext app = Getservletcontext ();

Guestbook Guestbook;

The guestbook is stored in the application
Synchronized (APP) {
Guestbook = (Guestbook) app.getattribute ("Guest_book");

If It doesn´t exist, create it.
if (guestbook = = null) {
Guestbook = new Guestbook ();
Guestbook.addguest ("Harry Potter", "Griffindor Rules");
Guestbook.addguest ("Draco Malfoy", "Slytherin Rules");
App.setattribute ("Guest_book", guestbook);
}
}

RequestDispatcher disp;
DISP = App.getrequestdispatcher ("login.jsp");

Synchronize the application so the JSP file
Doesn´t need to worry about threading
Synchronized (APP) {
Disp.forward (req, res);
}


The JSP file itself is simple. It grabs the "guest book" from the application and displays to the contents in a table. Normally, application objects need to be synchronized because and several clients may simultaneously browse the same page. Guestjsp has taken care of synchronization before the JSP file gets.

Login.jsp:Display Guest Book <%@ page Language=javascript%>

<title>hogwarts Guest book</title>

<body bgcolor=´white´>

<table>
&LT;TR&GT;&LT;TD width=´25%´><em>name</em><td><em>comment</em>
<%
var guestbook = Application.attribute.guest_book

For (Var guest in guestbook) {
Out.writeln ("<tr><td>" + guest.name + "<td>" + guest.comment);
}
%>
</table>

</body>


Hogwarts Guest Book
Name Comment
Harry Potter Griffindor Rules
Draco Malfoy Slytherin Rules



Guest book Logic

The guest book logic are simple. If the user has not logged in, she sees comments and a form to log in. After login, she´ll the comments and a form to add a comment. login.jsp Formats the login page and add.jsp formats the Add Comment page.

Guestjsp stores login information in the session variable.

Form Variable Meaning
Action´login´to Login Or´add´to Add a comment
Name User name
Password user password
Comment Comment for the guest book

Guest Book Logic ...

Name from the session
String sessionname = session.getvalue ("name");

Action from the forms
String action = request.getparameter ("action");

Name from the login.jsp form
String userName = request.getparameter ("name");

Password from the login.jsp form
String Password = request.getparameter ("password");

Comment from the add.jsp form
String comment = request.getparameter ("comment");

Login stores the user in the session
if (Action!= null && action.equals ("login") &&
UserName!= NULL &&
Password!= null && password.equals ("Quidditch")) {
Session.putvalue ("name", UserName);
}

Adds a new guest
if (Action!= null && action.equals ("add") &&
SessionName!= NULL &&
Comment!= null) {
Guestbook.addguest (sessionname, comment);
}

String template;
If not logged in, use login.jsp
if (Session.getvalue ("name") = = null)
Template = "login.jsp";
If logged in, use add.jsp
Else
Template = "add.jsp";

RequestDispatcher disp;
DISP = App.getrequestdispatcher (template);

...


Login.jsp and add.jsp just append different forms to the display code in the previous section.

login.jsp <%@ page Language=javascript%>
<title>hogwarts Guest book:login</title>
<body bgcolor=´white´>

<table>
&LT;TR&GT;&LT;TD width=´25%´><em>name</em><td><em>comment</em>
<%
var guestbook = Application.attribute.guest_book

For (Var guest in guestbook) {
Out.writeln ("<tr><td>" + guest.name + "<td>" + guest.comment);
}
%>
</table>

<form action=´guestjsp´method=´post´>
<input Type=hidden name=´action´value=´login´>
<table>
<tr><td>name:<td><input name=´name´>
<tr><td>password:<td><input name=´password´type=´password´>
<tr><td><input Type=submit value=´login´>
</table>
</form>
</body>



Conclusion

The Resin demo shows a few ways to extend the "guest book", including adding the some intelligence to the form processing. However, as forms get more intelligent, even JSP templates become complicated. There is a solution:xtp templates.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.