Fun JSP and JSTL

A Introduction

JSP: dynamic web programming technologies Java Server Page SUN company provides a Java Web server-side  dynamic resource. Compared terms html, html data to only provide static user, the technology allows nested Jsp java code in the page, provide dynamic data to the user. For comparison servlet, servlet data layout difficult, and in addition generates a dynamic jsp java code number used  at the same time data, the data is also very easy layout. Whether or JSP Servlet, although dynamic web resources can be used for development. But because the two technical characteristics of each, in the long-term software practice, people gradually as a controller servlet web application components to use,  and the JSP technology as a data template to use. In fact, that is a Jsp Servlet, when we first visit the Jsp, Jsp Jsp engine will be to translate this into a Servlet, the files are stored in the Tomcat work directory.

Two . Basic grammar

1. Comment

Supports two types of comments in JSP syntax operation, one is a comment that this comment is allow the client to see;  the other is the implicit comment, this comment is not visible client

①  display comment syntax: from HTML style inherited

②  implicit comment syntax: from inheritance JAVA style; JSP own notes

Notes JSP three ways:

1) // comment, single-line comment / * multiline comment * /

2) <-! HTML-style comments ->

3) <% - JSP Comment -%>

2. Scriptlet

In the most important part of the JSP is Scriptlet (script applet), all Java programs embedded in HTML code must use Scriptlet marked, in the JSP There are three Scriptlet Code:

The first: <%%>: java script section, you can define local variables, write statements

The second: <%!>: Statement, you can define global (member) variables, methods, classes

 Third: <% =%>: expression, a variable or specific content data

Understand the three kinds of small java script file jsp code by viewing parsing

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE >

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<%

String str = "Hello JSP";

System.out.println(str);

response.getWriter().write(str);

%>

<%!String memberStr = "a member String";%>

<%=memberStr%>

<h1>This is a JSP page!!</h1>

</body>

</html>

3. JSP tags instructions

JSP label instructions to control the behavior of the entire jsp, and give instructions to the JSP translator on certain aspects of the current JSP page.

1) page command

And control properties contentType page directive pageEncoding commonly used, are used as a MIME type and encoding format. import attribute for introducing other packages, and the import java

The same statement applies.

MIME type

<%@ page contentType=”text/html;charset=UTF-8”%>

Wrong hands <% @ page contentType = "test / html; charset = UTF-8"%> download the file at this time becomes Character Encoding

contentType main function is used to set the MIME (page response type), and

charset = "UTF-8" code has been assigned, using pageEncoding = "UTF-8" can specify the encoding, the former is more commonly used.

In JSP, if charset exist, then the JSP code is determined by the charset, and if not will be decided by pageEncoding, if none exists, use the ISO-8859-1 encoding.

Guide package

page directive import attribute exists, so the package can guide the proper use, and in the properties of the entire page of the instruction,  only the import statements can appear multiple times, other attributes can be set only once. You can lead pack means you can link directly to the database in jsp.

<%@page import="java.util.*" import="java.io.*" %>

It can be combined into one

<%@page import="java.util.* ,java.io.*" %>

2) include static contains

<% @ Include file = "file to include the path"%> relative path

<%@include file="include.jsp"%>

<%@include file="include.html"%>

Static content is to include a direct replacement, like the same variables defined in the program is translated in the servlet engine, put the contents of this document contains inside (two files of source code to integrate together , put all _jspService method in), so only generated a servlet, so the page can not have two variables of the same name. A little high operating efficiency. Coupling high, is not flexible enough.

3) taglib tag library introduced

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

 When using a third-party tag library needs to be introduced through the taglib tag.

4. JSP tag operation

Action tags, which are compiled into Java code to perform certain operations, such as access to a Java object, or invoke a method. JSP container has its own standard action support. In addition to the standard operation, you can create specific labels,  to perform certain operations. These jsp action tags with html tags provide fundamentally different:

* Action tags by tomcat (server) to explain the implementation! As with java code that are executed on the server

* Html be executed by the browser!

Format is as follows:

include dynamic include

include action for dynamically comprising another resource, which may contain another JSP page, a Servlet or a static HTML page. Containing operation, some duplicate code continue to include it, from the point of view of normal page composition, sometimes divided into several regions. And some of these areas may not need to be have been changed,

Wherein the change on a specific content area. There are two ways to achieve the above functions.

Method one: in each JSP page (HTML) contains a toolbar, header information and footer, details

Method 2: toolbars, header information and footer are divided into separate files, when the future use of direct  import came Obviously, the second method is a better than the first, first there will be a lot of duplicate code and that modifications very convenient, if it is implemented in JSP operation included, there are two ways: statically included, comprising dynamic and static include directive to include the use of dynamic comprising labels include action is required.

Dynamic code is included in the compilation stage, inclusion and included part of two separate parts, only when run, will contain dynamic come in, like calling the method.

<jsp:include page="include.jsp"></jsp:include>

