JSP Technology Entry

Source: Internet
Author: User

JSP Abbreviation: Java Server Page

1. operating principles of web resources

HTML: static Web resource. DefaultServlet reads HTML files and outputs them to IE browser through response

Servlet: Dynamic Web resources. The Web Container (Servlet Engine) parses the Web. xml file and finds the Java class corresponding to the URL.

Create a servlet object through reflection and call the service method

Class. forname ("CN. itcast. servlet. servlet1"). newinstance ();

JSP: Dynamic Web Resources

When a JSP page is accessed for the first time, the Web Container (JSP Engine) translates the JSP into a Servlet and then calls

Service method.

After JSP translation, the servlet will be placed

% Tomcat installation directory % \ work \ Catalina \ localhost \ webcontext

When the JSP page is accessed again, the Web Container will directly call the servlet service method. Therefore, JSP is usually slow when it is accessed for the first time.

If the JSP page is modified, the Web Container will re-translate the JSP

2. What is JSP?

In fact, JSP is a servlet, but it only providesIntuitiveWriting Method, because writing JSP is like writing html

Java can be written in JSPCodeThere are two ways to write

1) JSP script expression

The content will be put in out. Print () to output a browser.

<% = New date () %>

JSP script expression, followed by a line of Java code. Note that it cannot end with a semicolon.

Your IP address is: <% = request. getremoteaddr () %>

Interview Questions:

How to convert a number into a string?

String. valueof

Integer

What is the difference between string. valueof and to string?

They are all the same. Mutual call

2) JSP script snippets

A large amount of Java code can be written and multiple lines of Java code can be entered.

The content of JSP script snippets will be unblocked and translated to the servlet service method.

<%

// Java code

%>

JSP running principle: When ie accesses a JSP, the Web Container first translates the JSP into a servlet, and the rest of the process is exactly the same as accessing a servlet.

The expression is translated to the out. Print in the service method.

J

3. Differences between JSP and Servlet

1) servlet is suitable for writing Java code, because servlet is a Java class

Use servlet in development to process and respond to user requests

2) JSP is suitable for data beautification as a data display template.

Because JSP pages directly write HTML tags

3) The web layer in the project usually uses the MVC design mode servlet + JSP + JavaBean

The servlet acts as a controller to process user requests.

JSP as a display template

Javabean is the entity that encapsulates data.

4) How to develop a good coding style

Avoid any data output in the servlet.

In JSP, you should avoid writing Java code directly. In fact, it is difficult to do this, so you need to use el and jstl

(Java code that must be written in JSP to retrieve data from the domain object)

Ii. jsp Syntax 1. template Elements

All HTML tags on the JSP page are called template elements for layout of the entire page.

2. jsp script

The Java code in JSP is called a JSP script.

There are three forms

1) script expression

Translated to the out. Print () method.

<% = New date () %>

2) script snippets

Translated to service method

<%

For (INT I = 0; I <10; I ++ ){

System. Out. println (I );

}

%>

3) JSP Declaration

Translated to the service method

Write member variable \ member Method \ static code block

<%!

Private string name;

Static {

.......

}

%>

3. jsp commands

The include command is used to contain a page.

The taglib command is used to introduce the tag library file.

The page command is used to describe JSP pages to the JSP Engine.

The page command is usually placed at the beginning of the page, but it takes effect for the whole page no matter where it is placed.

Commonly used page Commands include:

1) import the import package. When importing multiple packages, separate them with commas (,) and separate them for writing multiple commands.

Example: <% @ page Language ="Java"Import ="Java. util .*"Contenttype ="Text/html; charset = UTF-8"Pageencoding =UTF-8"%>

In the automatic package import method, click Alt +/next to the word, and then select the package Import

OK.

2) The session indicates whether to use the session.

The default value is true. The translated Serlvet automatically obtains the session.
If this parameter is set to false, the session is not obtained in the service method of the translated servlet.

3) errorpage

You can also configure error pages in the web. xml file.

Can be configured according to the exception type or error code

Error-page

To prevent English errors, the error prompt page is configured as follows:

If an error occurs: Configure an incorrect jump page for all JSP pages, configure it in Web. xml

Configuration content:

1. catch exceptions and errors

<Error-page>

<Exception-type> JAVA. Lang. arithmeticexception </exception-type>

<Location>/error. jsp </location>

</Error-page>

1. Error Codes

<Error-page>

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

<Location> 404.JSP</Location>

</Error-page>

 

* Iserrorpage: True | false. Indicates whether the error handling page is correct. Whether to generate an exception object

* Contenttype = "mimetype; charset = UTF-8": equivalent to response. setcontenttype ();

* Pageencoding: the encoding used by the notification engine when translating JSP -- Servlet

* Iselignored: whether to ignore the El expression true | false. The default value is false. True indicates the El expression is ignored.

4) pagaencoding

Instruct the JSP Engine to decode JSP files during JSP Translation

