Java EE Jobs (iii)

Source: Internet
Author: User
Tags server memory

1. Analyze the filter statement:

Long before =system.currenttimemills ()//is the number of milliseconds to obtain the current time distance 1970-1-1 00:00:00, which specifies that the filter is responsible for intercepting all user requests for the filtering range

long after = System.currenttimemills ()//is the number of milliseconds to get the current time distance 1970-1-1 00:00:00, which specifies that the filter is responsible for intercepting all user requests for the filtering range

HttpServletRequest hrequest = (httpservletrequest) request; Casts the request to the HttpServletRequest type and assigns the HttpServletRequest request object Hrequest

SYSTEM.OUT,PRINTLN ("Filter has intercepted the user's requested address:" +hrequest.getservletpath ())//print filter via the Getservletpath () function The address of the user's request has been intercepted

2. Use filter to write user authorization examples:

Package com.drp.util.filter;

Import java.io.IOException;

Import Javax.servlet.Filter;

Import Javax.servlet.FilterChain;

Import Javax.servlet.FilterConfig;

Import javax.servlet.ServletException;

Import Javax.servlet.ServletRequest;

Import Javax.servlet.ServletResponse;

Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession;

public class AuthFilter implements Filter {

public void Destroy () {

}

public void DoFilter (ServletRequest servletrequest, Servletresponse servletresponse,

Filterchain Filterchain) throws IOException, Servletexception {

The first parameter of the/** 1,dofilter method is a ServletRequest object. This object provides the filter with information about the entry (including

* form data, cookies, and HTTP request headers) are fully accessible. The second parameter is Servletresponse, usually in a simple

* This parameter is ignored in the filter. The last parameter is Filterchain, which is used to invoke a servlet or JSP page.

*/

HttpServletRequest request = (httpservletrequest) servletrequest;

/** If you are processing an HTTP request and need access to servletrequest such as GetHeader or getcookies

* methods that cannot be obtained, the request object must be constructed into a httpservletrequest

*/

HttpServletResponse response = (httpservletresponse) servletresponse;

String Currenturl = Request.getrequesturi (); Obtain the absolute path for the root directory:

String TargetUrl = currenturl.substring (Currenturl.indexof ("/", 1),

Currenturl.length ()); Intercepts the current file name for comparison

HttpSession session = Request.getsession (false);

if (! " /login.jsp ". Equals (TargetUrl)) {

Determines whether the current page is redirected after the landing page page, if it is not to do the session judgment, to prevent the death cycle

if (session = = NULL | | Session.getattribute ("user") = = null) {

* User must manually add session after login

System.out.println ("request.getcontextpath () =" + Request.getcontextpath ());

Response.sendredirect (Request.getcontextpath () + "/login.jsp");

If the session is empty, the user is redirected to the login.jsp page without logging in

Return

}

}

Join the filter chain to continue execution down

Filterchain.dofilter (request, response);

/** invokes the Dofilter method of the Filterchain object. The Dofilter method of the filter interface takes a Filterchain object as

* For one of its parameters. Activates the next related filter when calling the Dofilter method of this object. If there is no other

* A filter is associated with a servlet or JSP page, and the servlet or JSP page is activated.

*/

}

public void init (Filterconfig filterconfig) throws Servletexception {

}

}

Then add in the Config file Web. xml: (Note that the filter was first introduced in version 2.3 of the Serlvet specification.) Therefore, the Web. xml file must use more than 2.3 versions of the DTD. )

AuthFilter

Com.drp.util.filter.AuthFilter

AuthFilter

*.jsp //indicates valid for all JSP files

This will go to the login page if the user is not logged in.

What is 3.session? How does it work? How to use it?

A session is a time interval between an end user communicating with an interactive system, usually the time elapsed between registering and logging out of the system, and, if necessary, a certain amount of operating space.

The specific session in the Web refers to the amount of time that a user has spent browsing a website, from entering the Web site to the browser closing. So from the definition above we can see that the session is actually a specific time concept.

It is important to note that the concept of a session needs to include specific clients, specific server-side, and non-disruptive operating times. A session where the user and the C server are connected when the session is established with the B user and the C server are two different sessions.

How the session works:

(1) When a session is first enabled, a unique identifier is stored in a local cookie.

(2) First, using the Session_Start () function, PHP loads the stored session variables from the session repository.

(3) When executing a PHP script, register the session variable by using the Session_register () function.

(4) When the PHP script executes, the non-destroyed session variable is automatically saved in the session library under the local path, which can be specified by the Session.save_path in the php.ini file and can be loaded the next time the page is browsed.