Note: Dynamic contain, in the middle do not add any content, including spaces, unless confirm that you want to use parameters, otherwise an error!

<jsp:include page="include.html"></jsp:include>

<%

String a = "hello.jsp";

%>

<jsp:include page="<%=a%>"></jsp:include>

Further comprising using the dynamic parameter passing through between pages. Receiving parameters

request.getParameter (name) to complete

jsp:include page="hello.jsp" flush="true">

<jsp:param name="school" value="shsxt"/>

</jsp:include>

<%=request.getParameter("school")%>

Note: Some objects can be used directly in the JSP, the code can be known by observing the .java. Currently we only need to know the request, response, session, application can be directly used.

Three . Nine built-in objects

View by jsp files can be parsed

1.request objects

javax.servlet.httpServletRequest request object is an object type. The object represents a client request information, mainly for receiving data transmitted to the server via the HTTP protocol. (Including header information. System Information Request mode and request parameters, etc.). Scope request once the request object.

2.response objects

response represents the response to the client, mainly the JSP container treated objects back to the client. The response object also has a scope, it is only valid within the JSP page.

3.session objects

session object is created automatically related objects requested by the user by the server. Server generates a session object for each user, for storing information of the user, the tracking operation state of the user. Map session using internal object classes to store data, the data stored in the format "Key / value". value session object may be a complex object types, not just a string type.

4.application objects

application information objects can be stored in the server until the server is shut down, otherwise

application objects stored information will be valid throughout the application.

Compared with the session objects, application objects longer life cycle, similar to the "system-wide variables ."

5.out objects

out object is used to output information in the Web browser, and manage the output buffer on the application server. When the object using the output data out, the operation may be made to the data buffer, timely removal of residual data in the buffer, so that the space for other output buffer. After the completion of data output, to close the output stream.

6.pageContext objects

The role of pageContext object is to obtain any range of parameters, you can get out JSP page through it. Request. Reponse. Session. Application and other objects. pageContext objects are created and initialized by the container to complete, can be used directly pageContext object in JSP pages.

7.config objects

The main role of config object is to obtain configuration information for the server. By pageConext object getServletConfig () method gets a config object. When a Servlet initialization, certain information transmitted to the container the Servlet using the config object. Application developers can program in the environment Servlet and JSP pages provide initialization parameters in the web.xml file.

8.page objects

object represents the JSP page itself, only in the JSP page is legitimate. page hidden object contains the current Servlet interface reference variable in nature, similar to the this pointer in Java programming.

9.exception objects

The role of the exception object is to display exception information, containing only can be used isErrorPage = "true" page, use the object in general will not compile JSP page JSP file. excepation object and all the objects, like Java, has inherited the structure provided by the system. Almost all the exception object is defined exceptions. If there is no abnormality in the captured JSP pages, it will generate exception object and transmits to the error page exception object set in the instruction page, and then the processing in the corresponding exception object error page.

Four, EL expressions

1. EL syntax and usage

EL (Expression Language) in order to make it easier to write JSP. Inspiration comes from the expression language ECMAScript and the XPath expression language that provides a simplified method in JSP expressions, let Jsp code more streamlined.

Syntax structure is very simple: $ {expressio} EL expression domain object data is in the general operation, the operation can not local variables. Domain object concept in JSP a total of four: pageContext, request, session, application ; range order that the present page, a request,  a session, the entire application. The EL default look for ways to find small to large, can be found. When the whole domain objects  looking over yet found an empty string is returned "."

When it is necessary to specify the data to find the object from a particular domain can be used in four spatial domain object corresponding to the object, are: pageScope, requestScope, sessionScope, applicationScope.

2. EL operation

Using an EL expression can be used to judge whether there are elements in the set $ {empty list}

1) List traversal

<%List<String> list = new ArrayList<String>();

list.add("aaa");

list.add("bbb");

list.add("ccc");

request.setAttribute("list", list);

%>

${empty list}

<br /> ${list[1] }

<br />

2) access map

As used herein, the value of another embodiment of the el [ ""]

<%

Map map = new HashMap();

map.put("aaa", "111");

map.put("bbb", 2222);

map.put("ccc-a", 333);

request.setAttribute("map", map);

%>

${empty map} ${map.aaa }

<br /> ${map["bbb"]}

<br /> ${map["ccc-a"]}

3) doing +, -, *, / (can also be used to represent div),%, ==

<%

String a = "aaa";

String b = "aaa";

%>

<%=a == b%>

${4 div 2 }

<br />

Note: String comparison also uses ==

<%

request.setAttribute("a", 10);

request.setAttribute("b", 10);

%>

 <h2>${a+b }</h2>

<h2>${a==b }</h2>

<%

request.setAttribute("a", "aaaa");

request.setAttribute("b", "aaaa");

%>

<h2>${a==b }</h2>

 

J STL

A . Introduction

