JSP and JavaBean Introspection technology

Source: Internet
Author: User
Tags dateformat throwable tomcat server

L JSP

L JavaBean and introspection

L-El Expression

1.1 Previous lesson Content review

Session Technology:

Cookies: Client technology. Save the data on the client browser. Cookies are limited in size and number.

Session: Server-side technology. Save the data on the server side. The session has no size or number limit. The session is based on a cookie that writes back a jsessionid.

Classification of Cookies:

* Session-Level cookies: The browser is closed and the cookie is destroyed!

* Persistent Cookies:

* Cookie.setmaxage (time); ---the time specified for survival.

* Cookie.setmaxage (0); ---destroy persistent cookies. Condition: The path must be consistent.

* Case one: Record the user's last access time.

* Case Two: Browsing history of customer visits.

Session:

* Case one: Shopping cart

* Case TWO: Verification code

* Session Tracking: Do you want to use the session after the browser disables cookies?

* URL rewrite:

* After all the address paths are spliced; Jsessionid=sessionid values.

* Response.encodeurl (URL); ---automatically stitching jsessionid after URL address

* Response.encoderedirecturl (URL); ---URL rewriting when redirecting.

1.2 JSP 1.2.1 JSP Overview: What is a JSP

Jsp:java Server Pages. Java server-side page. Run on the server.

JSP = Html + Java + JSP itself

Why learn JSP

Sun Company proposed dynamic development technology: Servlet.servlet in the use of time, found a lot of shortcomings. (When generating HTML pages, configuration runs are required). Sun realizes that Servlet has no way to compete with ASP, PHP (lamp:linux Apache Mysql php). So Sun has proposed a dynamic web development technology JSP.

JSP benefits: When generating HTML pages.

Where to use:

Develop dynamic Web pages to use. Generally, the development of a Web site, generally will not use the Jsp.sun company Dynamic Web development technology, application in the system, net silver system ...

1.2.2 JSP Operating principle:

JSP---> Server translated into a servlet----> compiled into a. Class execution.

* Code generated by the JSP in the source code:

* Public final class _1_jsp extends Org.apache.jasper.runtime.HttpJspBase

* See httpjspbase need to view Tomcat source code. You can see the. Httpjspbase class inherits HttpServlet.

<%! int a = 0;%>---translated into a servlet's global stuff.

<% int i = 1;%>---translated into something inside the service method.

<%= i%>---translated into out.print (i) within the service method;

1.2.3 JSP Syntax: the scripting element of the JSP:

Embed Java code in your HTML code with scripting elements in your JSP.

<%! %>---declares methods and variables. Translates into global methods and global variables in the servlet. (Seldom used!) Servlets are singleton. Thread safety issues.)

<%%>---Declaration cannot be a method. A local variable, an inner class, translated into a service method in a servlet.

<%=%>---Declares an expression. The Out.print () translated into the service method in the servlet;

The JSP script element of the interview question:

<%! int x = 0; %>---Declares the global variable x=0;

<%=X%>---Output global variable x

<% x=5; %>---Modified the global variable x=5;

<% int x = 10; %>---Declares the local variable x=10;

<% this.x = 20; %>---Modify the global variable x=20;

<%=x%>---Output local variable x

The content of the page output is: 0 10

* JSP translation of the global Declaration form, will be preferred translation.

Comments for JSP:

HTML, Java, JSP annotations are supported in JSP

HTML notation: It exists in the code of the JSP code and in the translated servlet code and in the HTML page.

<!--HTML comments--

Java code Comments: In the code of the JSP Code and the translated servlet

<%

Single-line Comment

/*

Multi-line comments

*/

/**

* Documentation Comments

*/

%>

JSP annotations: Only in the JSP source code stage

<%--JSP Comment--%>

1.2.4 the JSP directive.

There are three main instructions in JSP: page, include, taglib directive.

Syntax of the instruction:

<%@ directive Name Property Name = Property Value Property name = value of the property ...%>

Page directive: Sets the basic information for a JSP page.

<%@ page language= "java"%>

