Summary of JSP and Servlet knowledge points

Source: Internet
Author: User

I. Differences between JSP and Servlet:

1. after compilation, JSP becomes servlet. (The essence of JSP is servlet. JVM can only recognize Java classes and cannot recognize JSP code. Web containers compile JSP code into Java classes that can be recognized by JVM)

2. jsp is better at page display and servlet is better at logical control.

3. No built-in objects exist in the servlet. the built-in objects in JSP must be obtained through the httpservletrequest object, httpservletresponse object, and httpservlet object.

JSP is a simplification of servlet. To use JSP, you only need to output the content that the programmer needs to output to the client. How to embed the Java Script in JSP into a class is completed by the JSP Container. Servlet is a complete Java class. The service method of this class is used to generate a response to the client.

 

Answer 1 from the Instructor:

JSP is essentially a servlet, but the two are created in different ways. servlet is completely composed of Java program code. It is good at Process Control and transaction processing, and through Servlet

To generate dynamic web pages. jsp consists of HTML code and JSP tags, allowing you to easily compile dynamic web pages.

Therefore, in actual applications, servlet is used to control business processes and JSP is used to generate dynamic web pages. In the Struts framework, JSP is located at the view layer of the MVC design mode, while servlet is located at the control layer.

Answer 2:

JSP is an extension of Servlet technology, essentially a simple servlet method. After JSP compilation, it is "servlet-like ". The main difference between Servlet and JSP is that the application logic of servlet is in the Java file and is completely separated from the HTML in the presentation layer. In JSP, Java and HTML can be combined into a file with the extension. jsp. JSP focuses on views. servlet is mainly used for control logic.

 

Ii. Nine JSP objects, seven major actions and three major commands

 

Nine built-in JSP objects:

1> output data from the out to the client. byte streams, such as out. Print ("dgaweyr ");

 

2> request receives the HTTP request from the client.

String getparameter (string name): obtains the value of the form parameter name.

String [] getparametervalues (string name): (it is often used to obtain the string [] Check box ).

Setattribute (string name, object OBJ): Set the attribute name to name and the attribute value to OBJ.

Getattribute (string name); get the property value.

 

3> response: encapsulate the response generated by JSP, and then send it to the client to respond to the customer's request. Redirect to any interface. (server jump)

Addcookie ):

Sendredirect ("/wel. jsp"): Jump to the specified page

 

4> session: used to save user information and track user behavior. Data is shared among multiple pages in the current browser. the Session object refers to a session between the client and the server, starting from a webapplication that the client connects to the server until the client and the server are disconnected. it is an instance of the httpsession class.

Setattribute (string name, object OBJ): Set the attribute name to name and the attribute value to OBJ.

Getattribute (string name): Get the property value.

 

5> Application Object: implements data sharing among users and stores global variables. it starts from the start of the server until the server is closed. During this period, this object will always exist. In this way, the object can be connected between users or between users, you can perform operations on the same attribute of this object. operations on the attribute of this object anywhere will affect access by other users. the startup and shutdown of the server determine the life of the Application object. it is an instance of the servletcontext class.

 

Session, application, and request:

A project uses as few sessions as possible, because too many sessions will affect the execution efficiency of the program. It is mainly used to save login information (user information, permissions, resources) that is frequently used information.

Application: used to share data between multiple browsers. Multiple users share this object and can perform counters. The usage of this object is exactly the same as that of session.

Data range:

Application (expired when the server is closed)> ression (expired when the browser is closed)> request (can only be used between two jump pages)

 

6> the Page Object represents the JSP object itself, that is, the current page is valid. It is equivalent to this.

Data range: page <session <Application

 

7>. Exception: indicates an exception during running.

Add the following command to the page where an exception occurs: <% @ page errorpage = "processing error page. jsp" %>

On the page for exception handling, write: <% @ page iserrorpage = "true" %>

 

8>. the pagecontext object provides access to all objects and namespaces on the JSP page, that is, it can access the session on this page, you can also take a property value of the application where the page is located. It is equivalent to the aggregator of all functions on the page. Its Class Name is also called pagecontext.

 

