Java EE third Week job

Source: Internet
Author: User

First, what is the session? What's the effect? How do I manage a session in a servlet?

HTTP is a stateless protocol, where clients simply request to the server, but neither the client nor the server records each other's past behavior, and each request is independent. This introduces the session mechanism in the Java Servlet API to track the state of the customer. Session refers to a series of interrelated interactions between a single customer and a Web server over a period of time. In a session, the customer may request access to the same Web page multiple times, and may request access to a variety of different server resource sharing sources.
For example, in an e-mail application, from a customer login to the e-mail system, through a series of operations, such as receiving, writing and sending letters, until the final exit of the mail system, the entire process is a session.

For a session, the session is a container that can hold any object during the session. At the same time, the session is generated (Request object), and multiple requests in the same session share a session object that can be fetched directly from the request to the session object.

Session management mechanisms for Servlets:

HTTP is a stateless protocol. It means that the web app does not know about the information previously requested by the same user. One way to maintain session state information is to use the session tracing functionality provided by the servlet or JSP container. The Servlet API specification defines a simple httpsession interface that enables us to easily implement session tracking. The HttpSession interface provides methods for storing and returning standard session properties. Standard session attributes, such as session identifiers, application data, and so on, are saved in the form of a "name-value" pair. In short, the HttpSession interface provides a standard way to save objects to memory and extract them in subsequent requests from the same user. The method of saving data in a session is setattribute (string s, Object o), and the method of extracting the original saved object from the session is getattribute (string s). Whenever a new user requests a JSP page that uses a HttpSession object, the JSP container sends a special number to the browser, in addition to sending back the answer page. This particular number is called the "session identifier", which is a unique user identifier. Thereafter, the HttpSession object resides in memory, waiting for the method to call it again when the same user returns. At the client, the browser saves the session identifier and character the session identifier to the server in each subsequent request. The session identifier tells the JSP container that the current request is not the first request made by the user, and the server has previously created a HttpSession object for that user. At this point, the JSP container no longer creates a new HttpSession object for the user, but instead looks for a HttpSession object with the same session identifier, and then establishes the association of the HttpSession object and the current request. The session identifier is transmitted between the server and the browser in the form of a cookie. If the client does not support cookies, the URL rewriting mechanism is used to ensure that the session identifiers are returned to the server.

Ii. List of P132 on the analysis book

1, long before = System.currenttimemillis ();... long after = System.currenttimemillis (); What do these two statements do?

The purpose of this statement is to specify that the filter is responsible for intercepting all user requests for the filtering range.

2. HttpServletRequest hrequest = (httpservletrequest) request; What is the meaning of this statement?

Casts the request to the HttpServletRequest type and assigns the HttpServletRequest request object Hrequest

3. SYSTEM.OUT.PRINTLN ("Filter has intercepted the user's requested address:" + hrequest.getservletpath ()); What is the meaning of this sentence?

Print filter has intercepted the user's requested address via the Getservletpath () function

Third, write a user authorization with the filter example is to filter the request?

Loginfilter.java

Copy CodeThe code is as follows: public class Loginfilter implements Filter {

Private String permiturls[] = null;

Private String gotourl = null;

public void Destroy () {

TODO auto-generated Method Stub

Permiturls = null;

Gotourl = null;

}

public void DoFilter (ServletRequest request, servletresponse response,

Filterchain chain) throws IOException, Servletexception {

TODO auto-generated Method Stub

HttpServletRequest res= (httpservletrequest) request;

HttpServletResponse resp= (httpservletresponse) response;

if (!ispermiturl (request)) {

if (Filtercurrurl (request)) {

SYSTEM.OUT.PRINTLN ("---> Please login");

Resp.sendredirect (Res.getcontextpath () +gotourl);

Return

}

}

SYSTEM.OUT.PRINTLN ("---> Allow access");

Chain.dofilter (request, response);

}

public boolean Filtercurrurl (ServletRequest request) {

Boolean filter=false;

HttpServletRequest res= (httpservletrequest) request;

User user = (user) res.getsession (). getattribute ("user");

if (Null==user)

Filter=true;

return filter;
}

public boolean Ispermiturl (ServletRequest request) {

Boolean ispermit = false;

String Currenturl = currenturl (request);

if (permiturls! = null && permiturls.length > 0) {

for (int i = 0; i < permiturls.length; i++) {

if (Permiturls[i].equals (Currenturl)) {

Ispermit = true;

Break

}

}

}

return ispermit;

}

Request Address

Public String Currenturl (ServletRequest request) {

HttpServletRequest res = (httpservletrequest) request;

String task = Request.getparameter ("task");

String path = Res.getcontextpath ();

String uri = Res.getrequesturi ();

if (task! = null) {//URI format Xx/ser

URI = uri.substring (Path.length (), Uri.length ()) + "?" + "task="

+ task;

} else {

URI = uri.substring (Path.length (), uri.length ());

}

SYSTEM.OUT.PRINTLN ("Current request Address:" + URI);

return URI;

}

public void init (Filterconfig filterconfig) throws Servletexception {

TODO auto-generated Method Stub

String permiturls = Filterconfig.getinitparameter ("Permiturls");

String Gotourl = Filterconfig.getinitparameter ("Gotourl");

This.gotourl = Gotourl;

if (permiturls! = null && permiturls.length () > 0) {

This.permiturls = Permiturls.split (",");

}

}

}

