The details that are easy to ignore in Java (i)

Source: Internet
Author: User
Tags event listener html form session id

1.650) this.width=650; "src=" HTTP://S2.51CTO.COM/WYFS02/M00/8C/35/WKIOM1HLFW6JZC6UAAAERC_XGFQ034.JPG-WH_500X0-WM _3-wmp_4-s_2149138607.jpg "title=" 57d3a8110001dd3911070511-210-130.jpg "alt=" wkiom1hlfw6jzc6uaaaerc_ Xgfq034.jpg-wh_50 "/> in a program where the code snippet accesses the same object from a separate concurrent thread, then this code snippet is called a" critical section "

How to fix it: use a synchronous mechanism to protect critical areas


Two ways to synchronize: synchronous block and synchronous method

For synchronization, use the Synchronized method

Each object has a monitor, or a lock.

Java implements asynchronous execution between processes using the monitor mechanism


2.Struts framework based on MVC pattern

The work flow of struts:

When the web App starts, it loads the initialization actionservlet,actionservlet from

Struts-config.xml files to read configuration information and store them in various configuration objects

When Actionservlet receives a customer request, the following process is Executed.

-(1) retrieval and user request matching actionmapping instance, if not present, return the request path invalid information;

-(2) If the Actionform instance does not exist, create a Actionform object and save the form data submitted by the client to the Actionform object;

-(3) determine if form validation is required based on configuration Information. if validation is required, call Actionform's validate () method;

-(4) if Actionform's Validate () method returns or returns a Actuiberrors object that does not contain actionmessage, the form validation is successful;

-(5) Actionservlet determines which action to forward the request to, based on the mapping information contained in the actionmapping, and if the corresponding action instance does not exist, create the instance first and then invoke the Execute () method of the action;

-(6) the Execute () method of the action returns a Actionforward object that actionservlet the JSP component to which the client request is forwarded to the Actionforward object;

-(7) the Actionforward object points to the JSP component to generate a dynamic web page, which is returned to the customer;

Why to Use:

The advent of JSP, Servlet, and JavaBean technology gives us the possibility to build powerful enterprise application Systems. But the systems built with these techniques are very fanluan, so on top of that, we need a rule, a rule that organizes these technologies, and that is the framework in which struts Emerges.

struts-based applications consist of 3 types of components: controller components, model components, View components


The 3.HttpServletRequest class mainly deals With:

1. Read and write HTTP headers

2. Obtaining and setting cookies

3. Read path information

4. Identifying HTTP Sessions


4.== compares two objects for the same address

Equals compares the contents of a two object

= = compares the Object's address, i.e. whether it is the same object;

Equal compares the value of an object.


Whatever new comes out is the Object.

Whatever new comes out is a different object, no matter how similar they are.

Whatever new comes out has its own memory space.


5. The construction method does not need to be synchronized.

The methods defined in the interface are public by Default.

A container holds a reference to an Object.

Each time the construction method constructs a new object, there is no problem that multiple threads can read and write to properties in the same object, so no synchronization is Required.

If a method in the parent class uses the synchronized keyword, and the subclass also overrides the method, the method in the sub-class is not synchronized by default and must be displayed with the Synchronized keyword in this method of the Subclass. of course, the corresponding method in the parent class can also be called in the subclass, so that although the methods in the subclass are not synchronous, the subclass calls the synchronization method in the parent class, and the subclass method is also Synchronized.


6. The relationship between the general relational data model and the object data model has the following correspondence: table corresponding class, record corresponding object, table field corresponding to the properties of the class.


7. Automatic type conversion follows the following rules:

1. If the data type of the participating operation is different, it is converted to the same type first and then the operation is Performed.

2. The conversion is carried out in the direction of increasing data length to ensure that the accuracy is not reduced. for example, int and long operations, the int is converted to long before the Operation.

3. All floating-point operations are performed in double-precision, even if the expression containing only float single-precision arithmetic is converted into double type and then Calculated.

Type 4.char and short participate in the operation, you must first convert to int.