9> Configure servlet corresponding to. config JSP to get the initial parameters in Web. xml.

 

Seven JSP actions:

I. include dynamic inclusion (separate compilation ):

Implement with JSP: include action <JSP: Include page = "embedded ded. jsp" Flush = "true"/>

It always checks changes in the contained files and is suitable for containing dynamic pages and can contain parameters. Flush property: True indicates that the page can be refreshed. The default value is false;

 

Ii. usebean action (the second method of using JavaBean on a JSP page ):

<JSP: usebean id = "Object Name" class = "package name. Class Name" Scope = "scope of action (Request/page/application/session)"/>

The default scope is page (this page is valid ).

3. getproperty action (name is the ID of usebean action ).

Retrieve property values from an object: <JSP: getproperty name = "JavaBean object" property = "JavaBean object property name"/>

Iv. setproperty action (name is the ID of usebean action ):

Set the property value for the object: <JSP: setproperty name = "JavaBean object" property = "JavaBean object property name" value = "value"/>

Set the property value for the object: <JSP: setproperty property = "JavaBean object property name" name = "JavaBean object" Param = "username"/>

(Param = "username" is equivalent to value = <% = request. getparameter ("username") %>)

 

V. Param action (passing parameters )):

You can use request. getparameter ("parameter name") to retrieve the parameter value on the jump page.

<JSP: Include page = "URL to page">

<JSP: Param name = "parameter 1" value = "parameter value 1">

<JSP: Param name = "parameter name 2" value = "parameter value 2">

...........

</Jsp: Include>

Or:

<JSP: Forward page = "URL to the page">

<JSP: Param name = "parameter 1" value = "parameter value 1">

<JSP: Param name = "parameter name 2" value = "parameter value 2">

...........

</Jsp: Forward>

 

6. forward action:

Jump page: <JSP: Forward page = "login. jsp"/>

 

VII. plugin action: <JSP: plugin>: used to specify the plug-in running on the client

 

Three JSP commands:

I. Page command:

1. Specify the page encoding. Example:

<% @ Page Language = "Java" contenttype = "text/html; charset = GBK" pageencoding = "GBK" %>

2. Import the package, for example:

<% @ Page import = "Java. util. *, java. Text. *" %>.

Ii. include command

Static inclusion (Unified compilation): <% @ include file = "supported ded. jsp" %>

 

Iii. taglib

 

Iii. Static and Dynamic inclusion in JSP

Dynamic include (<JSP: Include page = "embedded ded. jsp"/>)

Static include (<% @ include file = "supported ded. jsp" %>)

1. The result of static include is to introduce other JSPs into the current JSP. The two are integrated to achieve data sharing, that is, unified compilation, and

The dynamic include structure is independent of the two. It is compiled separately only when the output is complete.

2. the dynamic include JSP file is highly independent and is a separate JSP file. You can create all the required objects and page settings on your own, static include is simply a sharing method for writing code outside. All variables can be shared with the main file of include. The two are highly tightly integrated and cannot conflict with the same name of the variable. the page settings can also borrow the main file.

3. Dynamic inclusion always checks the changes of included pages, and static inclusion does not necessarily check the changes of included pages.

4. Dynamic include parameters, static include does not include parameters. For example, (<JSP: Include page = "embedded ded. jsp"> put in parameters </jsp: Include> );

 

Iv. servlet Lifecycle