Java Server Pages Standard Tag Libray (JSTL): JSP Standard Tag Library is a collection of custom tag library for solving common problems, such as a map or an iterative set of test conditions, XML processing, database and even access the database operation. We now discuss only the most important JSTL tags, as well as a collection of iteration number and date formatting several labels.

The core tag library: http: //java.sun.com/jsp/jstl/core Web application that contains common tasks, such as: cycling, expression evaluation, the basic input and output.

Formatting tag library: http: //java.sun.com/jsp/jstl/fmt formatted to display operation data, such as: the date of formatting, etc. in different regions. In order to use JSTL libraries in JSP pages, you must use the taglib directive in the following format:

<%@taglib uri=”” prefix=””%>

For example: <% @ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c"%> prefix can be any content, the code can be made to follow the specification prepared by different teams art more similar; therefore, recommend the use of pre-designed prefix. In this case need to import two jar package. Lib directory can be directly into the Tomcat.

Two use. Tag

1. Condition Action Tags

Operation command output conditions for processing the page depends on the case of certain input values, using the Java if, if ... else and switch statement to be processed. In JSTL has four standard operation command may perform conditional expression: if, choose, when and otherwise.

1) if the label

if the label first to test a condition, if the conditional operator evaluates to true, then the process its main content, test results are stored in a Boolean object and create a variable to reference confinement Boolean object. Var property may be utilized confinement variable name, using the scope attribute specifies its scope.

Syntax if two forms: no body content, there is the main content

No body content

In this case: var variable domain specified limits determined by the same test tag behind a JSP page.

There main content

The main content is JSP, if the test condition is true, then the processing JSP. No tag JSTL else, for the scenario simulation else, if necessary to use two labels, and tags for these two  opposing conditions.

2) choose, when the label and otherwise

The role of choose and when tags and Java in the switch and case keywords similar. In other words: they provide content for the implementation of the conditional expressions mutually exclusive. label content portion must choose one or Multiple when embedded tags, each tag when a situation may be representative of operations and processing. otherwise the tag for the default condition code block, if the test results of all conditional operations when the label is not true, the block of code will be executed. After the label if otherwise, it must be placed when the last label, otherwise it will error.

otherwise choose tag has no attributes and, When you must use test label attribute setting a condition for determining whether to process the main content.

2. iteration tag

forEach tag

forEach is a main content iteration times, iterations or a collection of objects. Iteration may include the objects  and some achieved java.util.Collection and java.util.Map interface, and the basic type of an object or an array. He is also  an iterative java.util.Iterator and java.util.Enumeration, but

Enumeration can not be used in multiple or Iterator operation command, or as Iterator Enumeration can not be reset (reset). Each attribute have the following meanings: using varStatus property:

forEach syntax comes in two forms:

The body content repeated a number of times:

It used to iterate over a collection of objects:

<%

List list = new ArrayList();

for (int i = 0; i < 10; i++) {

list.add("A:" + i);

}

pageContext.setAttribute("li", list);

%>

<table>

<tr>

<td>List内容</td>

<td> current subscript </ td>

<td> total membership </ td>

<td> is / No first member </ td>

<td> is / No is the last member of </ td>

</tr>

<c:forEach items="${li}" var="item" begin="0" end="9" varStatus="idx">

<tr>

<td><b>${item}</b></td>

<td>${idx.index}</td>

<td>${idx.count }</td>

<td>${idx.first }</td>

<td>${idx.last}<br /></td>

</tr>

</c:forEach>

</table>

Content body as JSP, for each iteration, forEach tag confinement creates a variable whose name attribute is set by var. Map using a forEach iteration, respectively, using the key and a reference value attribute Map Map key and a value.

<%

Map map = new HashMap();

map.put("map1", "shsxt");

map.put("map2", "bjsxt");

map.put("map3", "sxt");

pageContext.setAttribute("map", map);

%>

<c:forEach items="${map}" var="myMap">

${myMap.key}:

${myMap.value}<br />

</c:forEach>

3. Format operation command

JSTL provides formatting and parsing numbers and dates of the label, which we discuss are:

formatNumber、formatDate、parseNumber 及 parseDate。

1) formatNumber label

matNumber tag of the tag with the specified format or digital format precision, <fmt: formatNumber> tag has the following properties: When this tag, has two syntax:

No body content

There main content

2) formatDate label

Style or pattern using the specified date and time format, <fmt: formatDate> tag has the following attributes: pattern attribute specifies more precise processing date:

3) parseNumber label

Using parseNumber tag number, currency, or percentage may be interpreted as a string representation of a ring to a specified language  digital environment. I.e. parses represents a number, or a percentage of the currency string. Two kinds of syntax:

No body content

Use main content <fmt: parseNumber> tag has the following properties

4) parseDate label

This label is a date and time specified region parse string representation. Parsing a word that is representative of the time or date  string. Two forms :

No body content

Use main content

Guess you like

Origin www.cnblogs.com/ruanjianwei/p/12133499.html