The response encoding method of the notification servlet engine, which is equivalent to response. setcontenttype ()

To put it bluntly

If pageencoding = "UTF-8" is specified for JSP"

When the JSP Engine translates JSP, it will automatically add a sentence

Response. setcontenttype ("text/html; charset = UTF-8 ")

Extension: JSP garbled

After Tomcat 6, there will be no garbled JSP code. If Tomcat 5 is used, garbled code will occur.

 

The JSP garbled solution tells the JSP Engine what code the JSP page is, so that the translation will not be wrong.

Tell response what code is used to send it to the browser

 

 

Cause of garbled characters

1. jspProgramChinese garbled characters are identical to servlet programs.

Contenttype = "text/html; charset = UTF-8"

2. Chinese garbled characters when reading the parameter information passed by the browser

3. Chinese garbled characters may also occur when the JSP Engine translates JSP pages into servlet source files.

JSP Engine JSP source file translated into Servlet Source file by default using ISO8859-1 encoding, and JSP developers can use a variety of character set encoding to compile JSP source file, therefore, when the JSP Engine translates a JSP source file into a Servlet Source file, it must undergo character encoding conversion.

If the JSP file does not indicate the character set encoding it uses, the JSP Engine treats it as the default ISO8859-1 character set encoding.

4. How to solve Chinese garbled characters when JSP engines translate JSP pages

Use the contenttype attribute of the page command to describe the character set encoding of the JSP Source File

The pageencoding attribute of the page command describes the character set encoding of the JSP source file.

The notification client encoding method is contenttype.

 

Iii. jsp nine implicit objects (written test) 1. Interview Questions:

List and describe nine implicit objects on the JSP page.

Object variable name, which can be directly used in JSP

Object Type

Config

Servletconfig

Application

Servletcontext

Response

Httpservletresponse

Request

Httpservletrequest

Session

Httpsession

Out

Jspwriter

Page

This (current servlet object)

Exception

Throwable

Pagecontext

Pagecontext

Note:

Not every page has an error page (errorpage), and The iserrorpage attribute is set to true.

The Session object does not exist on every page by default. However, if the session of the page command is set to "false", no session built-in object exists.

2. Out object

Jspwriter type, buffer-based consumer stream (Packaging stream) bufferedwriter

The data written to the stream will be refreshed to response and the response. getwriter (). Write (buffer) method will be called.

Under what circumstances will jspwriter refresh the data

1) buffer full (the default size is 8 KB. You can set the buffer size through the buffer attribute in the page command)

2) JSP page ends

Note:

1) output data in JSP should be used out as much as possible. Do not use response to directly obtain the stream output.

The reason is that the data written out will enter the buffer and refresh to response. If both are used, the data written later will be displayed in front.

2) at the end of the JSP page, response. getwriter () is automatically called to refresh the data.

Therefore, do not call getoutputstream () in JSP ()

Of course, it is not convenient to download files.

Conclusion: Output Data Using out in JSP

3. pagecontext object

This function is used to obtain other 8 hidden objects.

The significance of doing so:

To remove the Java code in JSP, you need to write the Java code to a Java class member method, and then try

To reuse code.

Because the Java code in JSP will inevitably access eight implicit objects, because these objects are all related to web development.

To remove this part of Java code, we need to pass eight objects to the Java class method. For convenience, we usually pass only one

The pagecontext object is in the past, so that the other eight objects can be easily obtained through this object in the method.

Pagecontext is also a domain object, but only valid on the current JSP page

Important:

1) Write 9 objects silently (describes how to use 9 objects)

2) understand the meaning of the pagecontext object (get the other 8 Objects)

Pagecontext has a special method findattribute ()

4. four domains in Web Development (key points)

From small to large: Page (JSP valid) Request (one request) session (one session) Application (current Web Application)

Page: pagecontext object

Request: httpservletrequest object

Session: httpsession object

Application: servletcontext object

ClassRequest {PrivateMap <string, Object> attributes =NewHashmap ();Public VoidSetattribute (string name, object Value) {attributes. Put (name, value );}PublicObject getattribute (string name ){ReturnAttributes. Get (name );}Public VoidRemoveattribute (string name) {attributes. Remove (name );}}
1. What is the lifecycle of these four objects?

The lifecycle refers to the period from object creation to destruction.

Page: the JSP page is executed. The lifecycle starts. the JSP page is executed and the lifecycle ends.

Request: the user sends a request, starts, the server returns a response, the request ends, and the lifecycle ends.

Session: the user opens the browser to access the object, creates a session (start), the session times out or is declared invalid, and the object lifecycle ends.

Application: When a web application is loaded, it is created (started), the web application is removed, the server is closed, and the object is destroyed (ended)

2. Scope of the four domains

What is a domain? Why are these four objects called domain objects?

Domain: Meaning of range

Domain objects in the Web, which can be stored and can be obtained within the scope of application

