"Head first JSP Servlet" note

Source: Internet
Author: User
Tags browser redirect string methods

I. Preface and Architecture

What does a Web server do?

The Web server receives the client request, and then returns some results.

Second, what do Web customers do?

A Web Client (browser) allows a user to request a resource on the server and displays the requested result to the user.

Third, HTML

When the server responds to a client's request, it typically sends a set of HTML-written instructions to the browser. HTML tells the browser how to display content to the user (depending on the content type of the response).

Iv. HTTP

HTTP is the protocol used to communicate between a client and a server on the Web. The server sends HTML to the customer using an HTTP response. HTML is part of the HTTP response.

HTTP request Analysis: http://www.cnblogs.com/RascallySnake/archive/2010/05/05/1728007.html

Five, the Web server does not do its own two things

1. Dynamic content

The Web server provides only static pages, but there is a "secondary" application (the Web container and the component in which it runs) that can generate non-static instant pages, and this helper application can communicate with the Web server.

2. Save data on the server

Even if the user submits the data through the form, the Web server is only processed by the secondary app, and the secondary app may be saved to the database.

Second, high-level overview

First, what is a container?

The servlet does not have a main method. They are controlled by another Java application, and this Java application becomes a container. Tomcat is such a container. If a Web server (such as Apache) gets a request to a servlet, the server does not hand the request to the servlet itself, but instead to the container that deploys the servlet. To provide HTTP requests and responses to the servlet by the container, and to invoke the servlet's methods, such as Dopost or doget, by the container.

Second, what can the container provide?

1. Communication support: Responsible for communication with the Web server.

2. Lifecycle Management: Control the life and death of Servlets.

3. Multithreading support: The container automatically creates a new Java thread for each servlet request that it accepts.

4. Declarative approach to security: With containers, you can use the XML Deployment profile (DD) to configure security without having to hard-code it into the Servlet class code.

5.JSP support: Responsible for translating JSP code into real java.

P.S: How does a container handle a request? P42

A city servlet can have 3 names

1. URL name that the customer knows

2. The password internal name that the Deployer knows

3. The actual fully qualified name

Establishing a mapping of the servlet names can help improve the flexibility and security of your application.

Iv. mapping URLs to servlets using deployment profiles

A URL can be mapped to a servlet using two XML elements, one mapping the client-known public URL name to your own internal name, and another element mapping your own internal name to a fully qualified class name.

p48,76

code example:

<?XML version= "1.0" encoding= "UTF-8"?><Web-app... ..>  <servlet>        <!--element 1: Internal name mapped to fully qualified name -       <Servlet-name>Suibianqude Name</Servlet-name>         <!--The name is random, the internal name, the customer can not see -       <Servlet-class>Com.example.MyServlet</Servlet-class>       <!--Place the fully qualified name of the class here (but without the. class extension) -  </servlet>   <servlet-mapping>       <!--element 2: Internal name mapped to public URL name -       <Servlet-name>Suibianqude Name</Servlet-name>       <!--consistent with the internal name above. -       <Url-pattern>/public.do</Url-pattern>       <!--This is the servlet name that the client sees (and uses), which is a fictitious name, not a specific servlet class name. --! > <!--Don't forget the front slash, which is the same as the request address: http://hostname:8080/WebAppName/public.do, no slash will become http://hostname:8080/ Webappnamepublic.do -  </servlet-mapping></Web-app>

V. MVC in the Servlet & JSP World

Controller: Get user input from the request and make clear what effect these inputs have on the model. Tells the model to update itself and lets the view (JSP) Get a new model state.

Model: Contains the specific business logic and state. In other words, the model knows what rules are used to get and update the state. Only this part of the system communicates with the database.

View: Responsible for representing aspects. It gets the state of the model from the controller. In addition, the view has access to the user's input and is submitted to the controller

Who will be responsible for each of the following tasks?

Task

Web server

Container

Servlet

Create a request and response object

Created before starting the thread

Invoking the Service method

The service method then calls Doget or Dopost

Start a new thread to process the request

Start a servlet thread

Convert the Response object to an HTTP response

Generates an HTTP response stream from the data in the response object

Understanding HTTP

For conversations with customer browsers

Add HTML to the Response object

Dynamic content provided to the customer

A reference to a response object

The container gives it to the servlet.

Print the response with it

Finding URLs in the deployment profile

Find the appropriate servlet for the corresponding request

Delete Request and Response objects

Once the servlet is finished, delete the request and response objects

Orchestrate dynamic content generation

Know how to forward to a container

Know what method to invoke

Managing the life cycle

Invoking a service method

Vii. What is the difference between a Web server and a Web container, is tomcat a Web server or a Web container?

