A detailed JSP for Java web development

Source: Internet
Author: User

JSP, as the most important technology in Java Web Development, is generally used as a view technology, that is to show the page. Servlets are generally used as controllers (Controller) because they are not suitable for the presentation layer itself, and JavaBean is used as a model layer. This is the classic MVC model.

The relationship between Servlets and JSPs has been discussed in the previous blog, and demonstrates a fairly simple example. Before you tell me about JSP, let's introduce JavaBean briefly.

JavaBean is actually a Java generic class that defines the properties and behavior of a class (get, set method). In the MVC design pattern, there is no mention of the database interaction operation, in fact, through the JavaBean implementation of the specific database operations. As for why it is called JavaBean, it is said that the name is the father of Java in a coffee at a time to see the coffee beans on the table, the whim of a JavaBean name (bean is the meaning of beans).

Referring to MVC, by the way, three layers (layered, multilayer) architecture, many people confuse the relationship, feeling that MVC is very similar to the three-tier architecture, think they are not much different. In fact, in a nutshell, MVC is a design pattern, and a three-tier architecture is a layered model. MVC contains model-controller-view, note there is no "layer", it emphasizes the development of the code into these parts, through this model to implement the application development. MVC is not the exclusive web development, in fact, in the early development of C/s has used the MVC design pattern. The three-tier architecture refers to the DAL (data Access layer), the BLL (business Logic Layer), the UI (user interface layer), which emphasizes the structure of the program development.

By clearing the above relationship, the Java language allows you to handle all the related operations in the background, while using JSP to handle all the related operations on the foreground page.


First, the basic elements of the JSP

A JSP contains the following basic elements:

1. HTML part

Refers to the static portion of the JSP (Java Server Pages,java Service-side page) page.

2. Instruction

There are 3 main types of directives:

Page directive (each JSP page needs to have, set page encoding, import requires Jar package requires page directive): <%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8" %>

TAGLIB directive (used when importing jstl or custom tags): <% @taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>

Include directive (including page): <% @include file= "test.jsp"%>

3. Expression

<%= method (Parameters ...) %>

<%=gettime ()%>

4. Script segment (scriptlet)

Format:<%...%>. Like what:

<% Calendar C = calendar.getinstance (); %><%if (C.get (calendar.am_pm) = = calendar.am) {%> morning <%} else {%> pm <%}%>

5. Statement

Format: <%!...%> such as:

<%!public String GetTime () {return new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (new Date ());}%>

6. Action

Use Javabean:<jsp:usebean id= "..." "class=" package name. Class name "scope=" page "/>

Get property: <jsp:getproperty property= "Bean's property name" Name= "The ID of the bean used"/>

Set properties: <jsp:setproperty property= "Bean's property name" Name= "The ID of the bean used" value= "the explicit value specified for the property"/>

Page contains: <jsp:include page= "test.jsp"/>

Page Jump: <jsp:forward page= "test.jsp"/>

...

7. Comments

There are two types of annotations:

A, <!--client can see the comments--

B, <%--the client cannot see the comment%>

Basically the above 7 elements, a slightly more complex JSP page will be included. In particular, the difference between the include directive and the include action can be made by introducing other pages in the main page to achieve the purpose of embedding the page. The main difference is that the include directive affects the construction of the main JSP page, affecting the variables defined on the master page, essentially compiling a new page with the main page, so that the page executes more efficiently. The include action is to embed the new page in the main page, loading the primary JSP page first, and then loading the Include action embedded page, the execution efficiency is lower than the include directive, but this is a more flexible choice. In real development, use the include action a little more.


Second, JSP implicit object

An implicit object means an object that does not require an explicit new class object and can be used directly on a JSP page. There are four main categories:

1. Input and Output objects: request, response, out

Request.getparameter ("name");

Request.getparametervalues ("name");

Response.setcontenttype ("TEXT/HTML;CHARSET=GBK");

Response.sendredirect ("url");

Out.println ("...");

2. Scope object: PageContext, request, session, Appplication

Pagecontext.getattribute ("name");

Pagecontext.setattribute ("name", "value");

Request.getattribute ("name", "value");

Request.setattribute ("name", "value");

Session.getattribute ("name");

Session.setattribute ("name", "value");

