Web DAY13 jstl Tag Library (c tag, custom tab), MVC design pattern, Javaweb classic three-layer framework

Source: Internet
Author: User
Tags tld


Jstl

1. Overview of Jstl

*apache stuff that relies on El

* Use Jstl to import Jstl1.2.jar

* Four libraries:

> Core: Key library, focus

> FMT: Formatting: Dates, numbers

> sql: Obsolete

> xml: Obsolete

2. Import Tag Library

*jar Bag

* In JSP page: <% @taglib prefix= "prefix" uri= "path"%>

----------------------

Core--C tags!

1. Out and set

*<c:out>: Output

> Value: Can be a string constant or an El expression

> Default: When the content to be output is NULL, the value specified by default is output

> EscapeXML: The default value is true, which means escape!

*<c:set>: Set (Create a domain's properties)

> var: variable name

> Value: Variable value, can be an El expression

> Scope: Domain, default is page, Optional value: page, request, session, application

2. Remove

*<remove>: Deleting a domain variable

> var: variable name

> Scope: If you do not give scope, the variable that is the name in all domains is deleted, and if a field is specified, only the variable for that domain is deleted.

3. URL

*URL tag will add sessionId when URL rewriting is required

*value: Specify a path! It automatically adds the project name in front of the path.

<> <c:url value= "/index.jsp"/>, it will output/day13_1/index.jsp

* Sub-tag: <c:param>, used to add parameters to the URL, for example:

<c:url value= "/index.jsp" >

<c:param name= "username" value= "Zhang San"/> <!--can URL encode parameters!! -

</c:url>

The result is:/day13_1/index.jsp?username=%ed%2c%3f%ed%2c%3f

*var: Specifies the variable name, and once this attribute is added, the URL tag is no longer exported to the page, but the generated URL is saved to the domain.

*scope: It is used with Var to save the URL.

<c:url value= "/" var= "a" scope= "request"/>

Assign the result that should be output to variable a. Range for request

4. If:

Corresponds to the IF statement in Java

*<c:if test= "Boolean type" >...</C:IF> when the test value is true, the tag body content is executed!

<c:set var= "A" value= "Hello"/>[create a variable named a in the page field]<c:if test= "${not Empty A}" ><span style= "font-size: 13.3333px; Font-family:arial, Helvetica, Sans-serif; >[determines that a variable is not NULL, no domain is specified, and the global]</span><c:out value= "${a}"/></c:if>


5. Choose:

It corresponds to If/else if/in Java .../else

For example

<c:choose>

<c:when test= "" >...</c:when>

<c:when test= "" >...</c:when>

<c:when test= "" >...</c:when>

...

<c:otherwise> ...</c:otherwise>

</c:choose>

Equivalent to

if (...) {

}else if (...) {

}else if (...) {

}else if (...) {

}...

else {...}

6. ForEach

It is used to iterate through arrays, collections!

It can also be used to count ways to cycle!

Counting method:

for (int i = 1; i <=; i++) {

...

}

<c:foreach var= "I" begin= "1" end= "ten" >

${i}

</c:forEach>

Property:

*var: Loop variable

*begin: Sets the loop variable from several beginnings.

*end: Sets the loop variable to a few ends.

*step: Set the step size! Equivalent to i++ in Java, or i+=2. Step defaults to 1

----------------------

Used to output arrays, collections!

<c:foreach items= "${strs}" var= "str" >

${str}<br/>

</c:forEach>

Equivalent to

for (String str:strs) {

...

}

Property:

* Items: Specifies who to loop, which can be an array or a collection

* var: assigns each element in the array or collection to the variable specified by var.

Traverse Map

<%Map<String,String> stu = new linkedhashmap<string,string> (), Stu.put ("number", "n_1001"); Stu.put (" Name "," Zhangsan "); Stu.put (" Age "," all "), Stu.put (" Sex "," male ");p Agecontext.setattribute (" Stu ", Stu);%><c: ForEach var= "Item" items= "${stu}" ><span style= "FONT-SIZE:13.3333PX; Font-family:calibri; " >[because a map is traversed, each entry is entry type]</span><c:out value= "${item.key}: ${item.value}"/><br/><span Style= "FONT-SIZE:13.3333PX; Font-family:calibri; " >[get entry key and value]</span></c:foreach>


----------------------

Loop state

You can use Varstatus to create loop state variables!

The loop state variable has the following properties:

*count: Number of looping elements

*index: The subscript of a looping element

*first: is the first element

*last: is the last element

*current: Current Element

<%ArrayList<String> list = new arraylist<string> (), List.add ("one"), List.add ("two"), List.add ("three"); Pagecontext.setattribute ("list", list),%><c:foreach items= "${list}" var= "Ele" varstatus= "vs" >${vs.index} $ {Vs.count} ${vs.first} ${vs.last} ${vs.current}<br/></c:foreach>
Results

0 1 true false one
1 2 false false two
2 3 false True Three

====================================

FMT Library

It is a format library

<fmt:formatdate value= "" pattern= "" >

Value: Specifies a variable of type date

Pattern: The template used to specify the output! Example: Yyyy-mm-dd HH:mm:ss

--------------

<fmt:formatnumber value= "${num1}" pattern= "0.00" >

Keep 2 digits after the decimal point and it will be rounded! If it is less than 2 bits, fill it with 0!

<fmt:formatnumber value= "${num1}" pattern= "#.##" >

Keep 2 digits after the decimal point and it will be rounded! If less than 2 bits, do not fill the bit!

====================================

Custom labels

1. Steps

* Label processing class (tag is also an object, then you need to have classes first!) )

