Experience sharing: how quickly become master Java
I asked many netizens learning Java Is there any shortcut, I said "no other CD-hand cooked Seoul." However, I will be very willing to learn from their own experiences and write, to make detours less later, helping others is the greatest happiness!
To learn Java, Java must first know the general classification. We know that, since Sun introduced Java, on trying to make it all-encompassing, so Java development to the present, according to the main application is divided into three large pieces: J2SE, J2ME and J2EE, which is SunONE (OpenNetEnvironment) system. J2SE is the Java2 Standard Edition, mainly for desktop application software programming; J2ME is mainly used in embedded system development, such as cell phones and PDA's programming; J2EE is the Java2 Enterprise Edition, mainly for distributed network procedures development, such as e-commerce sites and ERP systems. J2SE development of desktop applications than VC, VB, DEPHI these traditional development language, the advantage seems not obvious. J2ME for beginners, and seems a bit esoteric, but it is very difficult to develop a general development environment. So now, and the best use of the most extensive study is a J2EE. J2EE also includes many components, such as Jsp, Servlet, JavaBean, EJB, JDBC, such as JavaMail. Not up to study the matter 12 days.
So how should learn J2EE? Of course, in the first look at Java syntax, I / O package, Util package, you are all familiar with Lang package? And then learn from the JSP. If you learn HTML, then the matter should be handled more easily, and if not, then you taken to fill an HTML-based bar. In fact, the JSP or Java syntax, it is more like a scripting language, a bit like ASP. Then you learn that one of the Servlet. Servlet is the server-side small program, he was responsible for generating client sent to the HTML file. In the implementation of JSP, Servlet is first converted to run again. Although theoretically could completely replace JSP Servlet, this is the intention of JSP SUN launch, but Servlet Jump to control flow or very convenient, but also the procedures more clearly. Next you should learn to Javabean, you may have to see whether JSP Java embedded in the HTML code in the chaotic manner, in this way with what is the difference between ASP? Fortunately, SUN Javabean can provide your JSP code in the Java package, calling also facilitates easy reuse. EJB is followed, EJB is EnterpriseJavaBean to see the name as if it is Javabean, but it Javabean and still be different. It is an architecture, you can build a safer and more stable enterprise applications. It has been the large number of middleware code (that is, we often hear the Weblogic, Websphere these J2EE servers) to complete, so we have to do very little of code, most of the work in the design and configuration of the middleware. As for JDBC on Needless to say, if you use java database access for the procedure, they should be very familiar with it. Also, if you use Java for e-mail program, you have to look at the Javamail.
Well, the Java and J2EE with some of the basic concepts, you should for some of the procedures, do not empty talk, oh. Find some examples of the best and CD-ROM with the book, so that good procedures can be directly Ctrl + C to Ctrl + V, but also not the boss-you to personally bring it Zaishu again bar, also say directly copying not afraid of mistakes, Why not go ahead? There is always some good to the Java programming article, a good article to Cut down, a problem despite ask, as long as the problem is not too stupid, the general will answer your master. Here are a few good aspects of the Java programming site:
CSDN Forum http://www.csdn.net/
China's most famous Technology Forum, "programmers" that they published in the magazine, you can put in the above question was answered immediately, if you feel good, you can give that person points;
Java Research Organization http://www.javaresearch.org/
There are many original article above, the master or Tingzhi;
Java developers http://www.chinajavaworld.com/
Comparison of Java where all information;
Java.com.cn http://www.java.com.cn/
Look at the domain name to know how cattle, nearing the 10,000 registered users, while the number is 1,000 online about Renqihenwang;
IBM's Developer Network http://www-900.ibm.com/developerWorks/cn/java/index.shtml
IBM Big Blue forever;
Well, I read books, procedures have done, people ask me the question, I can be resolved, is not on a master? Of course not so simple, this is only taken the first step on Long March. Do not believe? Then you go out to a project, you know how you start, you know how you design, do you know how to organize personnel to make development? Now mind you, except for some scattered code, may no longer something else! You are the greatest shortages of actual work experience, rather than books to those created by the procedure. So you Kuaiquhua a Java programming work to do it (in the case of in-school students can do part-time ah), in the practice of improving, which is the fastest. But you have to pray in the company, get a master, and he is also willing to take the trouble to tell you, this seems to be hard for me, oh!
Another way is to read the open source process. We know that most from open source experts, the design reasonable, thoughtful, coupled with the participation of the broad masses of programmers, the value of the code is naturally every word Zhu Ji, sonorous, powerful (sorry, even recently, "Gold Sidacaizi" read more). Java required reading of the two open-source programs is that Jive and PetStore.. Jive is a very well-known abroad the BBS process, completely open source. Forum designed with a lot of advanced technology, such as Cache, user authentication, Filter, XML, and the Forum of the database completely shield the visit can be easily transplanted in different databases. Forum also facilitate the installation and management procedures, and this is our peacetime programming easy to forget a part of (China programmers generally focus only on the technical content programming, but do not consider the feelings of users, this is our software and abroad where the gap). Jive information in the Web site are many, we can study found. I believe you read the code, there will be completely feeling. It is regrettable that after Jive from 2.5 on the open-source is no longer unconditional, while licence restrictions. But fortunately there are China-class Java programmers concerned about it, foreigners do not open source, and the Chinese people will not be able to raise revenue? Here we recommend a Chinese language version of the Jive - J Road. Jive (J Road version) by the Chinese Java sector in the famous banq Jive2.1 version based on the basis of all Chinese, an increase of some practical features, such as mapping, users and user information on the portrait, but also a development team in the continually escalating. You can visit the website http://www.jdon.com/ banq
To download, or to the Technical Forum Tongji ftp://nro.shtdu.edu.cn to server, the installation on what is the problem, can be a boost to the Forum. Pet Store. (Pet shops) SUN company to demonstrate its standardized J2EE programming launched by the open-source process should be very authoritative, wants to learn J2EE EJB and friends not to miss.
You will be pleased to say, Hey, the original master on Java become so simple ah! Remember Tomjava have come across a project manager, they claim that Java is very simple, as long as three months can learn. In fact, those who said such things as small Japan was known as "China scored three months" as touted. Tomjava you not throwing cold water, you are just learned of the skeleton Java, Java has still not learned the essence. Next you have to design a model. Senior programmer is designed to truly master the core of object-oriented thinking of the required course. A design pattern is not specific "technical", it is about ideology, it is not displayed or abstract interface type in the actual case of the flexible application of and wisdom, so you can truly grasp the abstract class or interface applications, to the Java language in the original jump on the basis of further, more importantly, the design repeatedly emphasized that one purpose to you: let your procedures can reuse as much as possible. Information on the design model, we recommend banq or to the website of http://www.jdon.com/, he GOF 23 models accessible to interpretation by the way, pure Java description is classic in the classic. Have time to study it further MVC structure (the Model-View-Control separated from the design of) it, now it is popular Structs it is a way to achieve, but with up Structs is really complicated, as long as we learn the essence of that can be, we can design their own MVC structure. Then you study it further Software Refactoring (restated) and limit XP programming, I believe you also at a higher level.
Done this, you better finishing of your Java code, those classic procedures and common applications sorted out, then build a carefully, and improve their reusability and scalability. You find a few like-minded friends set up a studio bar, you can undertake a number of projects to do, there may be some difficulties in the beginning, but you have accumulated technology, and thoughtful, to take over the project can be quickly finished, I believe we will come after you, therefore, to the Money on the Hualala……
Of course, you can also take part in some open-source projects, on the one hand can improve themselves and the other is to make contributions to China's software industry! Developers on the Internet by CVS cooperate in the development, use QQ, MSN, E-mail discussion contact Tiannahaibei programmers scattered around the same time but with a software development is not very interesting?
Here are two good open-source project web site:
Hubei software development platform http://gro.clinux.org/ public;
Building http://cosoft.org.cn/ Union;
Wow, am glad Oh, I have finally become a master! No, No.. There is an old saying: "the time." You know that the computer industry is the development of the situation? You know Microsoft's. NET blueprints and plans SUNONE between tinge? You know that the development of computer technology will be where? In fact, from the major computer makers recent moves that can be seen "Web services will be the next generation of Internet applications the commanding heights ", and Microsoft. NET blueprint and focus of the struggle SUNONE plan, which is Web services. Web services is a new distributed computing model, which is a series of comprehensive standards (XML, SOAP, UDDI, WSDL, and WSFL). It allows different languages can be easily prepared by the software integration, network resources and Web sites into a service rather than chaos dump. The near future, we will be able to click the mouse at home, we can go on sightseeing trips completed all preparatory work, including the air tickets, the tourist routes, will be good rooms. Please note that this all among all Web sites are automatically completed, it was not the same as now, e-commerce is on the surface, are actually many areas of operation. Perhaps you will feel that this is the Yetan days, but nearby, you may also undertake a project to integrate the two businesses ERP system. Likely upstream enterprises Dephi system is used for, and the downstream enterprise system is compiled using Java. You say that you are Java experts, we all do, how you do it. Therefore, ah, you will need to learn new technologies, such as Web services, and you have to understand that it Dephi (Dephi6 Web services are now provided by the controls).
Part of the Java System you, and may have to. NET integration, so you. NET have to know that? In the end, you may find that you have become a Java master, but a lot of time it is engaged in other technologies. Tai Chi Master, said, the most powerful forms is not the forms, and this is probably the reason!
Because emerging, so Web services available online is not much, I recommend to everyone bar several Web sites:
China http://www.uddi-china.org/ UDDI Technology Alliance;
CSDN the Road column http://www.csdn.net/develop/author/ColumnAuthor/fennivel/ Chaixiao
(Note: Chaixiao Road on the Internet is a well-known figure, he has published many articles on Web services, also has a book, it should be said that the China is the pioneer of Web services technology)
IBM's Developer Network XML & WebService column:
Http://www-900.ibm.com/developerWorks/cn/xml/
But the IBM Web services are pushing people
Java containers of learning experience
Java containers of the learning experience because I am more familiar with C + +, Java learning Java should be the focus of the new concept. This paper is basically Java standards set in the framework of the basic concepts, not examples. The purpose of this paper is to write for a long time after I forgot If these things can be quickly recalled this article together.
1. Interface of the Java container is the foundation of containers interface (such as Collection, such as Map Interface), and not the class. Use interface will be the biggest advantage of the realization of containers and container interface separately, which means you can use the same method to containers and containers is not concerned about what kind of data structure to achieve. Similarly, the Iterator interface also enables users to use the same methods to different containers category. These generic algorithm is the basis.
1.1 Collection Interface
Collection interface has the following basic methods:
Boolean add (Object obj): If add an object, the changes have indeed occurred in pools, then returns true, otherwise returns false
Iterator iterator (): return to a realization of the target of the Iterator interface In addition,
Int size (), boolean isEmpty (), boolean contains (Object obj), void clear (), and many other useful ways
1.2 Map Interface
Map used for the storage keyword / value right. There are basic ways:
Object get (Object key)
Object put (Object key, Object balue)
Set keySet ()
Set entrySet ()
In addition, there are other useful ways.
It is noteworthy that the surface it seems that the keys to constitute a set, but in fact is not the case. But on the other hand if the Map will be seen as a part of assembly, or sometimes it is very convenient. In other words you can use it to create a pool to express that part of the Map. To sum up, one can return to the Map of things including its keys consisting of a Set, which will constitute the value of a set of keys, or by its constituting a Set.
1.3 Iterator interface
Iterator interface has the following three basic methods:
Object next (): Back iterators just across the application of the elements
Boolean hasNext (): determine whether there are containers for the visit to the elements
Void remove (): Delete iterators just crossed the elements NOTE: Java in iterators and STL in the concept of iterators in a very important distinction. In STL, iterators similar to the array index, the use of such iterators can view stored in the position of the elements (similar to the array index i through to visit the same c [i]). Java is not the iteration of this operation. Show closely with the changes in the location of the combine. Each through next () an element of the visit, iterators position will be automatically move forward step.
This problem can understand: Java in the iterators are not at the location of elements, but elements. In this way, each invocation next (), the next iteration of an element will be crossed, but it has just crossed the return of the elements that are cited.
According to the above note, it is easy to draw the following code is wrong:
It.remove ();
It.remove ();
The following code is correct:
It.remove ();
It.next ();
It.remove ();
Typical applications iterators
Iterator it c.iterator = ();
While (it.hasNext ())
(
Object obj = it.next ();
/ / Do something with obj
)
- Interface 1.4
1.4.1 List Interface
List from the Collection interface separation from the List because of the characteristics - orderly collection. Here, in an orderly manner that is not in accordance with the sequence of good size Pai (Sorted), but that can be set to determine the order of the sequence visit. List the features of this view, it has increased the Collection interface to operate through indexing method. For example, add, remove, get, set the parameters of the methods in the table can be added to the index value, thus operating in the location of the index elements.
1.4.2 Set interface
Set List and the different elements inside it is disorderly Therefore, the index can not be any way to operate Set Object
1.4.3 List ListIterator interface with the iteration, than Iterator interface, there are some methods (such as add (), etc.). In addition, because List is a two-way table, it has also increased the Object previous () and boolean hasPrevious (), usage and next () and hasNext () the same.
1.4.4 SortedMap interface contains the following basic methods:
Comparator comparator ()
Object firstKey ()
Object lastKey ()
2. Abstract category containers
2.1 abstract category includes AbstractCollection containers, AbstractList, AbstractSet etc.
Why do we need with 2.2 abstract category?
For example, in the Collection interface definition many useful ways, if realized Collection interface for each category have their own methods to achieve so much, it would be very troublesome. In order to achieve Collection of the realization of the interface more easily, AbstractCollection category for some basic methods (such as add () and iterator ()) into the abstract approach, and the use of these basic methods of other methods (for example, addAll () , etc.), specific has been achieved.
3. Specific containers
3.1 ArrayList and LinkedList
List is achieved interface, there are the ordered set. List interface support indexing methods to access elements of this point, ArrayList do not have any problems, but the LinkedList is a big problem, linked list itself should not support random storage, but as a realization of the List, also provided Listless Random visits to the support, but inefficient. Each method are indexed by an ergodic. I think, in fact we should not let Listless support random access, and Java to achieve this is because I would like to set the framework of the whole system, making linked list and the array can be used the same method to use. To sum up, the LinkedList best not to use random access, and use of iterators.
3.2 TreeSet
TreeSet SortedSet 3.2.1 is a realization. According to the data structure knowledge can know that the tree is highly efficient, and in the Java standard library TreeSet this category, should make full use of TreeSet future to improve the effectiveness of the procedure.
3.2.2 needs attention is: TreeSet as ordered set, it adopted compareTo or Comparator will bring together elements to sort. Any comparison with the same value of the elements (whether or not they are equals ()), both in the TreeSet as the same elements, and thus can not be duplicated. Thus, even if the target is different not join the pool, this is sometimes inconvenient. I am in the preparation of A * algorithm, corresponding to different states sometimes with a heuristic function value, then these different to the state will not be able to join in the TreeSet.
3.3 HashSet
3.3.1 HashSet is very efficient data structure, and TreeSet different, the object is a HashSet equals () method to distinguish between different objects. This only real difference can not be the object of repeated join the pool.
3.3.2 needs attention is: HashSet very efficient, but not object hashCode function identified. General default object hashCode function is based on object memory address that. HashSet good hashCode function is the key to successful use.
4. View
4.1 What is a view?
On the mapping of the use of keySet () method, the method as if the establishment of a new pool, and of all the keywords are entered this set. The actual situation is not the case, this set of any operation will be reflected in the original mapping object.
In fact, keySet () is a realization Set interface object, the object of the operation is to mapping operation. This collection of a view.
4.2 Application of view
4.2.1 existing thread-safe containers into containers: Use Collections.synchronizedCollection (Collection c), in the SDK documentation of the method explained that "Returns a synchronized (thread-safe) collection backed by the specified collection. "
4.2.2 will be available on CD-containers into containers: Use Collections.unmodifiableCollection (Collection c), in the SDK documentation of the method explained that "Returns an unmodifiable view of the specified collection.."
4.2.3 scope of
4.2.4 Arrays in category asList () method
5. Generic algorithm common set of the interfaces is a major advantage can be the development of generic algorithm. Collections can be used in the static general method can also prepare their own generic methodologies.
(Specific algorithm in the content of this omitted)
Summary: 10000000 remember this phrase - not the best containers (data structures), according to the different issues in different containers, in order to meet functional requirements and the optimal efficiency.
Java examples explain the regular expression
Create a regular expression
You can start with something relatively simple learning the regular expression. To fully grasp how to construct the regular expression can look at the documents java.util.regex JDK the Pattern category of documents.
Character character B B \ 0 xhh xhh16 hexadecimal values expressed by the characters \ 0 xhhhh uhhhh16 hexadecimal values expressed by the Unicode characters \ tTab \ n newline \ r Enter at \ f-page website \ eEscape
Regular expressions are a powerful embodied in the character set definition of it (character class). Below are some of the most common character set and the definition of ways, in addition to some pre-defined character sets:
Character Set. Said arbitrary character [abc] that characters a, b, c of an arbitrary (a | b | c same) [^ abc] In addition to a, b, c of the arbitrary character of a (negative) a-zA-Z] from a to z or A to Z of the arbitrary character (range) [abc [hij] a, b, c, h, i, j in an arbitrary character (a | b | c | h | i | j same) (and sets) [az & [hij] h, i, j in a (common) \ s space characters (spaces button, tab, and for trip-page Enter ) \ S non-whitespace characters ([^ \ s]) \ d a figure, which is [0-9] \ D, a non-digital characters, that is, [^ 0-9] \ w characters of a word (word character ), that is, [a-zA-Z_0-9] \ W of the characters in a non-word, [^ \ w]
If you used other languages is the regular expression, you can see a unique backslashed. In other languages, "\ \" means "I just want to in the regular expression, insert a backslash. No special meaning." However, in Java, "\ \", I mean "I want to insert it is an expression of the backslash, with the back of it that the meaning of the characters changed. "For example, if you would like to say one or more of the" character word, "Well, this is the regular expression should be "\ \ w +." If you want to insert a backslash, then to use "\ \ \ \." But like other firms, such as tabbing or only a backslash: "\ n \ t."
Only speaking to you here an example you should document java.util.regex.Pattern JDK Add Bookmark, so it should be easy to find a regular expression pattern has.
Logical XYX followed YX | YX or Y (X) "to match the group (capturing group)." Can be used after the \ i said to be the i-matched group.
Matching the border at the beginning of his $ ^ at the end of his \ b a word boundary \ B, a non-word boundary \ G before the end of a match
Cite a specific example. Below are the expression of these are legitimate, and can match "Rudolph":
Rudolph [rR rR] udolph [] [aeiou] [az] R. ol .* *
Fu said that the number of
"Fu said that the number of (quantifier)" is the definition of the role model should match the number of characters.
- Greedy (greedy): Unless otherwise indicated, or that the number of the greedy at all. Greedy expression has been matched continue until the match does not go so far. (If you find expression matching with the expected results not), most likely because you think that expression will only match in front of several characters, and in reality it is greedy, so it will always match.
- Reluctant (barely): The question indicated that it would at least match the characters. Also known as lazy, minimal matching, non-greedy, or ungreedy.
- Possessive (possession): The only Java support (other languages do not support). It has more advanced, so you may also not be used. As a regular expression matching string will be a lot of intermediate state, (general matching engine will preserve this intermediate state), when the failure of this match will be returned to the Yuan. Possession of expression do not save this intermediate state, therefore, you will not go back to the weight. It is then to prevent the uncontrolled expression, but also to improve operational efficiency.
Greedy Reluctant Possessive matching X - X - X? + Matching one or zero-XX * X *? X * + match zero or more than X X + X +? X + + matching one or more X XX (n) (n)? X (n) + n-XX match precisely (n, n (X),)? X (n, n) + match at least a XX (n, m) X (n, m)? X (n, m) + match n at least, up to the m X
To remind, to get expressions as you mean to run, you should use square brackets to 'X' enclose. For example:
Abc +
It seems that this expression to match one or several 'abc', but if you really use it to match 'abcabcabc', in fact only find three characters. Because the meaning of this expression is' ab 'behind with one or more of the' c '. To match one or more of a complete 'abc', you should be this:
(Abc) +
The regular expression can easily take you to play; This is a built on the new Java language.
CharSequence
JDK 1.4 defines a new interface, called CharSequence. It provides a String and StringBuffer these two categories of the characters in the sequence of abstract:
Interface CharSequence (charAt (int i); length (); subSequence (int start, int end); toString ();)
In order to achieve this new CharSequence interface, String, as well as CharBuffer StringBuffer have been modified. Regular expressions are a lot of operational parameters to be with CharSequence.
Pattern and Matcher
先给an example. The following procedures to test whether a regular expression matching string. The first parameter is the string to match, followed by the regular expression. Regular expressions can have more than one. Unix / Linux environment, a command line under the regular expression must also be used in quotation marks.
When you create a regular expression, you can use this procedure to judge it is not in accordance with the requirements of your work.
/ /: C12: TestRegularExpression.java / / Allows you to easly try out regular expressions / / (Args: abcabcabcdefabc "abc +" "(abc) +" "(abc) (2)") import java.util.regex .*; public class TestRegularExpression (public static void main (String [] args) (if (args.length <2) (System.out.println ( "Usage: \ n" + "java TestRegularExpression" + "characterSequence regularExpression +") ; System.exit (0);) System.out.println ( "Input: \" "+ args [0] +" \ "") for (int i = 1; i <args.length; i + +) (System . out.println ( "Regular expression: \" "+ args [i] +" \ ""); Pattern p = Pattern.compile (args [i]); Matcher m = p.matcher (args [0]); while (m.find ()) (System.out.println ( "Match \" "+ m.group () +" \ "at positions" m.start + () + "-" + (m.end () — 1));)))) ///:~
Java's regular expressions by the java.util.regex Pattern Matcher class and achievable. Pattern said that the object of a regular expression compiler. Static compile () method that will be responsible for a regular expression string compiled into Pattern object. As shown in the above routines, as long as the matcher to the Pattern () method to send a string object will be able to access a Matcher. In addition, there is a Pattern to quickly determine whether the input found inside the regex (Note that the original error, and missed the method)
Static boolean matches (regex, input)
String arrays, as well as to return to the split () method, it can use regex separated from the string.
As long as the Pattern.matcher () method-will be able to gain a string of Matcher object. Next Matcher method can be used to match the results of the enquiry.
Boolean matches () boolean lookingAt () boolean find () boolean find (int start)
Matches () Pattern Matching is the premise of the entire string, and lookingAt () Pattern Matching is the meaning of the beginning of the string.
Find ()
Matcher.find () function is found CharSequence Lane, and a number of pattern matching sequences of characters. For example:
/ /: C12: FindDemo.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; import java.util .*; public class FindDemo (private static Test monitor = new Test (); public static void main (String [] args) (Pattern.compile Matcher m = ( "\ \ w +"). matcher ( "Evening is full of the linnet's wings"); while (m.find ()) System.out.println (m. group ()); int i = 0; while (m.find (i)) (System.out.print (m.group () + "") i + +;) monitor.expect (new String [] ( "Evening "," is "," full "," of "and" the "and" linnet "," s "and" wings "," Evening vening ening ning ing ng g is is s full "+" full ull ll l of of f the the he e linnet linnet "+" innet nnet net et tss wings wings ings ngs gs s "));)) ///:~
"\ \ W +" means "one or more characters in the word", it will be decomposed into direct word string. Find () as an iteration, again from start to finish scanning string. The second find () int parameters of the zone, as you can see, it will start to tell where to find methods - from the beginning View location parameters.
Groups
Group refers to enclose, with the brackets, the following expression can be called a regular expression. Group 0 that the whole pattern, a group that was the first to include the group, and so on. Therefore;
A (B (C)) D
There are three group: group 0 is ABCD, a group is BC, is the C group 2.
You can use the following method to use Matcher group:
Public int groupCount () returns matcher in the target group number. Excluding group0.
Public String group () returns the last match operations (for example, find ()) group 0 (the entire match)
Public String group (int i) return to the operation of the last match of a group. If successful match, but failed to find a group, then returned to the null.
Public int start (int group) to return to the last match found, the group started here.
Public int end (int group) to return to find the last match, the end position group, the last subscript characters plus one.
Below we give some examples of the group:
/ /: C12: Groups.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; public class Groups (private static Test monitor = new Test (); static public final String poem = "Twas brillig, and the slithy toves \ n "+" Did gyre and gimble in the wabe \ n "+" All mimsy were the borogoves, \ n "+" And the mome raths outgrabe \ n \ n "+" Beware the Jabberwock, my son, \ n "+" The jaws that bite, the claws that catch \ n "+" Beware the Jubjub bird, and shun \ n "+" The frumious Bandersnatch. "; public static void main (String [] args) Pattern.compile Matcher m = (( "(? m) (\ \ S +) \ \ s + ((\ \ S +) \ \ s + (\ \ S +))$"). matcher (poem); while (m.find ()) (for (int j = 0; j <= m.groupCount (); j + +) System.out.print ( "[" + m.group (j) + "]"); System.out.println ( );) monitor.expect (new String [] ( "[the slithy toves]" + "[the slithy toves] [] [] [slithy toves]", "[in the wabe.] [] [in the wabe. ] [] [the wabe.] "," [were the borogoves,] "+" [were] [the borogoves,] [the] [borogoves,] "," [mome raths outgrabe.] "+" [mome] [raths outgrabe.] [] [raths outgrabe.] "," [Jabberwock, my son,] "+" [Jabberwock, my son] [] [] [my son], "" [claws that catch.] "+" [claws that catch] [] [] [catch that.] "," [bird, and shun] [bird, and shun] [] [and] [shun] "," [The frumious Bandersnatch.] [The] "+" [frumious Bandersnatch.] [] [frumious Bandersnatch.] "));)) ///:~
This poem is Through the Looking Glass, Lewis Carroll's "Jabberwocky" to the first part. Can see that this is a lot of regular expressions, including parentheses together with the group, it is by any number of consecutive non-space characters ( '\ S +') and any number of continuous space characters ( '\ s +') formed, with the ultimate aim is to capture each on the final three words; '$' to the end of that line. But '$' are usually stated at the end of the string, so here clearly told a regular expression attention to the newline. This is from '(? M)' signs completed (mode markers Guoyihui on).
Start () and end ()
If successful match, the start () will return to the beginning of the match position, end () will return to the position of the end of this match, the final one of the characters and a subscript. If unsuccessful before the match (or did not match), then either call the start () or end (), will trigger a IllegalStateException. Below this procedure also demonstrated matches () and lookingAt ():
/ /: C12: StartEnd.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; public class StartEnd (private static Test monitor = new Test (); public static void main (String [] args) ( String input [] = new String [] ( "Java has regular expressions in 1.4", "regular expressions now expressing in Java," "Java represses oracular expressions"); Pattern p1 = Pattern.compile ( "re \ \ w *" ), p2 = Pattern.compile ( "Java .*"); for (int i = 0; i <input.length; i + +) (System.out.println (" input "+ i +": "+ input [i ]); Matcher m1 = p1.matcher (input [i]), m2 = p2.matcher (input [i]); while (m1.find ()) System.out.println ( "m1.find (), '" m1.group + () + " 'start =" + m1.start () + "end =" + m1.end ()); while (m2.find ()) System.out.println ( "m2.find ( ) ' "+ m2.group () +"' start = "+ m2.start () +" end = "+ m2.end ()); if (m1.lookingAt ()) / / No reset () necessary System . out.println ( "m1.lookingAt () start =" + m1.start () + "end =" + m1.end ()); if (m2.lookingAt ()) System.out.println ( "m2. lookingAt () start = "+ m2.start () +" end = "+ m2.end ()); if (m1.matches ()) / / No reset () necessary System.out.println (" m1.matches () start = "+ m1.start () +" end = "+ m1.end ()); if (m2.matches ()) System.out.println (" m2.matches () start = "+ m2. start () + "end =" + m2.end ());) monitor.expect (new String [] ( "input 0: Java has regular expressions in 1.4", "m1.find () 'regular' start = 9 end = 16 "," m1.find () 'ressions' end start = 20 = 28 "," m2.find ()' Java has regular expressions in 1.4 ' "+" end start = 0 = 35 "," m2. lookingAt () start = 0 end = 35 "," m2.matches () start = 0 end = 35 "," input 1: regular expressions now "+" expressing in Java, "" m1.find () 'regular' start end = 0 = 7 "," m1.find () 'ressions' end start = 11 = 19 "," m1.find ()' ressing 'end start = 27 = 34 "," m2.find ()' Java ' start = 38 = 42 end "," m1.lookingAt () start = 0 end = 7 "," input 2: Java represses oracular expressions, "" m1.find () 'represses' end start = 5 = 14, "" m1.find () 'ressions' end start = 27 = 35 "," m2.find ()' Java represses oracular expressions' "+" end start = 0 = 35 "," m2.lookingAt () = start = 0 end 35, "" m2.matches () start = 0 end = 35 "));)) ///:~
Attention, as long as there are strings in this model, find () will be able to find it out, but lookingAt () and matches (), only in a regular expression string and the beginning of a match, which can be returned to the true. Matches () is the prerequisite for the success of a regular expression and a string perfectly matched, and lookingAt () [67] success on the premise that with the beginning of a string of a regular expression matching.
Matching mode (Pattern flags)
Compile () method is also available in a version, it needs a control is the regular expression matching of parameters:
Pattern Pattern.compile (String regex, int flag)
The value of the flag as follows: compiler signs Pattern.CANON_EQ effect if and only when the two characters "regular decomposition (canonical decomposition)," are exactly the same circumstances, it finds that match. For example, after using this symbol, in the expression "a \ u030A" will match "?." Default situation, we do not consider "the same norms (canonical equivalence)." Pattern.CASE_INSENSITIVE
(? I) default, unknown flu case matching only applies to US-ASCII character sets. The logo can neglect case expression matching. To the Unicode characters matching sense of unknown size, as long as the signs and will UNICODE_CASE together on the trip. Pattern.COMMENTS
(? X) In this mode, when the match will be overlooked (in the regular expression) space characters (Translator note: not the expression of the "\ \ s", but that the expression in space , tab, carriage return of the category). # Notes from the beginning until the end of this trip. Can be embedded to mark the opening of Unix mode. Pattern.DOTALL
(? S) in this mode, the expression '.' Can match any of the characters, including that at the end of his party. By default, the expression '.' Mismatch at the end of the trip. Pattern.MULTILINE
(? M) In this mode, '^' and '$', respectively match and the beginning of his end. In addition, the '^' still match the beginning of a string, '$' the end of the string also matched. By default, these two expressions matched only the beginning and the end of the string. Pattern.UNICODE_CASE
(? U) in this mode, if you have opened CASE_INSENSITIVE signs, then it will Unicode characters unknown flu case matching. By default, unknown flu case matching only applies to US-ASCII character sets. Pattern.UNIX_LINES
(? D) In this mode, the only '\ n'æ‰è¢«recognition for his suspension, and with'.','^', as well as' $ 'match.
In these signs inside, Pattern.CASE_INSENSITIVE, Pattern.MULTILINE, is the most useful and Pattern.COMMENTS (which Pattern.COMMENTS also help us to clarify ideas, and / or doing documentation). Note that you can use in the expression inserted in the way to mark the opening of the majority of the models. These marks in the table aboveé‚£å¼ all signs below. Mode where you want to start, where interpolation mark.
Can be used "OR" ('|') operator of the use of these signs:
/ /: C12: ReFlags.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; public class ReFlags (private static Test monitor = new Test (); public static void main (String [] args) ( Pattern p = Pattern.compile ( "^ java," Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher m = p.matcher ( "java has regex \ nJava has regex \ n" + "JAVA has pretty good regular expressions \ n" + "Regular expressions are in Java"); while (m.find ()) System.out.println (m.group ()); monitor.expect (new String [] ( "java", "Java", "JAVA "));)) ///:~
This created by the regular expression will match "java", "Java", "JAVA" … the beginning of the string. In addition, if the strings at several firms, which it will do on each match (matching sequences of characters at the beginning, and finally sequences of characters at the end of the trip). Note that group () method to return only part of the match.
Split ()
Refers to the so-called segmentation will be a regular expression for the sector, will be split into String string array.
String [] split (CharSequence charseq) String [] split (CharSequence charseq, int limit)
This is a fast and easy text according to some of the common border to sign separate ways.
/ /: C12: SplitDemo.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; import java.util .*; public class SplitDemo (private static Test monitor = new Test (); public static void main (String [] args) (String input = "This! unusual use! of exclamation! points"; System.out.println (Arrays.asList (Pattern.compile ("!!"). split (input)) ); / / Only do the first three: System.out.println (Arrays.asList (Pattern.compile ("!!"). split (input, 3))); System.out.println (Arrays.asList ( " Aha! String has a split () built in!. "split (" "))); monitor.expect (new String [] ( "[This, unusual use, of exclamation, points]", "[This, unusual use , of exclamation! points] "," [Aha!, String, has a, split (), built, in!] "));)) ///:~
The second split () will limit the number of segmentation.
The regular expression is so important, so some features were incorporated into String class, including split () (have seen), and matches (), replaceFirst (), as well as replaceAll (). With the function of these methods Pattern Matcher and the same.
Replacement Operation
Regular expressions are particularly expert replacement text. Here are some ways:
ReplaceFirst (String replacement) string, and the first model of the match in the replace string replacement.
ReplaceAll (String replacement), all the input string, and the match in the model replace all string replacement.
AppendReplacement (StringBuffer sbuf, String replacement) on successive sbuf to replace, rather than replaceFirst () or replaceAll (), the replacement of only one or all of string. This is a very important, because it can call methods to generate replacement (replaceFirst () and replaceAll () only permits the use of fixed strings to act as replacement). With this method, you can distinguish between programming group in order to achieve more powerful replacement function.
Calling End appendReplacement (), in order to return the remaining copies of the string, we must call appendTail (StringBuffer sbuf, String replacement).
Below us to a demonstration of how to use these substitutions. Elaborate, this procedure is handled by its own string beginning of the Notes is the use of regular expressions is extracted and be dealt with after transmission replacement method.
/ /: C12: TheReplacements.javaimport java.util.regex .*; import java.io. *; import com.bruceeckel.util .*; import com.bruceeckel.simpletest .*;/*! Here's a block of text to use as input to the regular expression matcher. Note that we'll first extract the block of text by looking for the special delimiters, and then process the extracted block.! * / public class TheReplacements (private static Test monitor = new Test (); public static void main (String [] args) throws Exception (String s = TextFile.read ( "TheReplacements.java"); / / Match the specially-commented block of text above: Matcher mInput = Pattern.compile ( "/ \ \ *!(.*)! \ \ * / ", Pattern.DOTALL). matcher (s); if (mInput.find ()) s = mInput.group (1); / / Captured by parentheses / / Replace two or more spaces with a single space: s = s.replaceAll ( "(2)", "") / / Replace one or more spaces at the beginning of each / / line with no spaces. Must enable MULTILINE mode: s = s.replaceAll ( "(? m) ^ +", ""); System.out.println (s) s = s.replaceFirst ( "[aeiou]", "(VOWEL1)") = new StringBuffer StringBuffer sbuf (); Pattern p = Pattern.compile ( "[aeiou]"); Matcher m = p.matcher (s) / / Process the find information as you / / perform the replacements: while (m.find ()) m . appendReplacement (sbuf, m.group (). toUpperCase ()) / / Put in the remainder of the text: m.appendTail (sbuf); System.out.println (sbuf); monitor.expect (new String [] ( "Here's a block of text to use as input to," and "the regular expression matcher. Note that we'll", "first extract the block of text by looking for", "the special delimiters, and then process the," " extracted block. "," H (VOWEL1) rE's A blOck Of tExt tO UsE As InpUt tO "," thE rEgUlAr ExprEssIOn mAtchEr. NOtE thAt wE'll "," fIrst ExtrAct thE blOck Of tExt by lOOkIng fOr "," thE spEcIAl dElImItErs, thEn prOcEss thE "," ExtrActEd blOck. "));)) ///:~
We introduced by the previous TextFile.read () method to open and read documents. MInput function is'/*!' and'!*/' match between the text (to the attention of the group with brackets). Next, we will all more than two consecutive spaces all as a replacement, and the trip will be the beginning of the space are removed (this is to allow the expression of the will of all firms, not just the first line work, Multi-line must be enabled). These two operations are used String of replaceAll () (more convenient to use it here). Attention, as each replacement only once, in addition to pre-compiler Pattern Therefore, no additional procedures expenses.
ReplaceFirst () only the first sub-string replacement. In addition, replaceFirst () and replaceAll () can only constants (literal) to replace, so if you replace each time to carry out some operation, they are powerless. Encountered such a situation, to use your appendReplacement (), which enables you to replace the time to write in the number of written code number. During that in the above procedures, the process of creating sbuf to deal with the elected group, which is a regular expression with the vowel letters find out, and then changed the course of capital. Usually you have completed all of the replacement after calling appendTail (), but if we imitate replaceFirst () (or "replace n") effects, you can only call on a replacement appendTail (). It would put all things remaining sbuf.
You can also appendReplacement () replacement parameters, "$ g" quoted the group has been arrested, 'g' group said the number. But this is to prepare the operation is relatively simple and, therefore, its effect can not be compared with the above-mentioned procedures.
Reset ()
In addition, it can be reset () method to existing Matcher object accompanied by new CharSequence.
/ /: C12: Resetting.javaimport java.util.regex .*; import java.io. *; import com.bruceeckel.simpletest .*; public class Resetting (private static Test monitor = new Test (); public static void main (String [] args) throws Exception (Matcher m = Pattern.compile ( "[] [aiu frb gx] []"). matcher ( "fix the rug with bags"); while (m.find ()) System. out.println (m.group ()); m.reset ( "fix the rig with rags"); while (m.find ()) System.out.println (m.group ()); monitor.expect (new String [] ( "fix", "rug," "bag", "fix" and "rig", "rag"));)) ///:~
If we fail to give parameters, reset () will be set up to the current Matcher at the beginning of the string.
Regular Expression and Java I / O
So far, all you see with a regular expression handling static string example. Below us to a demonstration of how to use a regular expression matching scanned documents and find the string. Inspired by the Unix grep, I wrote a JGrep.java, it requires two parameters: the file name, as well as the matching string with a regular expression. It will match a regular expression that this part of the trip and its affiliated firms, print it.
/ /: C12: JGrep.java / / A very simple version of the "grep" program / / (Args: JGrep.java "\ \ b [Ssct] \ \ w +") import java.io. *; import java . util.regex .*; import java.util .*; import com.bruceeckel.util .*; public class JGrep (public static void main (String [] args) throws Exception (if (args.length <2) (System . out.println ( "Usage: java JGrep file regex"); System.exit (0);) Pattern p = Pattern.compile (args [1]); / / Iterate through the lines of the input file: ListIterator it = new TextFile (args [0]). listIterator (); while (it.hasNext ()) (p.matcher Matcher m = ((String) it.next ()); while (m.find ()) System.out . println (it.nextIndex () + ":" + m.group () + ":" + m.start ());))) ///:~
Document is opened using TextFile (the first part of this chapter stresses). As TextFile will document the trip on ArrayList inside, and we extract a ListIterator, so we can document the trip in which freedom of movement (both can also move backward).
Each row will have a Matcher, then find () scan. Note that we use ListIterator.nextIndex (), line tracking.
Test parameters are JGrep.java and [Ssct] the beginning of the word.
StringTokenizer need?
See the regular expression can provide such a powerful function, you might suspect, is not also need the original StringTokenizer. JDK 1.4 previously, in order to split the string, with only StringTokenizer. But now, with a regular expression, the more it can do the clean and agile.
/ /: C12: ReplacingStringTokenizer.javaimport java.util.regex .*; import com.bruceeckel.simpletest .*; import java.util .*; public class ReplacingStringTokenizer (private static Test monitor = new Test (); public static void main (String [] args) (String input = "But I'm not dead yet! I feel happy!"; StringTokenizer stoke = new StringTokenizer (input), while (stoke.hasMoreElements ()) System.out.println (stoke. nextToken ()); System.out.println (Arrays.asList (input.split ( ""))); monitor.expect (new String [] (" But "," I'm "," not "," dead , "" yet! "," I "," feel "," happy "," [But, I'm, not, dead, yet!, I, feel, happy!] "));)) / / /: ~
With the regular expression, you can use more complex models will be separated from the string - to StringTokenizer If so, things will be much more trouble. I can be very confident that the regular expression can replace StringTokenizer.
To further study the regular expression, I suggest you look at Mastering Regular Expression, 2nd Edition, the author Jeffrey EF Friedl (O'Reilly, 2002).
Aggregate
Java I / O stream class library should be able to meet your basic needs: you can use it to read and write the console, documentation, memory, and even Internet. You can also use the inheritance to create new input and output types. You can even use the Java objects will automatically call the toString () method of characteristics (Java only the "automatic conversion"), through the re-definition of this method to pass on to the target flow to a simple expansion.
But Java's I / O libraries and documentation flow or left some deficiencies. For example, you open a file往里é¢write things, but the document has been published, the original will do to the content of the coverage. Then if anomalies like to have a - some programming language allows you only to the provisions of the new document output. Java appears to File object you use to judge whether the document exists, because if you use FileOutputStream FileWriter or so, the paper will be covered.
I I / O stream class library evaluation is a contradiction that it is capable lot of things, and do the cross-platform. But if you do not know decorator mode, it will find this design too difficult to understand, so regardless of the teachers or students, have spent much energy. In addition the class library is complete, otherwise, I also do not need to write a TextFile. In addition, it did not provide formatted output functions, and other languages have been provided this capability.
However, if you really understand the decorator patterns, and to begin flexibility in the use of this class library, you can feel the benefits of this design. Then write a few more lines of code on a nothing.
If you feel thirsty (just to be a of this chapter, thought to be exhaustive), and look at Elliotte Rusty Harold write Java I / O (O'Reilly, 1999). This book put it deeper.
(Original) TimeStamp control with the use of [example] - HTML pages script
This example has been fully tested and, if other requirements of its own modifications:
2 <! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.0 Transitional / / EN">
3 <HTML>
4 <HEAD>
5 <title> WebForm1 </ title>
6 <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
7 <meta name="CODE_LANGUAGE" Content="C#">
8 <meta name="vs_defaultClientScript" content="JavaScript">
9 <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
10 </ HEAD>
11 <body MS_POSITIONING="GridLayout">
12 <form id="Form1" method="post" runat="server">
13 <FONT face="宋体">
14 <TABLE id="Table1" cellSpacing="1" cellPadding="1" width="300" border="1">
15 <TR>
16 <TD align="right"> primary key out </ TD>
17 <TD>
18 <asp:TextBox id="tbKey" runat="server" ReadOnly="True"> </ asp: TextBox> </ TD>
19 </ TR>
20 <TR>
21 <TD align="right"> general presentation </ TD>
22 <TD>
23 <asp:TextBox id="tbValue" runat="server"> </ asp: TextBox> </ TD>
24 </ TR>
25 <TR>
26 <TD align="right"> timestamp </ TD>
27 <TD>
28 <asp:TextBox id="tbTimeStamp" runat="server" ReadOnly="True"> </ asp: TextBox> </ TD>
29 </ TR>
30 </ TABLE>
31 </ FONT>
32 <asp: Button id = "Button1" style = "Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 112px" runat = "server"
Text = 33 "Update"> </ asp: Button>
34 <asp:Label id="Label1" style="Z-INDEX: 102; LEFT: 80px; POSITION: absolute; TOP: 120px" runat="server"> Label </ asp: Label>
35 </ form>
36 </ body>
37 </ HTML>
38
Why always IOException
Although MS for us to consider things more and more, more and more programmers are not so mysterious, but there is always something more than a flaw. SerialPort said last category, in this thing. NET Framework, there is no problem, but one that always appeared on the Compact Framework IOException, essentially the same code is passed, and therefore suspected Bug, no way, and began to write their own a serial category.
Fortunately, not seen before in the serial category before MS also intends to write their own, to get very smooth, now used throughout the serial parts of use
This base class a feeling of the very cool.
ä¸çˆ½only that the hearing teammates say that today has been allowed to look us without our code (in fact, you say you read it), is that steal other people's work outcomes, compared shameful.
Well, today a bit YY ah
In the MySQL activate the option to add-character-set default = gb2312
- with-charset selection of projects:
Shell>. / Configure - with-charset = CHARSET
CHARSET can be big5, cp1251, cp1257, czech, danish, dec8, dos, euc_kr, gb2312 gbk, german1, hebrew, hp8, hungarian, koi8_ru, koi8_ukr, latin1, latin2, sjis, swe7, tis620, ujis, usa7, or win1251 win1251ukr one. See 9.1.1 for data collection and sequencing of the characters. Note: If you want to change the character set, you must make distclean done during configuration! If you want to transform between the server and client characters, you should look at the SET OPTION CHARACTER SET command. See 7.25 SET OPTION syntax. Warning: If you create a database table after any change character set, you will be running on each table myisamchk-r-q, otherwise, you might not be an index to sort correctly. (If you installed MySQL, create the table, and then re-configured MySQL use a different set of characters and re-install it, and you have such a situation may occur.)
Hibernate: Communication link failure: java.io.IOException
I recently launched a new site based on Struts, Hibernate and MySQL and immediately ran into a weird issue where Hibernate lost the ability to make database connections after a long period of inactivity. For the record, the stack trace is below:
Java.sql.SQLException: Communication link failure: java.io.IOException
At org.gjt.mm.mysql.MysqlIO.sendCommand (Unknown Source)
At org.gjt.mm.mysql.MysqlIO.sqlQueryDirect (Unknown Source)
At org.gjt.mm.mysql.Connection.execSQL (Unknown Source)
At org.gjt.mm.mysql.PreparedStatement.executeQuery (Unknown Source)
At net.sf.hibernate.impl.BatcherImpl.getResultSet (BatcherImpl.java: 83)
At net.sf.hibernate.loader.Loader.getResultSet (Loader.java: 794)
At net.sf.hibernate.hql.QueryTranslator.iterate (QueryTranslator.java: 846)
At net.sf.hibernate.impl.SessionImpl.iterate (SessionImpl.java: 1540)
At net.sf.hibernate.impl.SessionImpl.iterate (SessionImpl.java: 1513)
At net.sf.hibernate.impl.SessionImpl.iterate (SessionImpl.java: 1505)
Looks like there are other people having the same problem, the first suggestion was to use the Thread Local Session pattern, which I already had in place. The solution was to add the following properties to my hibernate.cfg.xml:
<property Name="connection.autoReconnect"> true </ property>
<property Name="connection.autoReconnectForPools"> true </ property>
<property Name="connection.is-connection-validation-required"> true </ property>
Which I believe are specific to MySQL, but as far as I can tell, aren't documented anywhere on the Hibernate site (or should they be documented on the MySQL JDBC driver site?)
For what it's worth, Hibernate is a dream come true. I don't like writing create, update, and delete SQL statements and I've found that the software I've written is much easier to manage and troubleshoot. If you haven ' t played with it yet, check it out now.
Allows you to directly support the Eclipse WebLogic (activated release).
Allows you to directly support the Eclipse WebLogic (activated release).
Nonsense less. To me on the pilot for the Weblogic8.1
1. Weblogic8.1 correct installation, and create domain MyDomain
2. Eclipse open, point Debug …
3. Creation of a new JAVA Application configuration.
Point button <New>, from the name, TU, called MyWeblogic This is the start of our paper, we have to configure Below him.
4. Configuration startup files
MyWeblogic configuration leaves a total of six (Eclispe3.0)
1) main
2) arguments
3) jre
4) classpath
5) soure
5) common
Go through configuration
==== ==== Classpath
User class: Weblogic fill in the necessary start-up jar, and the user's own jar
>>> Necessary jar: weblogic.jar/webservices.jar/ojdbc14.jar
>>> Must order: weblogic.jar/webservices.jar/ojdbc14.jar / user JAR
*** Item here can add the output path, and then set up the config.xml Weblogic virtual path can be issued.
== == Main
Progect: choose your projects to start this project with the best inside Weblogic.jar (and the path we should bea \ weblogic81 \ server \ lib)
Main calss: This call is initiated Weblogic8.1 the mail function. Options below, a single box, and then have the right of the Search, type keyword Server, View weblogic.jar this package (path we should bea \ weblogic81 \ server \ lib), if not, you will need to add classpath configuration page bea \ weblogic81 \ server \ lib \ Weblogic.jar
=== == Arguments
VM arguments: Weblogic start parameters: the following form "- Xms32m-Xmx200m-XX: 128m-Dweblogic.Name MaxPermSize = = myserver-Dbea.home =" C: / bea "-Dweblogic.management.username = weblogic-Dweblogic.management. password = weblogic-Dweblogic.ProductionModeEnabled false-Djava.security.policy == = "C: / bea/weblogic81/server/lib/weblogic.policy"
In accordance with their own specific data and change.
Working directiory: This selected local directory, select the path domain, such as: c: \ bea \ user_projects \ domains \ Mydomain
Other === =====
Default can be
Virtual path settings: configuration file path .. \ bea \ user_projects \ domains \ gdltdomain \ config.xml
Laws:
<Application Name = "MyProject"
Path = "D: \ Tools \ eclipse-SDK-3.0M4-win32 \ eclipse \ workspace \ TestProject"
StagingMode = "nostage" TwoPhase = "true">
<WebAppComponent Name="WebRoot" Targets="myserver" URI="WebTest"/>
</ Application>
Almost ~ ~ Oh
Junit some API
In the eclipse inside Development junit really convenient, as long as the corresponding right of the midpoint of the paper, "new "–>" junit test case" can generate a test-class, mostly inside the code have everything.
However, the methods to test access to as a "public"
Below briefly to the top of the static type junit.framework.Assert used. These included seven main methods:
1. AssertEquals () method, used to view objects in the value of the deposit is looking forward to the value of the string comparison with the use of the equals () method similar;
2. AssertFalse (), and assertTrue () method, is used to view the variables whether false or true, if assertFalse () Show the value of the variable is false is tested successfully, if it is true then fail, assertTrue () contrary.
3. AssertSame () and assertNotSame () method used to compare two objects and the application of the equal not equal, similar to the adoption of "==" and "! =" Compare two objects;
4. AssertNull () and assertNotNull () method, whether to Show for air and not air.
Part of the code
Public void testId () (
Book.setId ( "001"); / / id the value of the attribute set for 001
/ / Assert Show id attribute values for the 001
Assert.assertEquals ( "001", book.getId ());
System.out.println ( "id attributes to be tested!");
)
Public void testName () (
Book.setName ( "ASP") / / set the value of the attribute name for ASP
/ / Assert Show whether the value of the attribute name for JSP, it is inevitable that the wrong test Assert.assertEquals ( "JSP" book.getName ());
System.out.println ( "name attributes to be tested!");
)
Green successful tests will show the progress of the failed test will show the progress of the red
Public static void main (String [] args) (
/ / Use TestSuite final assembly and testing of TestSuite ts = new TestSuite ();
Ts.addTestSuite (BookTest.class);
/ / Textui, command line junit.textui.TestRunner.run (ts);
/ / Swingui, Swing way / / junit.swingui.TestRunner.run (ts.getClass ());
/ / Awtui, AWT way / / junit.awtui.TestRunner.run (ts.getClass ());
)
TestSuite is one of the tests used to organize, through its addTestSuite () method will be added to the test-class ts object, all add to ts in the category will be tested in junit.textui.TestRunner.run () is executed. In addition, you can object in the definition ts use its constructor function will be added to the test-class ts object, such as:
TestSuite ts = new TestSuite (BookTest.class);
This does not affect the use of follow-up addTestSuite () method. Again, JUnit offers three operating mode, junit.textui.TestRunner the command line, and junit.awtui.TestRunner junit.swingui.TestRunner visualization is the way, and the latter two have in front of them here, and if you want to see results, the Notes will be removed.
JAVA anomaly in the use of Thinking
In this era of open-source framework for the grade, people often are very concerned about the structure itself into all kinds of new ideas, and the exception handling mechanism is often overlooked. In fact, a framework for dealing with the abnormal way is to maintain its stability. And an application framework itself on the unusual approach, its users will be dealt with the abnormal way in which profound impact. This paper made reference to some of the masters of abnormal use JAVA discussion, and put forward the views of a few simple, as theæŠ›ç –å¼•çŽ‰for, let us explore together.
In JAVA, can be seen as abnormal actually is a method of non-normal return values. For example, User getUser (String usrName) This method should have been returned to a user group, but when the abnormality occurs, the methods and did not return to User, but returned to a Exception. Under normal circumstances, a non-return value is abnormal.
In the abnormal is normal method of the return value of this non-ideological, we can explore the following questions:
1. Any time should be used (custom) Exceptions
2. Use should check anomalies (CheckedException, I think that if translated into more appropriate controllable abnormal), or abnormal operation (RuntimeException).
What time should be used anomaly:
Since the definition of abnormal use of the time, there is a more general spread of the argument: anomaly can only be used to deal with the "real anomalies", can not participate in the process control, as excessive use of the unusual properties would cause the loss, in our system, we should minimize the use of defined exception.
First, let us look at what is the "real anomaly."
Under normal circumstances people think that the operating system level (JDK is a precise) dished out the anomaly is the "real anomaly." However, the so-called "system-level anomaly" and "application-level anomalies" in many cases it is difficult to define. For example, a word-processing software, "NoEnoughSpaceException" Is this unusual system-level or application level? From the system's point of view, not enough disk space should belong to the system-level anomaly. But from the point of view of application, the document could not be preserved, but also application-level anomaly. Therefore, I think that this classification method from the point of view of taxonomy is unscientific: the so-called "system-level" and "application-level" the scope of coverage each other often.
Besides a more pragmatic view is that, from a methodological point of view of the function of deciding whether the use of anomaly. In front of the "anomaly is in fact a special return values," saying, for example as follows:
User getUser (String usrName), users expect User object, but if there are really special to happen, and the user has no pre-judgement, then we can only throw an error. Here might be thrown in the anomaly is a custom anomaly: "user does not exist."
Boolean isUserExist (String usrName), the user in determining whether the user is there, so we certainly did not need to dish out the "user does not exist" anomaly, only to return a Boolean value can be.
Void registUser (String usrName), this method did not return to duty, so if there is the unusual circumstances, can only throw an error. Here might be thrown abnormal "user name has been used," "prohibit the registration system."
I think that the second method is the use of abnormal more scientific and more intuitive: everything from the effectiveness of starting. In this approach, under the guidance of, we might be in the system a lot since the definition of abnormal.
Some people think that anomaly should not be involved in process control, process control and participation in such abnormal ironic "SuperIf." On this issue we can RUP reference flow on the unusual event exposition, RUP to the conclusion that "abnormal situation is the reality of the objective existence of a class of incidents, it must be carried out when we deal with, to deal with this anomaly in stream" . JAVA will result in abnormal process as a means of control, and RUP coincides with the concept of abnormal flow, and the abnormal processing can be carried out in an irregular block.
Some may fear that large-scale use of the unusual properties will bring the loss. Performance is another issue to the huge size of the demonstration, we can make reference to Rod Johnson in his "J2EE Without EJB", a book on performance optimization analysis. In short sentence is: by all language-level optimization efforts, in a I / O or write to the database will come to naught. Therefore the use of the unusual properties of small losses, it is not "its word performance."
Use checks or abnormal abnormal operation:
This issue more controversial, such as extreme Bruce Eckel and Anders Hejlsberg, think that we should abolish all CheckedException, with the definition of news RuntimeException replacement, Bruce even personally given piece of code will tell you how to CheckedException RuntimeException. And James Gosling used CheckedException the fire, it was ironic James: In his eyes, users are God, and have the ability to deal with such as "IOException" Such things no one approach. Rod Johnson relatively moderate, in his view CheckedException its usefulness of: similar James Gosling said, when the need for a user to respond to special circumstances, we can use CheckedException to remind users "such a situation could occur, you should be it processed. "
But Rod greatly narrowed the scope of this situation, in his view only when abnormal flow must be special treatment, the use of only CheckedException demand. For example, int registUser (String usrName) method for registered users. This API provides the author, when the return value of 0, a representative registered success as a return value, on behalf of users who have already spent; return value to 2, on behalf of the registration system to prohibit…… In such circumstances, we should use CheckedException, rather than RuntimeException or simple return values. This is because apart from each return value of 0 is represented by an abnormal flow, and each abnormal flow should be carried out special treatment, such as user name already, we may have to remind automatically transferred to a page can be used to remind users of the other users of prohibit the registration, we have to enter a Notice pages, the pages display the reasons for the ban on the registration and opening hours, and so on.
On the above situation, they can do a more accurate summary: only when abnormal involved in the process control, it should be used CheckedException.
How then should we judge whether the anomaly should be involved in the process control? Such a judgement can demand from the start. If demand requires us this anomaly in the flow, it is necessary to conduct A deal with the abnormal flowé‚£æ¡to B to deal with, obviously, here CheckedException should be used to control the process. If demand is "the event of an anomaly in the interface on the tips," then such circumstances, we have no need to use CheckedException, as long as the use of a news RuntimeException can be.
CheckedException use of a significant problem, because each user must be thrown out of the way to respond to the CheckedException, once the method has been widely used, it is necessary to add a new CheckedException becomes very difficult: Each user to be amended accordingly. But from another perspective, if you add CheckedException reason is indeed "demand requirements, we have to deal with it special," then the users of each method should add a new catch, and this new increase special treatment.
The issue also reminds us that the use of CheckedException time, we must determine whether this situation needs "special treatment" Otherwise, as far as possible to replace RuntimeException.
keep looking »