5. In an assignment operation, the type of the right expression must be converted to the type of the left variable if the data type on either side of the assignment number is Different. If the data type length of the right expression is longer than the left side, a portion of the data is lost, which reduces precision.

Represents the rules for type auto-conversion:

Short/char--->int--->unsigned--->long---> Double <---float


Subclass error and Exception for 8.trowable

Exception includes non-inspection exception runtimeexception, and its subclasses, that is, runtime exceptions, run-time exceptions are code bugs,

And check exceptions, which are non-runtime exceptions, the program will find exceptions such as IOException when compiling, such as, when processing a similar file stream, Java enforces the need to handle the file stream exceptions that may be encountered.

RuntimeException is a runtime exception that throws an exception during runtime, and the program can choose whether to Try-catch Processing.

Other check exceptions (non-runtime exceptions, such as ioexception), must be try-catch, or the program will find errors when compiling.


9.Java There are six wrapper classes, boolean, Character, Integer, long, float, and double, literally we can see that they correspond to boolean, char, int, long, respectively, float and Double. The string and date itself are classes, so there is no wrapper class.


The difference between 10stringbuffer and stringbuilder:

1. Comparison of speed of execution: StringBuilder > StringBuffer

2. StringBuffer and stringbuilder, They are string variables, are objects that can be changed, and whenever we use them to manipulate strings, we actually operate on an object and do not create objects like string to manipulate them, so the speed is Fast.

3. StringBuilder: Thread Non-secure

Stringbuffer: Thread-safe

When we are using a string buffer to be used by multiple threads, the JVM does not guarantee that the StringBuilder operation is safe, although he is the fastest, but can ensure that the stringbuffer can be operated correctly. of course, Most of the time we are in a single-threaded operation, so in most cases it is recommended to use StringBuilder instead of stringbuffer, which is the reason for Speed.


For a summary of the three uses:

1. If you want to manipulate a small amount of data with = String

2. Manipulating large amounts of data under a single-threaded operation string buffer = StringBuilder

3. Multi-threaded operation string buffer operation large amount of data = StringBuffer


11. The variable declared in the class has a default initial value, the variable declared in the method has no default initial value, it must be initialized at the time of definition, or an error occurs when accessing the Variable.

The default value of the Boolean type is False


12. Both static and Non-static methods need to be executed after invocation, in the order in which they are executed, regardless of the order in which they are declared in the class, except that the static method is "class.method" and the Non-static method is "object.method", i.e. the latter needs to create an Object.

Static member variables (also called Class variables) are initialized before Non-static member variables, static member variables are initialized when the class is first loaded, all objects share a static member variable, and non-static member variables are initialized when the object is Created.

There are often static blocks in Java that are used to initialize the class before it is generated, regardless of the static in the C + + language of java, which is initialized First. The structure is as follows:

static {

Static Statement code block

}


{

Non-static Statement code block

}

Similarities and Differences.

The same point: when the JVM loads the class and executes before the construction method executes, you can define more than one in the class, typically assigning some static variables to the code BLOCK.

Different points: static blocks of code are executed before non-static blocks of code (static code block--and non-static code block--constructors).

A static block of code executes only once for the first time (or as long as it is accessed), and then not in execution, rather than a static block of code that executes once per new, just like a constructor. A non-static block of code can be defined in a common method (the individual feels less useful), while a static block of code does Not.



1. Static code blocks are automatically executed when the class is loaded, non-static blocks of code that create objects automatically execute code, and do not create objects that do not execute the Class's non-static blocks of Code. Order: Static Code block--"non-static code block-" class Constructor.

2, in the static method can only directly invoke the other static members of the same class (including variables and methods), and not directly access non-static members of the Classes. Because for non-static methods and variables, you need to create an instance object of the class before you can use it, and the static method does not have to create any objects before it is Used.

3, If some code must be executed at the start of the project, we can use static code block, This code is actively executed, it needs to be initialized when the project Starts.


When you do not create an object, you need to use a static method when the other program calls, and the code is executed passively.

The difference: static code blocks are executed automatically;

