Java SE 6 new features __java

Source: Internet
Author: User
Tags static class java se

Release date: End of 2006

New features:

The new features in the API library are not too much,

The main features are new features and enhancements in scripts, Web service,xml, compiler APIs, databases, JMX, networking, and instrumentation.

(1), HTTP enhancements

A, NTLM authentication

Inevitably, there are many resources in the network that are protected by security domains. Access to these resources requires authentication of the identity of the user.

Import java.net.*; 
 Import java.io.*; 

 public class Test {public 
	 static void Main (string[] args) throws Exception { 
		 url url = new URL ("Http://PROTECTED. com "); 
		 URLConnection connection = Url.openconnection (); 
		 InputStream in = Connection.getinputstream (); 
		 byte[] data = new byte[1024]; 
		 while (In.read (data) >0) 
		 { 
			 //do something for Data 
		 } 
		 in.close (); 
	 } 
  
 

When a Java program attempts to read information from a Web site that requires authentication, that is, the read data from the InputStream associated with http://Protected.com this urlconnection will cause Filenotfoundexc Eption. The previous version of Java 6 is not supported for NTLM authentication. Users who want to use httpconnection to connect to a Web site that uses Windows domain protection are not authenticated by NTLM.

Java 6 's authentication class provides support for NTLM.

Class Defaultauthenticator extends Authenticator { 
    private static String username = "username"; 
    private static String domain =  "domain"; 
    private static String password =  "password"; 
  
    Public Passwordauthentication getpasswordauthentication () {
        String usernamewithdomain = domain + '/' +username; 
        Return (new Passwordauthentication (Usernamewithdomain, Password.tochararray ()));
    } 
 
 


B, lightweight HTTP server

Java 6 also provides an implementation of a lightweight, pure Java Http server

public static void Main (string[] args) throws exception{ 
	 Httpserverprovider = Httpserverprovider.provider (); 
	 Inetsocketaddress addr = new inetsocketaddress (7778); 
	 Httpserver httpserver = httpserverprovider.createhttpserver (addr, 1); 
	 Httpserver.createcontext ("/myapp/", New Myhttphandler ()); 
	 Httpserver.setexecutor (null); 
	 Httpserver.start (); 
	 System.out.println ("Started"); 
 } 

 Static class Myhttphandler implements httphandler{public 
	 void handle (Httpexchange httpexchange) throws IOException {          
		 String response = "Hello world!"; 
		 Httpexchange.sendresponseheaders (Response.length ()); 
		 OutputStream out = Httpexchange.getresponsebody (); 
		 Out.write (Response.getbytes ()); 
		 Out.close (); 
	 }  
  
 

Access to http://localhost:7778/myapp/in the browser, we get: Hello World


(2), compiler API

A), JDK 6 provides the API to invoke the compiler at run time, and we will assume that the API is applied to JSP technology. In

In traditional JSP technology, server processing JSP usually need to do the following 6 steps: Analysis JSP code; Generate Java code; Write Java code to storage; start another process and run the compiler to compile Java code; Write class files to memory; server Read class files and run.

However, if you use Run-time compilation, you can simplify steps 4 and 5, save new process overhead and write memory output overhead, and improve system efficiency.

package compile; import java.util.Date; public class Target {public void dosomething () {Date da 
         Te = new Date (10, 3, 3);
     This constructor is marked as deprecated, and the compile time//error output information.
   System.out.println ("doing ...");
 }} package compile;
 Import javax.tools.*;
 Import Java.io.FileOutputStream; public class Compiler {public static void main (string[] args) throws exception{String fullquanlifiedfilename = "     
     Compile "+ java.io.File.separator +" Target.java ";

     Javacompiler compiler = Toolprovider.getsystemjavacompiler ();

     FileOutputStream err = new FileOutputStream ("Err.txt");
     int compilationresult = Compiler.run (null, NULL, err, fullquanlifiedfilename);
     if (Compilationresult = = 0) {System.out.println ("done");
     else {System.out.println ("Fail"); }
   }
 }

B, another powerful thing about the JDK 6 compiler API is that it can be compiled in the form of a source file that is not limited to text files.

c), the third newly added feature, is the collection of diagnostic information during compilation. Diagnostic information, usually referred to as error, warning, or verbose output during compilation.

(3), Java Db:java 6 database

The new installer with JDK 6 may find that, in addition to the traditional bin, JRE directory, JDK 6 has added a directory named DB. Java DB. This is a pure Java implementation, open source database management system (DBMS)

public class Hellojavadb {public static void main (string[] args) {try {//load the driver class
            . forname ("Org.apache.derby.jdbc.EmbeddedDriver"). newinstance ();
            System.out.println ("Load the embedded Driver");
            Connection conn = null;
            Properties Props = new properties ();  Props.put ("User", "user1");
           Props.put ("Password", "user1"); Create and connect the database named Hellodb conn=drivermanager.getconnection ("jdbc:derby:hellodb;create=t
            Rue ", props);
            System.out.println ("Create and connect to Hellodb");

            Conn.setautocommit (FALSE);
            Create a table and insert two records Statement s = conn.createstatement ();
            S.execute ("CREATE table hellotable (name varchar (), score int)");
            SYSTEM.OUT.PRINTLN ("Created table hellotable");
            S.execute ("INSERT into hellotable values (' Ruth Cao ', 86)"); S.execute ("Insertinto hellotable values (' Flora Shi ', 92) "); List the two records ResultSet rs = s.executequery ("Select name, score from Hellotable ORD
            ER by Score ");
            System.out.println ("Name\t\tscore");
                while (Rs.next ()) {StringBuilder builder = new StringBuilder (rs.getstring (1));
                Builder.append ("T");
                Builder.append (Rs.getint (2));
            System.out.println (Builder.tostring ());
            }//delete the table S.execute ("drop table hellotable");
            
            SYSTEM.OUT.PRINTLN ("Dropped table hellotable");
            Rs.close ();
            S.close ();
            System.out.println ("Closed result set and statement");
            Conn.commit ();
            Conn.close ();
            
            SYSTEM.OUT.PRINTLN ("Committed transaction and closed connection"); try {//Perform a clean shutdown Drivermanager.getconneCtion ("Jdbc:derby:;shutdown=true");
            catch (SQLException se) {System.out.println ("Database shut down normally"); } catch (Throwable e) {//Handle the exception} System.out.println ("Simpleapp fini
    Shed ");
 

 }
}


A database named Hellodb was created in the DBMS, a data table was created, named Hellotable, two pieces of data were inserted into the table, and then the data was queried and the results printed on the console; Finally, the tables and databases are deleted and the resources are freed.

(4), support for scripting languages

Javax.script package provides interfaces and classes we can easily add support for scripting languages for our Java applications.

public class RunScript {public

    static void Main (string[] args) throws Exception {
        String script = args[0];
        String file = args[1];
       
        FileReader Scriptreader = new FileReader (new file);
        Scriptenginemanager manager = new Scriptenginemanager ();
        ScriptEngine engine = manager.getenginebyname (script);
        Engine.eval (Scriptreader);
    }

 


Java runscript JavaScript run.js
In this way, Java applications can implement complex, variable logic processes with more flexible, weakly typed scripting languages, and then pass the javax. The API provided by the script package gets the results of the run, and when the script changes, simply replace the corresponding script file without recompiling the build project, the benefits are obvious, that is, saving development time and improving development efficiency.


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.