How to use:

The Session is a Web server-based approach to maintaining state. Session allows you to persist any object during the entire user session by storing the object in the memory of the Web server.

Session is typically used to perform the following actions

Stores information that needs to maintain its state throughout a user's session, such as logon information or other information that a user needs to browse the Web application.

Stores objects that only need to maintain their state between page reloads or a set of pages grouped by functionality.

The role of the Session is that it maintains the user's state information on the Web server for access from any page at any time. Because browsers do not need to store any such information, they can use any browser, even browser devices such as PDAs or mobile phones.

Limitations of persistence methods

As more and more users log in, the amount of server memory required for the Session is increasing.

Each user who accesses the Web application generates a separate Session object. The duration of each Session object is the time of the user's visit plus the time of inactivity.

If you keep many objects in each session, and many users use the Web application at the same time (creating many sessions), the amount of server memory that is used for session persistence can be large, affecting scalability.

Meet session:

1, for variables of value type, a copy of the value type is saved in the session

session["__test0"] = 1;

int i = (int) session["__test0"]+1;

int j = (int) session["__test0"];

Results: I=2,j=1

2, for the reference class new variable, the session is saved in the reference

Cdacommon CDA = new Cdacommon ();

session["__test"] = CDA. GetDataSet ("SELECT top 1 * from Tb_customer");

DataSet ds = (DataSet) session["__test"];

DataSet ds2 = (DataSet) session["__test"];

Ds. Tables[0]. rows[0][0]= "9999";

Results:

Ds. Tables[0]. rows[0][0]== "9999"

Ds2. Tables[0]. rows[0][0]== "9999";

3,session Cycle

After the new browser window starts, a new session starts, triggering the call of global Session_Start, the browser window opened from the first browser window does not start a new session. After the session expires, execution of the page will also trigger Session_Start, which is a new session.

4, call session

For Web Service, the invocation of each method will start a session, you can use the following method to make multiple calls in the same session cwssyscfg cwscfg = new Cwssyscfg (); Cwscfg.cookiecontainer = new System net.cookiecontainer (); Cwssyscfg is a Web service class that sets the Cookiecontainer property to the proxy class for the Web service, as long as the Cookiecontainer property of multiple proxies is the same value, then the Web The invocation of the service is in the same session. Can be implemented by using a singleton pattern.

5,session Data Expiration Date

As long as the page has a commit activity, all entries for the session will be maintained, and the session won't expire if there are no commit activities in the 20-minute (default configuration) page. Multiple data items stored in the session are disabled as a whole.

Preservation of 6,session

In the session, if a non-serialized analogy such as DataView is saved, it cannot be used in the mode of saving the session with SQL Server. The way to see if a class is serialized is to see if the class is marked with [Serializable].

4. Learning Async Task

That is, the asynchronous task, the asynchronous job. 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.

Asynctask must inherit the use. Subclasses must override at least one method (Doinbackground (Params ...) )。 In general, another method (OnPostExecute (Result)) is also overridden.

(1) The asynchronous task uses the following 3 types:

1. Params, the type of argument passed to the task.

2. Progress, the type of progressive unit (Progress units) during the execution of the background calculation. (that is, the background program has been executed a few percent.) )

3. Result, the type of results returned by the background execution.

Asynctask does not always need to use all 3 of the above types. It is simple to identify types that are not in use, just use void types.

(2) 4 Steps to Asynctask

An asynchronous task needs to perform the following 4 steps

1. OnPreExecute (), this step is called by the UI thread immediately after the task is executed.

This step is typically used to create a task that displays a progress bar on the user interface (UI).

2. Doinbackground (Params ...), this step is called by the background thread immediately after the execution of the OnPreExecute () method is completed. This step is often used to perform time-consuming background calculations. The result of the calculation must be returned by the step and passed to the last step. This step can also use Publishprogress (Progress ...). To publish one or more progress units (units of progress). These values will be in Onprogressupdate (Progress ...). The step is published to the UI thread.

3. Onprogressupdate (Progress ...), this step is made by the UI thread in Publishprogress (Progress ...) Called when the method call is complete.

The timing of the execution of the method is not defined. This method shows any form of progress on the UI when the background process is still executing. Typically used to dynamically display a progress bar or to display a log in a text box.

4. OnPostExecute (Result), called by the UI process after the end of the background calculation. The results of the background calculation are passed as parameters to this step.

Java EE Jobs (iii)

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.