Load (when the server is started, it will go to the Web. find the configuration of the Servlet File in the XML file and create the servlet instance) → initialize (Init () This method is only executed once) → execute (Service (), doget (), dopost () → clear (destroy destory ())

Service (): the method itself contains doget () and dopost (). If the server discovers the Service () method, doget () and dopost () are no longer executed ().

It is generally not recommended to override the service method of the parent class, because the doget and dopost methods of this method will not be used.

If no service () method is available, the doget () method is executed by default.

 

5. Ten Methods of Servlet

Init (httpservletconfig config): called by the servlet container to indicate that a servlet is put into the service.

Service (httpservletrequest request, httpservletresponse response): called by the servlet container to allow the servlet to respond to a request

Doget (httpservletrequest request, httpservletresponse response): The GET request of the client is called by the server.

Dopost (httpservletrequest request, httpservletresponse response): it is called by the server to process the POST request of the client.

Doput (httpservletrequest request, httpservletresponse response): the server calls the put request to process the client.

Dodelete (httpservletrequest request, httpservletresponse response): the server calls the client to process the Delete request.

Destroy (): called by Servlet iner to notify a servlet that it is excluded from the service.

Getservletinfo (): returns servlet-related information, such as the author, version, and copyright.

Getservletconfig (): returns the servletconfig object.

Dohead (httpservletrequest request, httpservletresponse response): The head request of the client is called by the server.

 

6. Basic servlet Architecture

Servlet interface: mainly defines the servlet lifecycle Method

Servletconfig interface: Provides servlet with several important objects and methods for using container service.

Servletcontext interface: it is the servlet context object, which was created at server startup and provides servlet with several important methods to use container service.

Genericservlet abstract class: provides a general implementation for servlet (including Servlet and servletconfig interfaces), and saves an important object of the servletconfig type that the container passes to servlet through the init method.

Httpservlet abstract class: provides a general implementation for servlet processing HTTP requests. It mainly defines and implements several service methods.

Inheritance relationship: genericservlet inherits Servlet and servletconfig interfaces; httpservlet inherits genericservlet; servlet we write inherits httpservlet

 

7. How to configure a servlet for running

1. servlet name, package class

<Servlet>

<Servlet-Name> httpservletdemo (name obtained for servlet) </servlet-Name>

<Servlet-class> com. lxitedu. httpservletdemo (package name. Class Name) </servlet-class>

</Servlet>

 

2. ing. Access address (URL)

<Servlet-mapping>

<Servlet-Name> httpservletdemo (same as the servlet name above) </servlet-Name>

<URL-pattern>/myservlet (name of the file displayed in the address bar during runtime) </url-pattern>

</Servlet-mapping>

 

8. What is the difference between get and post?

1. Post is safer than get. (get uses the question mark transfer method)

2. The length of Post receiving is relatively long.

3. POST requests are submitted in the form, and get requests are submitted in the form of a browser. So get is faster.

4. Post can better solve Chinese garbled characters.

By default, it is a GET request. If the method attribute of form is not specified, it is also a GET request by default.

The GET request will display the parameters in the address bar of the browser. The display format is as follows? Start with '&'. You can use the getquerystring () method of the httpservletrequest () object to obtain the parameter value of the GET request.

POST request: the getinputstream () method of the servletrequest object can obtain an input stream from the socket. You can use this stream to upload files. The getreader () method can directly obtain the parameters of the POST request.

 

9. What are the jump methods in JSP or Servlet. What are their differences?

1. Client jump:

1). Use the action attribute of the Form to set the page to jump to (this method can pass the Form attribute value of this page to the next page ):

<Form action = "My. jsp" name = "Lili" onsubmit = "return test ()">

<Input type = "Submit" value = "Submit">

Or (manually submit the form for the button type ):

<Input type = "button" value = "register" onclick = "test ()">

JavaScript Functions:

Function Test (){

// Manually set the jump page

Document. Lili. Action = "my1.jsp ";

Document. Lili. Submit ();

}

2). Use the page Jump method in JavaScript (the attribute values in form cannot be passed to the next page ):

Window. Location. href = "My. jsp ";

Window. Location. Replace ("My. jsq"); // This method cannot be used to remove the page.

2. Comparison of Two Methods for server jump:

<JSP: Forward page = "XXX. jsp"/>: equivalent

Request. getrequestdispatcher ("XXX. jsp"). Forward (request, response );

This server provides more efficient resource redirection. The Address Bar remains unchanged (the page before the jump). You can obtain the request attribute value.

Response. sendredirect ("XXX. jsp "):

Redirect to any resource. Change the address bar to the current page. The request attribute value cannot be obtained.

 

10. Can servlet data be shared with JSP? If you can pass

Yes. We can put the servlet data into the httpsession, httpservletrequest, servletcontext, and pagecontext objects,

Use the corresponding built-in object in the JSP page to get the data in our servlet.

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.