1、About Me jiniJWorld.TW(jakarta99)SoftLeader Tech.Corp.President since 2002 Focus on dev in Java enterprise applications for Insurances,Banking and Betting.Researching and Sharing Java Opensources My Google+(http:/gplus.to/jakarta99)Single nowAgenda Introduction Servlet 3.0 EJB 3.1 WebServices CDI Op
2、ensources Javassist/ASMAnnotationCourse1IntroductionWhats annotation Begin with“”An Interface Set Values Annotation Annotation(“someValue”)Annotation(var1=“someA”,var2=“someB”)Annotation(value=“Apple”,“Banana”,“Cherry”)RetentionPolicyAnnotation Runtime Default value Stereotype Find the classes conta
3、in Annotation Initialize them as what you want To generate the codes or xml and etc.Target(ElementType)AnnoTarget(TYPE)public class TheTarget AnnoTarget(FIELD)private String globalMsg;AnnoTarget(CONSTRUCTOR)public TheTarget()/This is a constructorAnnoTarget(METHOD)public void someMethod(AnnoTarget(P
4、ARAMETER)String myParam)/This is a methodAnnotationCourse 2 Servlet 3.0Servlet 2.5package javatwo.annotation;public class CatServlet extends HttpServlet public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException /do somethingweb.xmlCatServletjavatwo
5、.annotation.CatServletCatServlet/catServlet 3.0package javatwo.annotation;WebServlet(“/cat”)public class CatServlet extends HttpServlet public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException/do somethingWebServlet(name=catServlet,urlPatterns=/ca
6、t,initParams=WebInitParam(name=name,value=bobo)Servlet 3.0 No web.xml needed WebServlet-Define a Servlet WebFilter-Define a Filter WebListener-Define a Listener WebInitParam-Define init parameter MultipartConfig-Define upload properties Can use web.xml to override values that specified by the Annota
7、tions.FileUpload in Servlet 3.0WebServlet(“/upload”)MultipartConfig(location=“c:tmp”)public class FileUploadServlet extends HttpServlet public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException Collection parts=request.getParts();for(Part part:par
8、ts)part.write(“upload.txt”);/save to c:tmpupload.txtset Async in Servlet 3.0WebServlet(name=“AsyncServlet”,urlPatterns=“/async”,asyncSupported=“true”)public class AsyncServlet extends HttpServlet public void doGet(HttpServletRequest request,HttpServletResponse response)AsyncContext aCtx=request.star
9、tAsync(request,response);ServletContext sc=request.getServletContext();(Queue)sc.getAttribute(“slowQueue).add(aCtx);WebListenerpublic class SlowQueueListener implements ServletContextListener public void contextInitialized(ServletContextEvent sce)AnnotationCourse 3 EJB 3.1EJB 2.x1.public interface C
10、alculatorLocal extends EJBLocalObject.2.public interface CalculatorLocalHome extends EJBLocalHome.3.public class CalculatorBean implements SessionBean .4.ejb-jar.xmlcalculatorCalculatorLocalHomeCalculatorLocalCalculatorBeanStatelessContainerEJB 3.01.Local public interface CalculatorLocal extends EJB
11、LocalObject.2.public interface CalculatorHome extends EJBHome.3.Stateless public class CalculatorBean implements CalculatorLocal.4.ejb-jar.xmlEJB 3.1(LocalBean)1.Local public interface CalculatorLocal extends EJBLocalObject.2.public interface CalculatorHome extends EJBHome.3.Stateless public class C
12、alculatorBean implements CalculatorLocal.4.ejb-jar.xmlSingleton SessionBeanSingletonConcurrencyManagement(ConcurrencyManagementType.CONTAINER)public class SingletonBean private int clickCount=0;Lock(LockType.WRITE)public int getClickCount()return clickCount+;/Thread-Safe,TransactionalSchedule TimerS
13、ingletonpublic class TransFileBean Schedule(minute=“0”,hour=“4”,dayOfMonth=“Last”)public void trans()/do transferAnnotationCourse 4 WebServicesWebServices“Big”WebServices SOAP JAX-WS javax.jws.*RESTful WebServices REST JAX-RS javax.ws.rs.*SOAP WebServiceimport javax.jws.WebMethod;import javax.jws.We
14、bService;WebService(serviceName=“helloService”)public class Hello WebMethodpublic String sayHello(String name)return“Hello“+name;RESTful WebServiceimport javax.ws.rs.GET;import javax.ws.rs.Path;import javax.ws.rs.PathParam;import javax.ws.rs.Produces;import javax.ws.rs.core.MediaType;Path(/helloREST
15、/name)public class HelloREST GETProduces(MediaType.TEXT_PLAIN)public String getHello(PathParam(name)String name)return Hello*+name+*from JAX-RS;AnnotationCourse 5 CDIResource Injection JEE5WebServlet(“/product”)public ProductServlet extends HttpServlet Injectprivate ProductBean productBean;.Stateles
16、spublic class ProductBean.Ambiguous InjectQualifierpublic interface CarPolicyNo Qualifierpublic interface FirePolicyNo CarPolicyNoGeneratorpublic class CarPolicyNoGenerator implements PolicyNoGenerator.FirePolicyNoGeneratorpublic class FirePolicyNoGenerator implements PolicyNoGenerator.public class
17、FireService InjectFirePolicyNoGeneratorprivate PolicyNoGenerator policyNoGenerator;Producespublic class DatabaseProducer Produces PersistenceContext(unitName=“ds1”)FireDatabaseprivate EntityManager em;public class FireService Inject FireDatabaseprivate EntityManager em;AnnotationCourse 6 Opensources
18、jUnit 3.ximport junit.framework.Assert;import junit.framework.TestCase;public class CalculateServiceTest3 extends TestCase public void setUp()throws Exception public void testSum()int actual=new CalculateService().sum(3,5);Assert.assertEquals(8,actual);public void tearDown()throws Exception jUnit 4.
19、xpublic class CalculateServiceTest4 extends TestCase BeforeClasspublic static void setUpBeforeClass()throws Exception Beforepublic void beforeTest()throws Exception Testpublic void theSum()Assert.assertEquals(8,new CalculateService().sum(3,5);Afterpublic void afterTest()throws Exception AfterClasspu
20、blic static void tearDownAfterClass()throws Exception Spring 2.5Servicepublic class NewsService Autowiredprivate NewsDao newsDao;Spring 3.0Namedpublic class NewsService Injectprivate NewsDao newsDao;Spring 3.0Configurationpublic class AppConfig private Value(“#sysprop.dbURL”)String dbURL;private Val
21、ue(“#sysprop.username”)String username;private Value(“#sysprop.password”)String password;Beanpublic DataSource dataSource()return new DriverManagerDataSource(dbURL,username,password);MVC in Spring3.0ControllerRequestMapping(“/news”)public class NewsController RequestMaaping(value=“id”,method=Request
22、Method.GET)public ModelAndView getById(PathVariable(“id”)Long id)return AnnotationCourse 7 Javassist/ASM ReflectionClass myClass=MyClass.class;Method myMethods=myClass.getMethods();for(Method myMethod:myMethods)Annotation annotations=myMethod.getAnnotations();for(Annotation annotation:annotations)if
23、(annotation instanceof MyAnno)MyAnno myAnno=(MyAnno)annotation;/do somethingScan in ClassLoader project(based on javassist)URL urls=ClasspathUrlFinder.findClassPaths();AnnotationDB db=new AnnotationDB();db.scanArchives(urls);MapString,Set annoIndex=db.getAnnotationIndex();Set aClassNames=annoIndex.g
24、et(“javatwo.annotation.MyAnno”);for(String aClassName:aClassNames)./in Web,WarUrlFinder.findWebInfClassesPath(this.getServletContext();Get the Annotation valuesClassPool pool=ClassPool.getDefault();pool.insertClassPath(new ClassClassPath(this.getClass);CtClass cc=pool.get(aClassName);Object annos=cc
25、.getAnnotations();for(Object anno:annos)if(anno instanceof MyAnno)MyAnno myAnno=(MyAnno)anno;/do myAnno.var1(),myAnno.var2()Class R/W in ASMpublic class ScanMyDocVisitor implements ClassVisitor public AnnotationVisistor visitAnnotation(String desc,boolean visible)/in Controllerfor(String className:classNames)ScanMyDocVisitor sv=new ScanMyDocVisitor();ClassReader cr=new ClassReader(Thread.currentThread().getContextClassLoader().getResouceAsStream(className);cr.accept(sv,0);List annotationList =sv.getVisibleAnnotations();.