Application.getattribute ("name");

Application.setattribute ("name", "value");

Life cycle of the scope object: PageContext (page) <request (Request) <session (session) <application (APP).

3. Servlet object: page, config

((httpjsppage) page). Getservletinfo ();

Config.getinitparameter ("name");

4. Error object: exception

Exception.printstacktrace (out);


Three, El expressions (expression language)

Although it is possible to embed Java code in the JSP page through expressions to achieve output, this is not the best way to develop. From a development perspective, the foreground JSP page should not appear in Java code (Java code should appear in the background). In order to solve this problem, JSP expression language was introduced.

Syntax: ${...}.

To give an example of a simple point:

<jsp:usebean id= "Bean" class= "com. JspPractise.bean.City "scope=" page "/><jsp:setproperty property=" name "Name=" Bean "value=" Test El "/>${ Bean.name}   or    ${bean["name"}
A javabean is used by the Usebean action of the JSP, and the Name property is assigned by SetProperty action, and finally through ${bean.name} or ${bean["name"} Output: Test el.

Another example is the form form submission:

We can use <%=request.getparameter ("name") to%> the output, but the better way is to output it through ${param.name}. Because the scope is page, it is also possible to output by ${pagescope.bean.name}el implicit objects. From small to large in the scope of the other also have Requestscope, Sessionscope, Applicationscope and other El implicit objects (different from the JSP implicit object).

In addition, El expressions also have arithmetic functions, such as:

${10+1.0} <!--11.0-->${90e2-120} <!--8880.0-->${23.8*7} <!--166.6-->${1/0} <!--Infinity  - ->${10 Div 5} <!--2.0-->${10%4} <!--2-->${10 mod 4} <!--2-->${10*10 eq. <!--true-- ${' C ' GT ' B '} <!--true-->${9 le 8} <!--false-->


Iv. JSTL (Java Standard Tag Library)

Jstl is also a technique used in JSP pages, and the purpose of this set of tag libraries is to face some judgments in JSP pages (condition Tags: if), Loops (Iteration label: foreach), Database operations (SQL Tag Library: update, param, query, and so on). It's always inevitable to embed Java code, and the use of these tags makes the JSP page code "refreshing" a lot. In addition to these tags above, there are some common tags, such as: Set, remove, out and so on.

With Jstl, you first use the TAGLIB directive to import jstl.

<% @taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>
After importing, you can use JSTL in your JSP pages.

The following is an example of embedding Java code with the above output "morning/Afternoon", using jstl instead of JSTL implementation.

<c:set var= "CC" value= "<%=calendar.getinstance (). Get (CALENDAR.AM_PM)%>"/><c:set var= "PM" value= " <%=Calendar.PM%> "/><c:set var=" AM "value=" <%=Calendar.AM%> "/><c:if test=" ${cc==am} "> <c:out value= "Morning" ></c:out></c:if><c:if test= "${cc==pm}" ><c:out value= "Afternoon" ></c:o Ut></c:if>
In addition to the code inside the value is Java code (here for a simple demonstration did not put Java code into the background code), no longer see the figure of Java, replaced by Jstl.
And see how the foreach tag is used.

<%string[] colors = new string[] {"Red", "green", "yellow", "Black", "Silver"};p Agecontext.setattribute ("Colors", col ORS);%><c:foreach var= "Color" items= "${pagescope.colors}" ><c:if test= "${color== ' Yellow '}" ><c:o UT value= "${color}"/></c:if></c:foreach>
A string array is stored in the PageContext (JSP scope object) and is then fetched and looped out by JSTL in conjunction with the El expression pagescope (El scope object).

JSTL also provides a library of SQL tags, because our development is generally in the background to encapsulate this part of the code, so basically no need, here is no longer demonstrated.


This blog mainly review the JSP development process of a lot of basic details of knowledge, master the above knowledge can be able to Java Web development. Of course, with the size of the project more and more large, simple JSP development can not be competent, need to introduce the development framework. The famous struts, Hibernate, spring and other frameworks I will introduce later.

In fact, as long as the number of knocks on the code, encounter errors and more thinking, analysis will be able to master the Java Web skills, this is my review of Java Web Development The greatest experience these days.


A detailed JSP for Java web development

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.