* Language: Language is used in scripts that set up JSPs. It can only be Java at this time. (No modification is required.)

* Sun's design jsp is ambitious.

* Extends: Sets the JSP to translate into servlet code. Which class to inherit after translation into a servlet. (No modification is required.)

* Default value: Org.apache.jasper.runtime.HttpJspBase. This value can be modified. However, the inherited class must be a HttpServlet or httpservlet subclass.

* Session: Set JSP page can directly use the session. The default value is true. (No modification is required.)

* Import: Sets the appropriate class for the import of JSP pages.

* The import attribute can occur multiple times.

* Packages that do not need to be imported:

* JAVA.LANG.*;

* JAVAX.SERVLET.*;

* JAVAX.SERVLET.HTTP.*;

* JAVAX.SERVLET.JSP.*;

* Buffer: Sets the output of the JSP page to a buffer size. Default value: 8KB

* AutoFlush: Sets the output of the JSP page a buffer if it is full. Default value: True

* ContentType: The default character set used by the browser when setting the JSP page to be opened by the browser.

* pageencoding: Set JSP file saved to local hard disk and JSP translated into servlet saved to hard disk. The character set used.

* ErrorPage: What to do when setting the JSP page exception (Error page friendly hints)

* Iserrorpage: What to do when setting the JSP page exception (Error page friendly hints)

* Set iserrorpage= "true": in Source code

Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable (request);

if (Exception! = null) {

Response.setstatus (Httpservletresponse.sc_internal_server_error);

}

These two properties are generally not used to configure error-friendly pages when developing in the enterprise. (Global error page)

* Configure the Global error friendly page in Web. Xml.

<error-page>

<error-code>404</error-code>

<location>/404.jsp</location>

</error-page>

<error-page>

<error-code>500</error-code>

<location>/500.jsp</location>

</error-page>

* Iselignored: Sets whether the JSP page ignores El expressions. The default value is false. Do not ignore. (El can be used directly in JSP)

Properties in the page directive:

* Import, ContentType, pageencoding

Include directives

The Identity JSP page contains those JSP pages.

Syntax: <%@ include file= "included page path"%>

* The page contains the structure code for the HTML of the page. Contains the structure of the page that contains the HTML that is not written.

The inclusion of directives that use JSPs: This inclusion is typically referred to as a static inclusion.

* Principle: Equivalent to the code copy, eventually translated into a servlet to execute.

* File attribute:

* Cannot be a variable: The variable does not have a specific value.

* Parameters cannot be passed: The parameter is meaningless.

TAGLIB directive

Identifies the tag library used by JSP pages.

Syntax: <%@ taglib uri= "" prefix= ""%>

* URI: Tag Library path

* Prefix: Tag library aliases

The built-in object of the 1.2.5 JSP.

A JSP's built-in object refers to an object that can be used directly in the JSP.

There are 9 built-in objects in a JSP.

* PageContext, request, session, application, response, page, config, out, exception.

What are the 9 built-in objects of a JSP, who are the corresponding classes, and what are the common methods?

JSP built-in object (real object)

* PageContext PageContext

* SetAttribute (String name,object obj);

* GetAttribute (String name);

* Request HttpServletRequest

* SetAttribute (String name,object obj);

* GetAttribute (String name);

* GetParameter (String name);

...

* Session HttpSession

* SetAttribute (String name,object obj);

* GetAttribute (String name);

* Application ServletContext

* SetAttribute (String name,object obj);

* GetAttribute (String name);

* Response HttpServletResponse

* sendredirect (String URL);

* Getwriter ();

* Getoutputstream ();

* Page Object

* Wait ();

* Notify ();

* Equals ();

* Config ServletConfig

* Getservletname ();

* Getinitparameter ();

...

* Out JspWriter

* Print ();

* println ();

* Flush ();

* Exception Throwable

* Exception to use the need to set iserrorpage= "true" in the JSP page;

* GetMessage ();

* Getcause ();

* Learned: Request, response, session, Application, config, exception

* Never learned: page, PageContext, out

Page object:

The Page object is an instance of object.

