If you are using Java servlets directly, you will have to process HTTP input and HTML output in the Java class. You need rich Java programming experience to build complex applications. The addition of JSP allows you to distinguish the HTML expression logic from the complicated business logic embedded in servlets. This means that the expression-layer code can be written by experienced script writers, while advanced Java developers can concentrate on solving more complex problems in servlets and beans.
JSP can be used no matter whether you have any Java programming knowledge. JSP contains some server labels so that dynamic data can be displayed without writing a line of Java code. You can directly access the bean to complete the operation, and then use the JSP tag to display the result as dynamic content. You can also use servlets to generate beans, and the operation results of the servlets operation are stored in them. Then, you can use JSP labels to display the results without writing Java code on the JSP page.
There are three ways to add Java code to Your webpage:
1. Using declarations (Declaration), you can define global variables or Java methods that can be accessed anywhere on the page. The Declaration is included in the tag <% !... %>.
2. Using scriptlets (script snippets), you can write any logic required for processing in the page, which is included in the <%... %> tag.
3. Expressions (expression), included in <% =... %>. It provides a simple method to display the results of Java expressions. The appended expression is calculated and displayed on the page, as if you have explicitly written the value of the calculation result in the code.
In your own code, you can use some implicit variables-predefined Java objects provided by JSP. In addition, JSP commands (directives) can contain non-Java code modules, such as HTML text from other files.
Let's take a closer look at these script elements, which will be frequently used when writing your own JSP scripts.
Directives (command)
JSP defines three in-page commands for setting JSP parameters or expanding code. They are page, include, and taglib. They must be written in the first line of the JSP page. Syntax:
<% @ Directive attribute = "value"... %>
The page command allows you to set some basic parameters for the webpage, including setting the parameters of the script language used (Java by default), the Java class introduced in your script snippet, and setting the output buffer. For the complete page command parameter table, see Chapter 2.8.1 of JSP Specification Version 1.0 (JSP Specification 1.0.
The include command can contain the content of other files, such as the HTML header and footer stored in a separate file.
The taglib command is used to expand the standard JSP tag set, which is beyond the scope of this article. However, it is good to understand that JSP defines a method to expand its tag set. When you are a software vendor and want to expand the original functions of JSP without compromising its compatibility, this is especially important.
Declarations (Declaration)
With declarations, you can define methods or variables on the JSP page, which can be accessed by other code on the same page. In most cases, you may define methods in your own bean. However, sometimes it is easier to define methods in a webpage, especially when the code is only used for a single page. Whether the method or variable is defined, the Declaration is included in <%! %> Marked.
Note that the Declaration does not generate any output on the JSP page. They are only used for definition without generating output results. To generate output results, you should use JSP expressions or script fragments.
Expressions (expression)
Expressions is a simple JSP tag used to convert the value of the JSP expression defined in <% = %> into a string and send the value in the form of dynamic text. Expression is indeed a shortcut for generating text. With Expression, you do not have to call the print () method every time you want to display a piece of dynamic text. A typical application is that you can use expressions to display simple variable values or return values of methods in bean.
For example, the following code will generate the return value of the getName () method:
<H2> Welcome, <% = mybean. getName () %> </H2>
In fact, before generating dynamic output, JSP must convert the return value of the method into a String object in Java. The JSP specification describes in detail what Java types and Java classes are converted into strings in JSP expressions.
Scriptlets)
So far, you have learned how to use commands to introduce any Java class or Java package. You can define page-level methods or variables and use them in pages, you can also use implicit variables that provide common web processing functions. What else can be done on the JSP page depends on you, because you can write any Java code you want in scriptlets, as shown below:
<%... Code... %>
By using the IMPORT parameter in the page command, you can call all Java APIs from the script snippet. Because all the JSP code you write is actually compiled into a Java servlet, which itself is a Java class, so the language you use is Java, instead of any modified or sorted version. This is just like writing any code in SSJS. Unlike SSJS, you have the right to use a full set of Java APIs in JSP, so there are almost no limitations.
Implicit Variables (Implicit variable)
As mentioned above, JSP defines some implicit variables (that is, Java objects) for your use in expressions and script fragments. Table 2-2 of JSP Specification Version 1.0 lists the hidden variables available in JSP1.0. Some common objects are listed here:
An out object of the javax. servlet. jsp. JspWriter type. It provides access to methods (such as the print () method) and is used to generate output results in a script snippet.
The request object corresponds directly to the javax. servlet. http. HttpServletRequest class in Java and has all the attributes and methods of the object of this class. For example, to obtain a value passed in from an HTML form or URL query string, you can call the request. getParameter () method to obtain parameters by name.
The response object corresponds to the javax. servlet. http. HttpServletResponse class in Java, providing access to the parameters of HTML responses generated by your webpage. Therefore, to add a value to the HTML response Header returned by the JSP page, you can call the response. setHeader () method.
Another simple example
In the following example, we will take a look at the interaction process between a form and its JSP form handle. Using the script elements discussed earlier, I implemented a simple web site feedback form (see figure 2) and a JSP form handle to verify the input, then, outputs based on feedback are generated conditionally.
Figure 2. A web site Feedback Form
Button in the figure: submit query -- submit; reset -- refill
The form handle checks the name and comment bar to confirm that they are filled. If either or both of them are blank, the form handle generates an error message; otherwise, it will continue to check whether the user opinion matches the preset string. If it matches, it outputs a special message; otherwise, it outputs "thank you ".
Example 2
<HTML>
<HEAD>
<Meta name = "GENERATOR" Content = "NetObjects ScriptBuilder 2.01">
<TITLE> Feedback Results </TITLE>
</HEAD>
<%!
// The name and comment Column cannot be blank
// Check their values and return results
Boolean validateInput (String name, String comment ){
Boolean result = true;
// If the name or comment is not filled in, false is returned to indicate that the input is invalid
If (name. length () = 0)
Result = false;
If (comment. length () = 0)
Result = false;
Return result;
} // End input verification validateInput
// Output results based on the comment bar on the form
String getStringCheese (String comment ){
String cheese = "I like cheese .";
String result;
If (comment. compareTo (cheese) = 0)
Result = "We like cheese too! ";
Else
Result = "We hope someday you'll learn to like cheese .";
Return result;
} // End getStringCheese
%>
<Body bgcolor = "# F0F0E0">
<%
// Obtain the data submitted through the form
String name = request. getParameter ("name ");
String age = request. getParameter ("age ");
String comment = request. getParameter ("comment ");
Boolean isValid;
IsValid = validateInput (name, comment );
// Determine the output content based on whether the user has not filled in the name or comment Column
If (isValid ){
%>
<H2> Thank you for your feedback! </H2>
<H3>
<%
// Output the query results in the comment bar
Out. println (getStringCheese (comment ));
} // End the if program segment
Else {
Out. println ("You didn't give us your name or a comment .");
%>
</H3>
Please <a href = "feedback_form.html"> try again </a>
<%
} // End the else program segment
%>
</BODY>
</HTML>
In this example, we assume that the comment you enter is "I like cheese." (I like cheese) And you can see in the code that this response is customized for users who enter this comment. The form handle will return the page shown in 3:
Figure 3. Form handle output
Text in the figure: Thank you for your feedback! We also like cheese.
This example is very easy to understand. Even if you are just a JavaScript programmer, you should be able to understand it. I also want to point out some of the features that are embodied in the JSP specification in this example. First, note that I have defined some methods in the Declaration section (<% '... %>), which is exactly the same as the method defined in the Java class. This is because the JSP Engine converts these methods to the underlying Java servlets, which is executed by the server when the browser sends a request to the webpage. Therefore, all variables and methods must comply with the standard Java syntax.
It should also be noted that in my script snippet code, I separated an if... else statement, which spans two different script snippets. This is completely legal! Not only is it legal, but it is also a good way to generate HTML with conditions to combine the script snippet code with static HTML, just as I did in this example.
Finally, you can see that I call request. getParameter () to obtain the value of the form element and assign it to a temporary variable. This is a standard method for processing input values from a form or query string.