A standalone web container is typically configured to collaborate with an HTTP Web server, such as Apache. However, the Tomcat container itself can be used as a basic HTTP server. However, in terms of HTTP server functionality, Tomcat is not as robust as Apache, so the most common non-EJB Web applications typically use Apache and Tomcat,apache as HTTP Web servers, tomcat as a web container.

Third, the MVC combat

I. Request DISPATCH mechanism

RequestDispatcher rd = Request.getrequestdispatcher ("request.jsp");

Rd.forward (Request,response);

The Getrequestdispatcher parameter, if not the slash, indicates that the JSP and servlet are under the same path, and if there is a slash, it represents a JSP page under the root path of the current web App. "/" represents the root of the Web app.

This should be similar to Getservletcontext (). getResourceAsStream ("").

Iv. Requests and responses

I. The relationship between the Servlet Genericservlet HttpServlet

A servlet is an interface. Genericservlet is an abstract class that implements the Servlet interface. HttpServlet is also an abstract class that inherits from the Genericservlet abstract class.

P98

Second, each request is run in a separate thread

In a JVM, no servlet class has more than one instance, except for one special case (called Singlethreadmodel). The container runs multiple threads to handle multiple requests to a servlet. corresponding to each customer request, a pair of new request and response objects (HttpServletRequest and HttpServletResponse) are generated.

Third, ServletContext

N Each Web app has a servletcontext.

n is used to access Web application parameters (these parameters are configured in the deployment description file).

n is used to obtain server information, including the container name and the container version, and the version of the supported API.

A Servlet object encapsulates a set of context initialization parameters and a set of properties . For context initialization parameters, only getter methods are provided, and Getter/setter methods are provided for attributes.

Iv. ServletConfig Objects

N each servlet has a ServletConfig object.

n is used to pass deployment-time information to the servlet, and you do not want to hardcode the information into the servlet.

n is used to access ServletContext.

The n parameter is configured in the deployment description file.

The ServletConfig object simply encapsulates a set of string-type key-value pairs (servlet initialization parameters). The container reads out the servlet initialization parameters from DD, encapsulates the parameters as a ServletConfig object, and then passes the ServletConfig to the servlet's Init method. The servlet initialization parameter can only be read once, when the container initializes the servlet. So the ServletConfig only provides getter methods.

P158 the difference between the servlet initialization parameters and the context initialization parameters.

V. ServletRequest interface and Servletresponse interface

The HttpServletRequest interface inherits from the ServletRequest interface. The HttpServletResponse interface inherits from the Servletresponse interface.

Both the HttpServletRequest interface and the HttpServletResponse interface are implemented by the container (TOMCAT). When invoking the Servlet's service method, the container passes a reference to the method for the respective implementation class object of the two interfaces.

Vi. various methods of HTTP

GET

POST

HEAD

TRACE

PUT

DELETE

OPTIONS

CONNECT

Vii. the difference between get and post

1. Data size issues. The Get method has restrictions on parameter data, and parameter data can only be placed on the content of the request line. There is no limit to the post mode, and the parameters are placed in the body of the message.

2. Security issues. When you use Get mode, the request parameter is placed behind the actual URL by the browser (with a "?" Separated by "&" between the parameters).

3. Bookmark problems. The Get method allows the end user to bookmark the requested page, while the Post method does not.

4. Power and other issues. A GET request is idempotent, just to get something and not to modify anything on the server. Post is non-idempotent, and the commit data in the post body may be used to modify something on the server.

Idempotent: For http/servlet, this word means that the same request can be done two times without adversely acting on the server. Not that the same request always gets the same response, nor does it mean that a request has no side effects.

What can I get from httpservletrequest except the parameters?

1. Client's platform and browser information: String client = Httpservletrequest.getheader ("user-agent");

2. cookie:cookie[in connection with the request] Cookies = Httpservletrequest.getcookies ();

3. Related to client session (session): HttpSession session = Httpservletrequest.getsession ();

4. http method Requested: String methods = Httpservletrequest.getmethod ();

5. Requested input stream: ServletInputStream InputStream = Httpservletrequest.getinputstream ();

Httpservletrequest.getserverport (); port on which the server listens

Httpservletrequest.getlocalport (); The server is looking for a different local port for each thread

Httpservletrequest.getremoteport (); Get the port of the customer

Nine, the common method of HttpServletResponse

Httpservletresponse.setcontenttype (String);

Httpservletresponse.getwriter (); Process text data.

Httpservletresponse.getoutputstream (); Process any other content.

Httpservletresponse.addheader ("Key", "value"), no corresponding key is created, otherwise it will overwrite the existing value

Httpservletresponse.setheader ("Key", "value"), no corresponding key is created, or another value is added

Ten, using relative URLs in Sendredirect ()