* Page represents a reference to a Servlet object after a JSP page is translated. Generally not recommended.

* Object page = this;

Out object:

is the Out object and Response.getwriter () an object?

* Not necessarily.

JspWriter----Out

PrintWriter----Response.getwriter ();

Illustrates the principle of an out object through a case:

* The contents of the buffer of the out stream are first output to the buffer of the response stream, and the output stream of the response responds to the page.

PageContext object:

Four scopes of JSP:

* The servlet learned three domain objects.

* ServletContext, HttpSession, HttpServletRequest.

* ServletContext object:

* Create and Destroy:

* Created: When the Tomcat server is started. The server creates a ServletContext object for each Web project itself. is a global shared object.

* Destroy: When the Tomcat server is shut down. When the Web project is removed from the server.

* Role: Record the global stuff. Number of visits to the site. Be a chat room.

* HttpSession object:

* Create and Destroy:

Create

* The server is created the first time the GetSession () method is called.

* Do you create a session when accessing the HTML? Will you create a session when you visit the JSP?

* The session will not be created when accessing HTML. The JSP is created when it is accessed!

* Destruction: Three cases of session destroyed.

* The session expires. Default 30 minutes.

* Abnormal shutdown of the server! (Destroy normal shutdown: Session serialized to hard disk.)

* Session.invalidate () method will destroy session.

* Function: Save private generated data. Shopping Cart. Login information. Verification code.

* HttpServletRequest object:

* Create and destroy

* Create: The client accesses the server once.

* Will the HTML be created when accessing the JSP?

* The server is created when the HTML is accessed. Access to the JSP will be more.

* Destroyed: After the server responds to this request.

* Function: Save data at forwarding time.

* Redirect and Forward differences: (interview)

* 1. Redirect is two requests two responses! Forwarding is a request one time response!

* 2. Redirect the Address bar will change! The forwarding Address bar does not change!

* 3. Redirect is directed to any website! Forward only resources within the project!

* 4. REDIRECT path requires Add/project name! No need to add engineering name when forwarding!

Four domain objects in a JSP:

* PageContext: The saved value can only be applied to the current page! (range is minimal)---pagescope (page range)

* SetAttribute (String name,object obj);

* GetAttribute (String name);

* Request: One Access---requestscope (Request scope)

* Session: One conversation.---sessionscope (Session range)

* Application: One application.---applicationscope (Application range)

* The role of PageContext:

* 1. Access values to four domain scopes.

* 2.findAttribute (String name); ---to retrieve values from a small to large range.

* 3.pageContext built-in objects get other 8 built-in objects. (Write a framework or a high-versatility code.)

1.2.6 JSP Action Tags:

Grammar:

<jsp: Action Tags >

* Tags can replace a piece of Java code.

<jsp:forward >: Forwarding.

<jsp:include >: Included. (Dynamic inclusion.)

* What are the differences between static inclusions and dynamic inclusions?

* Static inclusions: Equivalent to a copy of the code. Translated into a servlet execution.

* Dynamic Inclusion: Translate the included pages into the respective servlet. The respective servlet executes. Contains only the results of the servlet execution.

<jsp:param >

* Used in forward and include. (Rarely used! When forwarding, Request.setattribute ("name", "123"))

It is related to JavaBean! See JavaBean part of the content!

<jsp:useBean>

<jsp:setProperty>

<jsp:getProperty>

1.3 JavaBean and introspection 1.3.1 what JavaBean

JavaBean is a Java class that has a specific wording.

* Java classes need to have an parameterless construct.

* Attributes need to be privatized.

* Provide public method access to the properties of privatization. Setxx Getxx method.

* Name: Corresponding method. SetName (); GetName ();

JavaBean action: Encapsulate and process data!

Properties of the JavaBean:

*!!! determined by the set and get methods in the bean

1.3.2 encapsulating data using the JSP action tag

<!--package Data--

<!--Usebean: Using JavaBean

ID: Equivalent to the identity of the class

Class: The full path of the Java class that encapsulates the data

Four areas of scope:jsp