Map <string, Object> is implemented in the map set.

ClassPagecontext {PrivateMap attributes =NewHashmap ();PrivateHttpsession session;Public VoidSetattribute (string name, object Value) {attributes. Put (name, value );}PublicObject getattribute (string name) {attributes. Get (name );}Public VoidRemoveattribute (string name) {attributes. Remove (name );}}}

Page: Valid only on the current JSP page

Request: valid only for the current request. Each request corresponds to different request domain objects.

// Session: by default, the access from the same browser is valid (send the same sessionid)

Session: valid only for one session, and data cannot be obtained after the session ends (in special cases, sending cookies)

Application: valid in a web application (as long as the server is not closed, the Web application can retrieve data without removing it)

The four domain objects are arranged in ascending order: Page request session Application

3. In which case the domain object is used.

Principle: when four domain objects are selected, they can be used in a small range and never use a large range.

Page: data only has a set temporarily. It is used elsewhere on the JSP page. Use Page (custom map on the page)

When does MAP need to be used?

Request: The data is only displayed. It is useless after reading it, and the request domain is saved.

Request forwarding: The processing result (data) generated by Servlet is displayed in JSP,

Session

The user logs in and sends the user information to the client. After reading the information, visit other pages and view the user information.

Shopping Cart. Shopping cart is successful. You can view the shopping cart at any time.

Request redirection, because it is two requests, the data of the first request, the second request also needs to be viewed

Application: The data is used up for a user.

Chat rooms and chat records, which must be viewed by all users

Count the number of online users on the website. All users can see one number.

Conclusion: we need to define that map is not as good as page. The request is forwarded to the JSP data storage request by the servlet.

Request redirection data stored sessions with past data, global data stored applications

V. jsp details

The exception implicit object is available only when the iserrorpage command specified by the JSP page is true.

The Session object is not available on every JSP page. The premise is that the session attribute of the page command is true.

JSP notes:

1. SP Error

1) The translated servlet cannot be compiled, and the syntax is incorrect. In this case, it will report which line of JSP cannot be compiled.

2) The translation servlet encounters an exception during running and reports the exception caused by the JSP line.

In this case, the cause of the exception is further reported, and the row in the servlet contains the exception.

2. jsp ING also uses servlet Elements

Vi. neixing 1. JavaBean

Fixed-write Java class

1) required parameter Constructors

2) attributes must be private, which is called fields.

3) provides standard getter and setter

Example: getter: String getname () settter: void setname (string name) of the Name field)

2. What is introspection?

Introspection: Access JavaBean through reflection

In JDK, the API: propertydescriptor class operates bean attributes.

3. beanutils Toolkit

Apache developed a set of APIS for operating JavaBean (introspection)

Core class beanutils

Setproperty (bean, name, value)

Copyproperties (target, source );

Supports conversion of basic data types from string to 8

For other referenced data types, you must register the convertutils. Register (converter, class) converter)

3. webutils tool class

Encapsulate any form submitted by request to the corresponding JavaBean

Important:

1. jsp running principle (will be translated into servlet)

2. jsp script expressions and script fragments

3. Nine implicit JSP objects

4. Four domain objects for Web Development

5. Introspection

Use of beanutils

Use

VII. jsp tags (optional)

To remove Java code from JSP pages, Sun provides some built-in labels.

We call it a JSP tag or a JSP action element.

1. <JSP: Include> is equivalent to the page introduction of the requestdispatcher object

Dispatcher. Include implements servlet inclusion

Dispatcher. Forward implements servlet forwarding

When forwarding, the Web Container clears the data in response.

Data cannot be written to response after forwarding

Dynamic import method, introduced during the program running, JSP is translated into two

The include command can also implement page introduction, static introduction, and translate Two JSPs into a Servlet

The included and included JSP page commands cannot conflict.

The import and pageencoding operations can conflict with each other.

2. <JSP: Forward> implement request forwarding

Automatically performs URL Encoding Based on the <JSP: param> label parameter passing. For the encoding method, see Request Encoding.

3. <JSP: usebean ID class scope> Introspection

Creates a JavaBean by reflection and stores the ID as the key in the specified domain.

In fact, the domain will be searched first before the creation. If it is found, it will not be created.

4. <JSP: setproperty> set the property value

<JSP: setproperty name = "user" property = "username" value = "Zs"/>

<JSP: setproperty name = "user" property = "username" Param = "username"/>

<JSP: setproperty name = "user" property = "*"/> batch

5. <JSP: getproperty> get the property value

8. Web Development Mode

Sun provides two modes for web development.

Model1: JSP + JavaBean is only suitable for small applications

Model2: servlet + JSP + JavaBean MVC

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

Common functions of JSP:

1. Your IP address is: <% = request. getremoteaddr () %>

2. Scroll function: <marquee behavior = "scroll" direction = "Left"> </marquee>

Use the <div> function, AP element.

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.