Javaweb Foundation Strengthening (20)

Source: Internet
Author: User
Tags apache tomcat

Generic basic knowledge Review 1. Generic Basic Overview
Definition:) arraylist<e>  :  <>typeofe: Type formal parameter (with class with generics:) New arraylist<integer> () Integer: Type actual parameter arraylist<e>  : generic type arraylist<integer>: Parameterized type   (in Java there is a type to represent the Parameterizedtype)
2. Generic Basic definitions
1. How to define a generic type of your own, with t representing a generic types 2. A generic is declared before it is used, and the declared position is declared 3 with <T> before the return value. When an instance method of a class is generic, it can be further simplified by declaring the class as generic class 4. How do I declare a class to be a generic class? is to add <t>5 to the class name at the same time as the class declaration. If a class declares a generic class, the inner instance method does not have to declare the generics to be 6. If a class declares a generic class, the static method must declare the generic public static <T> T Fillbean (map map, class<t> clazz) throws Exception {//static method, A static method must declare a generic t bean = clazz.newinstance (), regardless of whether the class has a declared generic type; Beanutils.populate (bean, map); return bean;}
3. Generics Simple Application
1. Write a generic that implements the specified position Exchange public static <T> void Swap (t t[], int x, int y) {T temp = t[x];t[x] = t[y];t[y] = temp;} 2. Invert any array public static <T> void reverse (T t[]) {for (int start=0, end=t.length-1; start<=end; start++,end--) {SWA P (t,start,end);}}
DAO design Patterns and the reflection of generics
Class clzz1 = This.getclass ();//this refers to the current class   in the test class jdaotest, New Customerdaoimpl (), who, this refers to who//2. Find the current CLZZ1 generic parent Type type = Clzz1.getgenericsuperclass (); Parameterizedtype pt = (parameterizedtype) type;//3. Find the parameters of the generic parent class Classclz = (Class) pt.getactualtypearguments () [0];// A value that takes an array with a subscript of 0

Note (Annotation) 1. Basic knowledge of annotations
The @override//jdk1.6+ in the JDK can only be     used when the method overrides in the interface override@override  //jdk1.5+ to use the override @ when the method overrides in the parent class        Deprecated  //represents that the method is obsolete, there may be a better alternative to the   maintenance of system updates @suppresswarnings ({"All"  })//Eliminate some warning message "unused", "rawtypes "," unchecked "How to customize Note 1. How to define the annotation public @interface the name of the annotation {}2. What can I write in the annotations? 1). Only write property 1. Must be a public 2. Add one () 2) after the property. If you want to add the default default value,   such as: public int A () default 1;      3). What types of attributes can be written in annotations only? Only primitive type, String, Class, annotation, enumeration is permitted or 1-dimensional arrays         basic type                    Class
     annotation              Enumerations                     and the one-dimensional arrays they form
2. Reflection of annotations
1. Annotation Get method Java.lang.reflect.AnnotatedElementT getannotation (Class clazz): Gets the specified annotation type annotation[] Getannotations (): Get all the annotation types annotation[] getdeclaredannotations (): Get yourself above the direct annotation type of the Boolean isannotationpresent (Class clazz): There are no specified annotations such as class, Method, Field, constructor, etc. all implement the interface. For example: Class clazz = Object.class; Boolean B = clazz.isannotationpresent (Myann1.class); The object class has no MYANN1 annotations 2, the life cycle of the annotations: 2.0 yuan Annotations: Annotations that can only be used on annotations are meta annotations. [email protected]: Change the life cycle of annotations Retentionpolicy.source Retentionpolicy.class (default) Retentionpolicy.runtime[email  protected]: Indicates where annotations can be used ElementType: enumeration [email protected]: Whether annotations appear in Javadoc documents [email protected] : Whether subclasses of a class that use annotations automatically own annotations 
New features of Servlet3.0
1. Use Servlet3.0 prerequisites? jdk1.6+ Tomcat7.0 or above 2.Servlet annotation configuration @webservlet () @WebServlet (value={"/servlet/helloservlet", "/1.jpg"},initparams={ @WebInitParam (name= "encoding", value= "UTF-8"), @WebInitParam (name= "CGX", value= "AJ")// ServletConfig can take out the initialization parameters in the annotations servletconfig sconfig = Getservletconfig (); String Encodingvalue = sconfig.getinitparameter ("encoding"); System.out.println (Encodingvalue);//Get multiple initialization parameters enumeration<string> enumsss =sconfig.getinitparameternames (); while (Enumsss.hasmoreelements ()) {String paramname = (string) enumsss.nextelement ();//Get parameter name String paramvalue = Sconfig.getinitparameter (paramname); System.out.println (paramname+ ":" +paramvalue);} 3.Servlet annotation configuration for file upload Commons-fileupload-xxx.jar is Apache Tomcat is also Apache------------->tomcat7.0+ integrated File upload functionality (using this feature is added an annotation) @MultipartConfig @multipartconfig//Represents the current servlet's ability to handle file uploads--------->request.getpart (" FileName "). Write (" Disk path "), Example: File Upload code response.setcontenttype (" Text/html;charset=utf-8 "); Request.setcharacterencoding ("UTF-8");//Solve the common field garbled problem <input type= "text" name= "username"/>string username = request.getparameter ("username"); Response.getwriter (). write (username);//File Upload part = Request.getpart ("photo1");//<input type= "File" Name= " Photo1 ">//is images by the relative path and gets the absolute path Getservletcontext (). Getrealpath ("/images "): Returns C:/TOMCAT7/WEBAPPS/DAY22/IMAGES/1. Jpgpart.write (Getservletcontext (). Getrealpath ("/images") +file.separator+i+ ". jpg"), Response.getwriter (). Write (" File upload succeeded, <a href= ' "+request.getcontextpath () +"/01upload.jsp ' > Return </a> "); 4. Listener configuration: @WebListener5. Annotation configuration for Filters @WebFilter Note://Multiple filter order issues? Look at the dictionary of the filter name
LOG4J Log Manager
1. What is it? Log  for Java is  primarily used for logging information  (who logs on to my web site at what time) or database (SQL) 2. To save log information in one of the quickest ways 3. Where do you usually use log4j? Withdrawals (SQL (perform subtraction), Cash machine money)------> anomalies (log4j logging   (id=324323 withdrawals  , ATM no money)   ----> Reverse actions) Permission log, Exception Log 4. How do I use logs in development? 1.log4j-xxxx.jar Package 2. write config file  default (src/log4j.properties) 3. Use 5. LOG4J uses log4j.properties to select Log4j.properties#log4j.rootcategory=info, CONSOLE, in the MyEclipse directory search in the Apache directory LOGFILE You can remove the annotations here, enable the file log log4j.appender.logfile.file= Axis.log directory template log format for specified log log4j.appender.logfile.layout.conversionpattern=%d{iso8601}%-6r [%15.15t]%-5p%30.30c%x-% M\n
Today's Case 1. Customer information rewriting hibernate getting Started
Getting Started with Hibernate is a durable layer solution for lightweight applications 1. ORM Mapping Tool: JavaBean---> Database 2. By manipulating JavaBean, the equivalent of operating a database hibernate environment is built 1. Guide Pack copy Hibernate Hairstyle Pack \hibernate3.jar (1) Copy hibernate hairstyle pack \lib\required all jars (6 copies) Hibernate hairstyle pack \lib\ JPA jar (1) Copy log4j core jar package (1) Copy slf4j hairstyle pack \slf4j-log4j12-*.jar (1) and your database driver jar (MySQL 1) If you use the log, copy the Hibenate hairstyle package \ Project\etc\log4j.properties to the first introductory case in the build path 1. Create database tables and entities private Integer id;private String name;private Date birthday;2. In the package where the entity class resides, create a map file of the Java object and the database. The file name "entity class name-hbm.xml" can refer to the Hibernate release package under Search *.HBM.XML3. The framework connection database creates hibernate profile Hibenate.cfg.xml in the classpath and informs the path of the mapping file (refer to Hibernate hairstyle pack \project\etc\hibernate.properties) URL, User name, password, connection pool size, dialect, current thread object bindings, level two cache, whether the console shows whether SQL creates a table structure, and where the mapping file is 4. Tool Class 5. Persondaodemo/crud-----------------------------------------------------------------------DAO Design Pattern original Duplicate code 1. Persondao Interface 2. Customerdao interface Paging 3. Two implementation interfaces overwrite 1. Extract common DAO definition Generic T, Method crudvoid Add (t t); void update (T t); void Delete (Serializable PK); T FindOne (Serializable PK); 2. Customerdao inherited dao<customer> Unique method list<customer> findAll (); 3. Implementing Class Extraction Basedao&Lt T> implements the dao<t>3.1 tool class HibernateUtil3.2 Clazz dependency injection, using generic reflection, reflecting to the parent generic 3.3 crud Method: Increase open transaction, increase session S = Hibernateutil.getsession (); Transaction ts = s.begintransaction (); S.save (t); Ts.commit (); S.close (); Find session S = hibernateutil.getsession (); t bean = (t) s.load (clazz, PK); return bean;4. Implement class, inherit Basedao, implement customer interface 5. Modify the configuration file 6. Test
2. Reflection Annotation Case

Javaweb Foundation Strengthening (20)

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.