Static methods are executed only when they are called;

Function: static code blocks can be used to initialize some of the most commonly used variables and objects in a project, and static methods can be used as code that does not create an object or can be Executed.


The difference between 13.abstract class and Interface:

1. Abstract classes can have construction methods, and interfaces cannot have Constructors.

2. There can be ordinary member variables in an abstract class, and there are no ordinary member variables in the Interface.

3. A class can implement multiple interfaces, but can inherit only one abstract class.

Abstract class

Characteristics:

Methods can be constructed in abstract classes

Ordinary properties, methods, static properties, and methods can exist in an abstract class.

Abstract methods can exist in abstract classes.

If there is an abstract method in a class, then the current class must be an abstract class, and abstract classes do not necessarily have abstract methods.

Abstract methods in abstract classes need to have subclass implementations, and subclasses need to be defined as abstract if the subclasses are not Implemented.

Interface

Characteristics:

There is only a method declaration in the interface, there is no method body.

There are only constants in the interface, because the defined variables are added by default at compile Time.

public static final

The methods in the interface are always modified by public.

There is no construction method in the interface, nor can an object that instantiates an interface.

Interfaces can implement multiple inheritance

The methods defined in the interface need to be implemented by the implementation class, if the implementation class cannot implement all the methods in the interface

The implementation class is defined as an abstract class.


14.1. the thread obtains the Object's mutex lock by invoking the Synchronized method of the Object.

2. The thread scheduling algorithm is platform Independent.

3. Create a thread by inheriting the thread class or implementing the Runnable Interface.

Thread scheduling is divided into cooperative scheduling and preemptive scheduling, Java uses preemptive scheduling, that is, each thread will be allocated by the operating system execution time, thread switching is not determined by the thread itself (cooperative scheduling). This is why the platform is Independent.


15. Method Rewriting (override) two of the same two small one major principle:

Method names are the same, parameter types are the same

The subclass return type is less than or equal to the parent class method return Type.

Subclass throws exception less than Equals parent class method throws an exception,

The subclass access permission is greater than or equal to the parent class method Access.


16.1, The Boolean type has only two direct measures: true and False.

2, except the member variable will have the default initial value, the other variable must be initialized before the first use

The default value of the Boolean type is false;

The remaining 7 basic types default Values:

BYTE is (byte) 0;

Short is (short) 0;

int is 0;

Long is 0L;

Float is 0.0f;

Double is 0.0d;

Char is \u0000;

String is null;


Description of the Init,service,destroy method in 17.servlet:

Init method: A method that is called when a servlet instance is created to create or open any servlet-related resources and initialize the Servlet's state, and the servlet specification guarantees that the Init method is not processed before any

The Init () method is the starting point of the Servlet's Life.

Once a servlet is loaded, the server calls its init () method immediately.

Service Method: is the method that the servlet really handles the request sent by the client, called by the Web container, distributes the request to doget, dopost, and so on, based on the HTTP request method (GET, post, Etc.)

Destory method: called by the Web container when the servlet instance is Destroyed.

The servlet specification ensures that all requests are processed before the Destroy method call is completed,

Scenarios in which the Destroy method needs to be Overwritten: releases any servlet-related resource storage opened in the Init method

The state of the stored Servlet. The Destroy () method flags the end of the servlet life Cycle.


18. Class Loading process

Class starts from being loaded into the virtual Machine's memory, and its entire lifecycle includes: load (Loading), validate (verification), prepare (preparation), parse (Resolution), Initialize ( initialization), use (using), and unload (unloading) 7 Stages. wherein, the preparation, validation, parsing 3 parts collectively referred to as the connection (linking).

The order of the 5 stages of loading, validating, preparing, initializing, and unloading is determined, and the load process of the class must begin in this order, and the parsing phase is not necessarily: it can be started after the initialization phase in some cases, This is to support runtime bindings for the Java language (also known as dynamic binding or late binding).

Source: http://www.importnew.com/18548.html


19.java does not allow individual methods, procedures or functions to exist and needs to be subordinate to a class.