Httpservletresponse.sendredirect ("http://www.google.com"); Servlet Lets browser redirect

You can use a relative URL as a parameter to Sendredirect () instead of specifying the full "http://www ...." "。 There are two types of relative URLs: preceded by a slash "/" and no slash.

Suppose the customer originally typed: Http://www.hehe.com/myApp/cool/bar.do

When the request arrives at a servlet named "Bar.do", the servlet calls Sendredirect () based on a relative URL that does not start with a slash: Sendredirect ("foo/stuff.html");

The container will create a new url:http://www.hehe.com/myapp/cool/foo/stuff.html

If the Sendredirect () argument begins with a slash: Sendredirect ("/foo/stuff.html");

The container creates a new url:http://www.hehe.com/foo/stuff.html

The "/" here represents the root of the Web container.

P136

Xi. Differences in Request dispatch (forwarding) and redirection

RequestDispatcher rd = Httpservletrequest.getrequestdispatcher ("/request.jsp");

Rd.forward (Request,response);

Httpservletresponse.sendredirect ("/foo/stuff.html");

1. The "/" in the request dispatch represents the root of the Web app. The "/" in the redirect represents the root of the Web container. If none is present, it means that it is relative to the directory where the current servlet resides.

2. The request dispatch occurs on the server side, while the redirect is performed on the client. The request dispatch passes the request to another component on the server. Redirection simply tells the browser to access another URL.

Request Quantity Address Bar
Forwarding 1 unchanged
REDIRECT 2 change

For example: Add, modify, delete after successful to redirect to the list function, so that in the Refresh page will not appear "do one more, delete, change" operation.

V. Attribution and supervision of listeners

First, Servletcontextlistener

Because the context parameter can only be string. After all, you cannot hard-plug a dog object into XML. What if you want to create a database connection object to be shared by each servlet when ServletContext is initialized?

Javax.servlet.ServletContextListener object of the implementation class of this interface can listen to the two key events in ServletContext lifetime, initialize and revoke.

Suitable for the following requirements scenario: to establish a database connection using the initialization parameter lookup name when ServletContext is initialized. Storing a database connection as a property makes it accessible to all parts of the Web application. Closes the database connection when ServletContext is revoked.

Other listeners as well as the application scenario. P182

Second, what is a property?

A property is an object that may be set to one of the other 3 Servlet API objects, including ServletContext, HttpServletRequest, or httpsession. It can be simply thought of as a name/value pair in a mapped instance object (the name is a string and the value is an object).

Three, the difference between attributes and parameters

P186

四、三个 Scope: Context, request, and session

P187

V. Context scopes are not thread-safe

P192

Solution: ServletContext Object Yoke P197

Session scopes are also not thread-safe

P199

Solution: HttpSession Object Yoke P200

Two scenarios for implementing Singlethreadmodel: Instance pool policy and queuing policy P201

Recommended Solutions and Reasons P202

Only request properties and local variables are thread-safe!

Variable type

is thread safe

Context Scope Properties

Whether

Session Scope Properties

Whether

Request Scope Properties

Is

Instance variables in a servlet

No (unless STM is implemented)

Static variables in a servlet

No (Implementation of STM is also non-thread safe)

Local variables in the service method

Is

Vi. Session Management

One, send a session cookie in response the same as the code that gets the session ID from the request

HttpSession session = Request.getsession ();

Ii. Differences Between GetSession (Boolean) and GetSession ()

P235

Second, the customer disables the cookie, thus causes the customer and the server to be unable to pass the SessionID processing method

P237

URL rewrite: Httpservletresponse.encodeurl ("/user.do")

URL rewrite using Sendredirect (): Httpservletresponse.encoderedirecturl ("/user.do")

Iii. life cycle Events of HttpSession

P255

Iv. Session Migration

P257

Vii. use of JSP

One

<%%> scriptlet, the variables declared here are local variables.

<%@%> instruction, <%@ page import= "com.model.*,java.util.*"%> this is the page directive with the Import property.

<%= expression%> expression, do not add a semicolon after the expression. Equivalent to <% out.print (expression)%>

<%! %> JSP declarations, you can declare variables and methods.

<%----%>jsp notes

<jsp:usebean./> action

Second, the life cycle of JSP

P306

Third, initialize the JSP

Configure the JSP initialization parameters, overriding the Jspinit method. P310

Iv. PageContext

In addition to the standard Servlet request, session, and context, JSP also adds a fourth scope, the page scope, which can be obtained from the PageContext object. The PageContext encapsulates other implicit objects. P298, 311-313

V. Use the <scripting-invalid> tag in DD to prohibit the use of scriptlet in the page and disable El using the <el-ignored> element.

p321-322

"Head first JSP Servlet" note

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.