*tld file, which is an XML

* Use <% @taglib%> in the page to specify the location of the TLD file

2. Label Processing class

Simpletag Interface:

*void Dotag (): This method is called every time the label is executed;

*jsptag getParent (): Returns the parent tag (non-life cycle method)

*void setParent (Jsptag): Set parent tag

*void setjspbody (jspfragment): Set label body

*void Seetjspcontext (Jspcontext): Sets the JSP context object, whose son is PageContext

 where Dotag () is called by Tomcat after the other three methods.

Simpletagsupport class :

* Simpletagsupport It implements the Simpletag interface.
* It has saved all the data that Tomcat has passed! It also provides a GET method for subclass invocation!

3. Configuring TLD Files

TLD files are generally placed under web-inf so that clients cannot access them!

<tag>

<name>myTag1</name> Specify the name of the current label

<tag-class>cn.itcast.tag.MyTag1</tag-class> Specifies the label handling class for the current label!

<body-content>empty</body-content> Specify the type of label body, we use an empty label here!

</tag>

4. Specify the TLD file location on the page

<%@ taglib prefix= "It" uri= "/web-inf/tlds/itcast-tag.tld"%>

Guide Tag Library, is to specify the location of the TLD file for the page!

-------------------------------

Custom Label Advanced

Tag Body Content

*empty: no tag body!

*jsp:jsp2.0 is not supporting this type anymore! Indicates that the tag body content can be: Java script, can be a tag, can be an El expression

*scriptless: Can only be an El expression, or another label!

*tagdependent: Tag body content will not be executed, but directly assigned to the label processing Class!

Do not label the contents below the tag!

Use Skippageexception to end in Dotag () in the Label handling Class!

Tomcat invokes the Dotag () method of the label-handling class, and Tomcat gets skippageexception, which skips the rest of the page!

public class MyTag4 extends Simpletagsupport {@Overridepublic void Dotag () throws Jspexception, IOException {THIS.GETJSPC Ontext (). Getout (). Print ("See me only, there's nothing underneath!"). "); throw new Skippageexception ();//After throwing this exception, the contents after this tag will not be visible! }}

---------------

Label Properties

Steps:

1. Add properties to your label handling class!

Add a property to the label processing class, and the property must be at least one set Method! This set method will be executed by Tomcat before the Dotag () Method! You can use attributes in the Dotag () area.

2. Configure the properties in the TLD file

<attribute>

<name>test</name> Specify property name

<required>true</required> Specifies whether the property is required

<rtexprvalue>true</rtexprvalue> Specifies whether the property can use the El

</attribute>


Simple Analog If label

/** * Tagged with attributes *  * @author CXF *  */public class MyTag5 extends Simpletagsupport {Private Boolean test;/* * This method will be made by Tom Cat to invoke, and before Dotag () */public void Settest (Boolean test) {this.test = test;} @Overridepublic void Dotag () throws Jspexception, IOException {if (test) {/* * executes tag body */this.getjspbody (). Invoke (null);/ If the output stream passed is null, it means that the out! of the current page is used }}}


==========================================

Mvc

It is not Java-specific, all the B/s structure of the project are using it!

M--model Model (own code)---- Program Programming Program application functions (Implementation algorithm, etc.), database management;

V--view View (JSP)---- Interface designer for graphical interface design;

C--cotroller Controller (Servlet)---- request processing, responsible for request forwarding

Almost all of b/s structure software has adopted the MVC design pattern. However, it should be noted thatMVC in b/s structure software is not fully implemented, such as in our future b/S software will not have event-driven!


==========================================

Javaweb three-layer frame

We often say that the three-layer framework is proposed by Javaweb , which means that this is javaweb Unique!

The so-called three tiers are the presentation layer (theWEB layer), the business logic layer, and the data access layer.



Web Layer--web-related content (Servlet,jsp,servlet related api:request, response, session, ServletContext)

Business Layer--business object (service): The business layer does not contain the javaweb API, it only cares about business logic;

Data tier--operational database (DAO data Access Object) (all operations on the database cannot jump out of the DAO)


PS: Note that the javaweb APIcannot appear in the business layer, such as request,response , and so on. In other words, the business layer code is reusable and can even be applied to non- Web environments. Each method of the business layer can be understood as a panacea, such as a transfer business method. The business layer relies on the data tier, and the Web tier relies on the business layer!


Example: using three-layer frame structure to display the properties of the user class simply


JSP page

Show results

Web.servlet (Userservlet)

* Rely on service in servlet, then save the result to request with service completion function
* Forwarded to the JSP display.

Service (userservive)

The service layer relies on the DAO layer

* Service query, need to use DAO to complete!

DAO (DAO)

* After the data in the XML is queried, it is encapsulated in the user object and then returned

Domain (User)

* Save the results of queries in the database to this object.


Web DAY13 jstl Tag Library (c tag, custom tab), MVC design pattern, Javaweb classic three-layer framework

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.