Methods in the Java language belong to the members of the object, not to the members of the CLASS. however, the static method belongs to the members of the CLASS.

Methods in the Java language must be subordinate to a class (object), and the calling method is the same as a procedure or Function.


The event processing model provided by 20.Java is a human-computer interaction model. It has three basic elements:

1) event source: that is, the place where the event occurs, that is, the individual components, such as buttons, click the button is actually an event on the component;

2) Event: The event encapsulates what happens on the component, such as button clicks, button loosening, and so on;

3) Event Listener: responsible for listening to specific types of events occurring on the source of the event, and when the event arrives, it must be responsible for handling the corresponding event;


21. the techniques for implementing session tracking in Web development are: session,cookie, address rewriting, hidden domains.

1.Cookies

Cookies are the most widely used session tracking mechanism, where cookies are created by the server and stored on the hard drive of the User's machine, and the cookie information stored on the hard disk on the User's machine is sent back to the server the next time the user accesses the site server Again. General cookies generally do not exceed 4KB, and users ' sensitive information such as credit card account passwords should not be stored in Cookies.

2.URL rewrite

URL Heavy user appended to the end of each URL identified data, the server associated with the identifier to save data about the session, such as when we visit a news, in the address bar we generally see this information: http://www. xxx.com/news?id=??, the question mark that follows the usual ID indicates the ID of the news sheet in the background database for that piece of news. URL rewriting can still work when the client deactivates cookies or does not support Cookies.

3. Hide form fields

In general, when we use hidden form fields in the form, there is a code: <input type= "hidden" name= "xxx" value= "xxx"/>. By assigning a value of type to the hidden value to be hidden, the user cannot see the data of this line of code while browsing, but the user can see it by looking at the source Code.

4.Session mechanism

This mechanism should be used with caution, especially for sites with a large number of visits, because this mechanism is to save the session information on the server Side. If the traffic is particularly large, it is conceivable that the requirements for the Server's endurance are High.


Cookie (used in conjunction with Session)

You can use cookies to store the ID of a shopping session, and in subsequent connections, remove the current session ID and use that ID to extract information about the session from the lookup table (lookup tables) on the Server. Using cookies in this way is a great solution and is the most common way to work with Sessions. however, It is best to have an advanced API to handle all these tasks in sevlet, as well as these tedious tasks: extracting a cookie that stores the session identifier from a multitude of other cookies (after all, There may be many cookies), and determining when an idle session expires, and recycle them; Associate a hash list with each request; generate a unique session Identifier.

URL rewriting

In this way, the client adds some extra data at the end of each url. This data identifies the current session and the server associates the identifier with the user-related data it Stores. URL rewriting is a good conversation-tracking solution that works even if the browser does not support cookies or if the user disables Cookies. URL rewriting has the same drawbacks as cookies, which means that server-side programs do a lot of simple but tedious processing tasks. Even if there are high-level APIs that can handle most of the details, be very careful about each URL that references your site, and the URLs that are returned to the User. Additional information is added even through indirect means, such as the Location field in server Redirection. This limitation means that you cannot have any static HTML pages on your site (at least static pages cannot have any links to site dynamic pages). therefore, each page must be dynamically generated using a servlet or JSP. Even if all the pages are generated dynamically, if the user leaves the session and returns through a bookmark or link again, The session information is lost because the stored link contains the wrong identity Information.

Hidden form fields

An HTML form can contain entries such as the following: <input type= "hidden" name= "session" value= "a1234" >

This entry means that when the form is submitted, the specified name and value are automatically included in the GET or POST Data. This hidden field can be used to store information about the session, but its main disadvantage is that this method can only be used if each page is dynamically generated by the form Submission. Clicking a regular hypertext link does not result in form submission, so hidden form fields cannot support normal session tracking, only for a specific set of operations, such as the checkout process for an online store.


This article from the "learning is easy to learn and learn and cherish" blog, Please be sure to keep this source http://lhf20132175.blog.51cto.com/11029145/1887490

The details that are easy to ignore in Java (i)

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.