-

<jsp:usebean id= "P" class= "Cn.itcast.bean1.Person" scope= "page" ></jsp:useBean>

* Usebean tag after translation code:

Cn.itcast.bean1.Person p = null;

Synchronized (_jspx_page_context) {

p = (Cn.itcast.bean1.Person) _jspx_page_context.getattribute ("P", pagecontext.page_scope);

if (p = = null) {

p = new Cn.itcast.bean1.Person ();

_jspx_page_context.setattribute ("P", p, Pagecontext.page_scope);

}

}

<jsp:setproperty property= "name" Name= "P"/>

<jsp:setproperty property= "Age" name= "P"/>

<jsp:getproperty property= "name" Name= "P"/>

<jsp:getproperty property= "Age" name= "P"/>

***** <jsp:setproperty property="*" name="P"/>

The * number represents all the attributes in the form.

1.3.3 Beanutils Class Library (will be used)

The bottom of beanutils is introspection!

Introspection:

* via BeanInfo info = introspector.getbeaninfo (Class clazz);

* via propertydescriptor[] PDS = info. getpropertydescriptors ()

* Iterate through all the attribute descriptions:

* Pd.getreadmethod ();

* Pd.getwritemethod ();

Automated encapsulation of data through introspection:

public void populate (Object obj,map<string,string[]> Map) throws exception{

1. Obtaining class Information

BeanInfo BeanInfo = Introspector.getbeaninfo (Obj.getclass ());

2. Get all the attribute descriptions in the bean through the class information

propertydescriptor[] pds = Beaninfo.getpropertydescriptors ();

3. Iterating through an array

for (PropertyDescriptor Pd:pds) {

The value of the property that describes the name of the form is the same as the property name in the Bean.

if (Map.containskey (Pd.getname ())) {

string[] Value = Map.get (Pd.getname ());

Gets the set method of the object.

Method method = Pd.getwritemethod ();

Method.invoke (obj, value[0]);

}

}

}

A tool class provided by the Beanutils:apache Organization for JavaBean data encapsulation.

* A jar package is required to download beanutils.

* Commons-beanutils-1.8.3.jar

* Commons-logging-1.1.1.jar

* Used in Servlets:

* Beanutils.populate (Object obj,map Map);

* You can turn a string into a basic data type (wrapper class)

* If a date type is passed: beanutils cannot complete type conversion and an exception will occur!

* A custom type converter is required:

public class Mydateconvertor implements converter{

Go from O to C

String--->date

Public Object Convert (Class C, object o) {

object is the type to convert string

String values = (string) o;

Turns a string into date.

DateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd");

Convert string to date format (convert date to String) parse (convert string to date);

Date date = null;

try {

Date = Dateformat.parse (values);

} catch (ParseException e) {

E.printstacktrace ();

}

return date;

}

}

* Use the type converter:

* need to be used before the Beanutils.populate () method

Convertutils.register (New Mydateconvertor (), date.class);

Summary of today's content

Jsp:

* JSP concept:

* JSP Operating principle:

* JSP scripting elements:

* JSP Syntax:

* Comments for JSP:

* JSP Instructions:

* Page

* Include

* Taglib

* JSP built-in objects:

* PageContext, request, session, application, Response, config, out, page, exception

* Four domain scopes for JSPs:

* Page_scope:pagecontext

* Request_scope:request

* Session_scope:session

* Application_scope:application

* JSP Action:

* <jsp:forward>

* <jsp:include>

* <jsp:param>

* <jsp:useBean>

* <jsp:setProperty>

* <jsp:getProperty>

JavaBean and Introspection:

* What is JavaBean.

* A Java class that satisfies a specific format.

* Non-parametric construction

* Attribute Private

* Private properties have the get and set methods of public.

* Use JavaBean in JSP

* Introspective technology: Get the set and get methods for attributes and attributes in JavaBean.

Use of Beanutils:

* Beanutils.populate (Object obj,map Map);

* Convertutils.register (Converter c,class clazz);

1.4 El Expression

JSP and JavaBean Introspection technology

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.