Xml

Copy CodeThe code is as follows:<filter>

<filter-name>loginFilter</filter-name>

<filter-class>filter. Loginfilter</filter-class>

<init-param>

<param-name>ignore</param-name>

<param-value>false</param-value>

</init-param>

<init-param>

<param-name>permitUrls</param-name>

<param-value>/,/servlet/Loginservlet?task=login,/public.jsp,/login.jsp</param-value>

</init-param>

<init-param>

<param-name>gotoUrl</param-name>

<param-value>/login.jsp</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>loginFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

Iv. summarize the differences between the two sections of code in the Jeett document and analyze the effect of the startup code?

1. First describe what is asynchronous processing, asynchronous tasks

Asynchronous processing: The concept of asynchrony is relative to synchronization. When an asynchronous procedure call is made, the caller cannot get the result immediately. The part that actually handles the call notifies the caller via status, notification, and callback after completion. Take the Casycsocket class as an example (note that CSocket derives from CAsyncSocket, but its functionality has been converted from asynchronous to synchronous), and when a client makes a connection request by calling the Connect function, the caller thread can run down immediately. When the connection is actually set up, the bottom of the socket sends a message informing the object. It is mentioned here that the executing parts and callers return results in three ways: status, notifications, and callbacks. Which one can be used depends on the implementation of the execution part, which is not controlled by the caller unless the execution part provides multiple choices. If the execution part is notified by the state, then the caller needs to check every time, the efficiency is very low (some beginners of multithreaded programming, always like to use a loop to check the value of a variable, which is actually a very serious error). If you are using notifications, the efficiency is high because there is almost no extra action required to execute the part.

Asynctask: That is, asynchronous task, asynchronous. Asynctask is actually an auxiliary class designed around thread and handler, which is an encapsulation of thread and handler inside. Asynctask asynchronous is manifested in the operation of the background thread (access to the network and other time-consuming operations), and then publish the results to the user interface to update the UI, using Asynctask so that I do not have to operate thread and handler.

2. What is the difference between asynchronous and synchronous?

The difference between synchronous and asynchronous is that the requested content is not returned immediately, and the synchronization request needs to wait for the result to return before it can continue execution. Single-threaded execution requires sequential execution, and if a computationally intensive, time-consuming function needs to be executed, the thread must wait here for the result to be evaluated before it can continue execution.

The asynchronous request theoretically does not need to wait for the result of the request, handing out the time-consuming computation to another thread, and notifies the main thread when the result calculation is complete. In fact, the asynchronous request will immediately get a temporary result, and then the asynchronous request can proceed, when the asynchronous thread returns the real result and then notifies the main thread, then the main thread is making the action.

3. Based on the above basics, it is possible to approximate the differences in the code in the document:

(1)request.startAsync()Causes the request to be processed asynchronously; At the end of the service method, the response is not sent to the client.

(2)acontext.start(new Runnable() {…?})Gets the new thread from the container.

(3)run()The code for the method of the inner class executes in the new thread. An inner class can access an asynchronous context to read parameters from a request and write a response. complete()the method that invokes the asynchronous context submits the response and sends it to the client.

The difference in running effect:

Use an example of asynchronous processing to respond faster with heavy loads and server throughput to become larger

Java EE third week job

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.