03.eGovFrame Runtime Environment Training Book Supplement

1,590 views

Published on

eGovFrame - Framework for e-government
Runtime Environment Training Book Supplement

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,590
On SlideShare
0
From Embeds
0
Number of Embeds
23
Actions
Shares
0
Downloads
32
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

03.eGovFrame Runtime Environment Training Book Supplement

  1. 1. eGovFrame Training Book Runtime Environment <Supplement> eGovFrame Center 2012
  2. 2. Table of contentsI OverviewII Foundation LayerIII Persistence LayerIV Presentation Layer Page l 2
  3. 3. Runtime Environment Composition OverviewRuntime Environment is the foundation of software applications and provides the basicfunctionality required to run software eGovFrame Runtime Environment Presentation Layer Business Logic Layer Persistence Layer Integration Layer Foundation Layer Service Group Page l 3
  4. 4. Runtime Environment Composition OverviewRuntime Environment provides libraries of common modules consisted of 5 service layers and 34services that work as a core foundation for running SW applications eGovFrame Runtime Environment Presentation Layer Business Logic Layer Persistence Layer Integration Layer MVC Internationalization Process Control DataSource Data Access Naming Service Ajax Support Security Exception Handling 2. 공통기반 레이어 ORM Transaction Integration Service UI Adaptor Web Service Foundation Layer AOP Cache Compress/Decompress Encryption/Decryption Excel File Handling File Upload/Download FTP Server Security ID Generation IoC Container Logging Mail Marshalling/Unmarshalling Object Pooling Property Resource Scheduling String Util XML Manipulation Service Group Service Page l 4
  5. 5. Features & Effects Overview Features • Adopt proven open source SW, optimized for e-government projects • Utilize Spring framework as a core foundation that is a pervasive lightweight framework • Apply DI, AOP, MVC, etc for SW architecture and implementation • Provide a common interface for integrating solutions as defining associated standard interface Effects • Improve development productivity • Improve e-government system reusability • Improve interoperability of e-government system • Standardize e-government application software • Promote Open Source Software • Enhance SMEs competitiveness Page l 5
  6. 6. Runtime Environment OSS OverviewRuntime Environment consists of a variety of open source software Open Source S/W Version Applied Service Reference URL Spring 3.0.5 IoC Container, AOP, Property, Resource http://www.springsource.org/ Spring Security 2.0.4 Server Security http://static.springsource.org/spring-security/site/ Log4j 1.3 Logging http://logging.apache.org/ EHCache 2.4.1 Cache http://ehcache.sourceforge.net/ Commons Compress 1.1 Compress/Decompress http://commons.apache.org/compress/ Commons VFS 1.0 File Handling http://commons.apache.org/vfs/ Commons FileUpload 1.2.2 File Upload/Download http://commons.apache.org/fileupload Commons Net 3.0.1 FTP http://commons.apache.org/net/ Common Email 1.2 Mail http://commons.apache.org/email/ Commons Pool 1.5.6 Object Pooling http://commons.apache.org/pool/ Jakarta Regexp 1.5 String Util http://jakarta.apache.org/regexp/ Apache Xerces 2 2.10.0 http://xerces.apache.org/xerces2-j/ XML Manipulation JDOM 1.1 http://www.jdom.org/ java simplified encryption (jasypt) 1.7 Encryption/Decryption http://www.jasypt.org/ Apache POI 3.2 http://poi.apache.org/ Excel jXLS 0.9.8 http://jxls.sourceforge.net/ Castor 1.2 http://www.castor.org/ Marshalling/Unmarshalling Apache XML Beans 2.4 http://xmlbeans.apache.org/ Quartz 1.8.5 Scheduling http://www.opensymphony.com/quartz/ Page l 6
  7. 7. RE*) Open Source - Spring Framework Overview Foundation Layer  Overview • Open source framework supports Java based enterprise applications • POJO based lightweight container (very loosely coupled) • Developed by Rod Johnson (Based on “Expert one-on-one J2EE Design and Development”)  Spring Mission and Goals • Spring should be fun and easier than J2EE in use. • Spring should not depend on the API. • Spring integrates with existing good solutions rather than competing.  EJB Problems • Heavy weight remote model • High complexity + Portability, Difficult to ensure performance and scalability·RE*) : Runtime Environment Page l 7
  8. 8. Spring Framework Composition Foundation LayerSpring Framework consists of DAO, ORM, AOP, JEE, Web, based on the core that governs theBean object life cycle Page l 8
  9. 9. IoC Container Foundation Layer Overview • Manage creating objects and object dependencies by external setting, rather than hard coding within source code • IoC is an abbreviation of the “Inversion of Control” or referred to “Reverse control” • Improve flexibility and scalability Key Features • Dependency Injection - Inject dependencies among objects in the external setting - Framework determines dependencies(objects) and relationships which will be used at run time • Bean Lifecycle Management - Manage the life cycle of object creation, destruction, etc Page l 9
  10. 10. IoC Container - Container Foundation Layer BeanFactory • org.springframework.beans.BeanFactory (interface) • Default interface provides Spring IoC Container’s basic functionality ApplicationContext • org.springframework.context.ApplicationContext (interface) • BeanFactory + (Spring AOP, message resource handling, event publication, etc) • ApplicationContext generally recommended over the BeanFactory, except for a few situations such as in low memory environment • Spring Framework offers many implementation of ApplicationContext interface Ex) ClassPathXmlApplicationContext, FileSystemXmlApplicationContext WebApplicationContext • org.springframework.web.context.WebApplicationContext • Provide more Bean scope ( request, session ) • Implementation class in Spring framework : XmlWebApplicationContext Page l 10
  11. 11. IoC Container - Container Foundation Layer Example ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"services.xml", "daos.xml"}); // an Application is also a BeanFactory (via inheritance) BeanFactory factory = context; Foo foo = (Foo)context.getBean(“foo”); Page l 11
  12. 12. IoC Container Foundation Layer XML configuration file • Bean configuration file has <beans/> as root, and provides related Namespace and Schema <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="..." class="..."> <!-- collaborators and configuration for this bean go here --> </bean> <bean id=“xmlEmpDAO” class=“egovframework.example.service.impl.XmlEmpDAO“ /> <bean id=“xmlEmpService” class=“egovframework.example.service.impl.XmlEmpServiceImpl” > <property name=“xmlDAO” ref=“xmlEmpDAO” /> </bean> <bean name=“otherExampleBean” class=“egovframework.example.OtherExampleBean“ /> </beans> Page l 12
  13. 13. IoC Container Foundation Layer Bean configuration (XML) • Bean definitions contain information about initialization dependency injection <bean id="" [Bean Name] Setting Bean id or name name="" class="" [Bean Class] Setting Class to be initialized factory-bean="" factory-method="" [Bean Instantiation] Setting instance mehtod lazy-init="" dependency-check="" [Dependency Injection] Setting dependency injection depends-on="" scope="" [Method Injection] Setting lookup method injection init-method="" destroy-method="" [Dependency Check] Setting dependency check info. autowire="" [Bean Scope] Setting bean scope autowire-candidate="" primary="" [Bean lifecycle callback] Setting lifecycle callback method abstract="" parent=""> <constructor-arg/> [Autowiring] Setting autowiring injection method <property/> <lookup-method/> [Bean inheritance] Setting inheritance info. <replaced-method/> <qualifier/> [Autowiriing setting] Setting additional info for autowiring </bean> Page l 13
  14. 14. IoC Container Foundation Layer Bean name • All bean definitions have only one id, and more than one name. id must be unique in container <bean id="exampleBean" class="example.ExampleBean"/> <bean name="anotherExample" class="examples.ExampleBeanTwo"/> • Bean definition can supply more than one name by using <alias/> element <alias name="fromName" alias="toName"/> Bean Class • All bean definitions need java class for instantiation <bean id="exampleBean" class="example.ExampleBean"/> <bean name="anotherExample" class="examples.ExampleBeanTwo"/> Page l 14
  15. 15. IoC Container Foundation Layer Bean instantiation • Generally bean instantiation is equal to java‟s „new‟ operator • In addition, bean instantiated by static factory method as below <bean id="exampleBean" class="examples.ExampleBean“ factory-method="createInstance"/> • Or by static method of other Factory class as below <!-- the factory bean, which contains a method called createInstance() --> <bean id="serviceLocator" class="com.foo.DefaultServiceLocator"/> <!-- the bean to be created via the factory bean --> <bean id="exampleBean" factory-bean="serviceLocator" factory-method="createInstance"/> • Traditional method ExampleBean exampleBean = new ExampleBean(); ExampleBean exampleBean = ExampleBean.createInstance(); ExampleBean exampleBean = DefaultServiceLocator.createInstance(); Page l 15
  16. 16. IoC Container Foundation Layer Dependency Injection • Constructor injection and Setter injection • Constructor Injection : Injected by constructor with arguments package x.y; public class Foo { public Foo(Bar bar, Baz baz) { // ... } } <beans> <bean name="foo" class="x.y.Foo"> <constructor-arg> <bean class="x.y.Bar"/> </constructor-arg> <constructor-arg> <bean class="x.y.Baz"/> </constructor-arg> </bean> </beans> Page l 16
  17. 17. IoC Container Foundation Layer Dependency Injection • type of index specified package examples; public class ExampleBean { // No. of years to the calculate the Ultimate Answer private int years; // The Answer to Life, the Universe, and Everything private String ultimateAnswer; public ExampleBean(int years, String ultimateAnswer) { this.years = years; this.ultimateAnswer = ultimateAnswer; } } <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg type="int" value="7500000"/> <constructor-arg type="java.lang.String" value="42"/> </bean> <bean id="exampleBean" class="examples.ExampleBean"> <constructor-arg index="0" value="7500000"/> <constructor-arg index="1" value="42"/> </bean> Page l 17
  18. 18. IoC Container Foundation Layer Dependency Injection • Setter injection with <property/> element <bean id="exampleBean" class="examples.ExampleBean"> <!-- setter injection using the nested <ref/> element --> <property name="beanOne"><ref bean="anotherExampleBean"/></property> <!-- setter injection using the neater ref attribute --> <property name="beanTwo" ref="yetAnotherBean"/> <property name="integerProperty" value="1"/> </bean> <bean id="anotherExampleBean" class="examples.AnotherBean"/> <bean id="yetAnotherBean" class="examples.YetAnotherBean"/> <bean id="exampleBean“ public class ExampleBean { class="examples.ExampleBean"> public void setBeanOne( <property name="beanOne"> AnotherBean beanOne) <ref bean="anotherExampleBean"/> { </property> this.beanOne = beanOne; </bean> } } Page l 18
  19. 19. IoC Container Foundation Layer Dependency Injection • Straight values (primitives, Strings, and so on) <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource“ destroy-method="close"> <!-- results in a setDriverClassName(String) call --> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/mydb</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>masterkaoli</value> </property> </bean> Page l 19
  20. 20. IoC Container Foundation Layer Dependency Injection • References to other beans <ref bean="someBean"/> • Inner beans <bean id="outer" class="..."> <!-- instead of using a reference to a target bean, simply define the target bean inline --> <property name="target"> <bean class="com.example.Person"> <!-- this is the inner bean --> <property name="name" value="Fiona Apple"/> <property name="age" value="25"/> </bean> </property> </bean> Page l 20
  21. 21. IoC Container Foundation Layer Dependency Injection • Collections : <list/>, <set/>, <map/>, and <props/> elements <bean id="moreComplexObject" class="example.ComplexObject"> <!-- results in a setAdminEmails(java.util.Properties) call --> <property name="adminEmails"> <props> <prop key="administrator">administrator@example.org</prop> <prop key="support">support@example.org</prop> <prop key="development">development@example.org</prop> </props> </property> <!-- results in a setSomeList(java.util.List) call --> <property name="someList"> <list> <value>a list element followed by a reference</value> <ref bean="myDataSource" /> </list> </property> ... Page l 21
  22. 22. IoC Container Foundation Layer Dependency Injection • Collections : <list/>, <set/>, <map/>, and <props/> elements ... <!-- results in a setSomeMap(java.util.Map) call --> <property name="someMap"> <map> <entry> <key><value>an entry</value></key> <value>just some string</value> </entry> <entry> <key><value>a ref</value></key> <ref bean="myDataSource" /> </entry> </map> </property> <!-- results in a setSomeSet(java.util.Set) call --> <property name="someSet"> <set> <value>just some string</value> <ref bean="myDataSource" /> </set> </property> </bean> Page l 22
  23. 23. IoC Container Foundation Layer Bean Scope • Spring framework supports five scopes as follows . Scope 설 명 singleton (default) Scopes a singe bean definition to single object instance per IoC container prototype Scopes a single bean definition to any number of object instances Scopes a single bean definition to the lifecycle of a single HTTP request request Only valid in the context of a web-aware Spring ApplicationContext Scopes a single bean definition to the lifecycle of an HTTP Session session Only valid in the context of a web-aware Spring ApplicationContext Scopes a single bean definition to the lifecycle of a global HTTP Session global session Only valid when used in a portlet context Page l 23
  24. 24. IoC Container Foundation Layer Bean Scope • Singleton scope : Only one shared instance is managed • example <bean id="accountService" class="com.foo.DefaultAccountService"/> <bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/> <bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/> Page l 24
  25. 25. IoC Container Foundation Layer Bean Scope • Prototype scope : Creation of a new bean instance every time a request for that specific bean is made • example <bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/> <bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/> Page l 25
  26. 26. IoC Container Foundation Layer Lifecycle callbacks • Initialization callbacks • InitializingBean interface allows to perform initialization work • InitializingBean specifies a sinlge method: void afterPropertiesSet() throws Exception; • POJO initialization method public class ExampleBean { public void init() { // do some initialization work } } <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/> Page l 26
  27. 27. IoC Container Foundation Layer Lifecycle callbacks • Destruction callbacks • DisposableBean interface allows to perform disposable work • DisposableBean specifies a sinlge method: void destroy() throws Exception; • POJO initialization method public class ExampleBean { public void cleanup() { // do some destruction work (like releasing pooled connections) } } <bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/> Page l 27
  28. 28. IoC Container Foundation Layer Annotaion • Available to use Java annotation instead of XMlL configuration files (Java 5 or higher) • As using annotation, simplify configuration files, and mapping between view pages and objects or methods can be clearly defined. Page l 28
  29. 29. IoC Container Foundation Layer Annotation Type • Using Java Annotation, Spring Bean definitions can be set, then need to add namespace and element <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> </beans> • Auto scan configuration, based on Annotation <?xml version="1.0" encoding="UTF-8"?> <beans ··> · <context:component-scan base-package=“egovframework“/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> </beans> Page l 29
  30. 30. IoC Container Foundation Layer Annotation type • @Required : Applied to setter method, mark a property as being required-to-be-set (i.e. an annotated (setter) method of a class must be configured to be dependency injected with a value) methods public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can inject a MovieFinder @Required public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected MovieFinder is omitted... } • @Autowired : auto wire a bean on the setter method, constructor or a field. It can autowire property in a particular bean • @Resource : marks a resource that is needed by the application. It finds the target bean with name @Service public UserServiceImpl implements UserService { @Resource (name="userDAO") private UserDAO userDAO; } • @PostConstruct, @PreDestroy : Use to assign Instantiation callback, Destruction callback methods Page l 30
  31. 31. IoC Container Foundation Layer Annotation type • @Required : Applied to setter method, mark a property as being required-to-be-set (i.e. an annotated (setter) method of a class must be configured to be dependency injected with a value) ethods public class SimpleMovieLister { // the SimpleMovieLister has a dependency on the MovieFinder private MovieFinder movieFinder; // a setter method so that the Spring container can inject a MovieFinder @Required public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // business logic that actually uses the injected MovieFinder is omitted... } • @Autowired : auto wire a bean on the setter method, constructor or a field. It can autowire property in a particular bean • @Resource : marks a resource that is needed by the application. It finds the target bean with name @Service public UserServiceImpl implements UserService { @Resource (name="userDAO") private UserDAO userDAO; } • @PostConstruct, @PreDestroy : Use to assign Instantiation callback, Destruction callback methods Page l 31
  32. 32. IoC Container Foundation Layer Auto-detecting components • Set bean name with @Component, @Repository, @Service, @Controller annotation‟s name value @Service("myMovieLister") public class SimpleMovieLister { // ... } • If name isn‟t set, camel case of class name is used @Repository public class MovieFinderImpl implements MovieFinder { // ... } Page l 32
  33. 33. IoC Container Foundation Layer ApplicationContext for web application • Spring provides classes for easy WebApplicationContext setting • Add following settings in web.xml for ApplicationContext setting with the Listener (Servlet 2.4 or later) <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> Page l 33
  34. 34. AOP Foundation Layer Overview • Aspect-oriented programming (AOP) is a programming paradigm which aims to increase modularity by allowing the separation of cross-cutting concerns • AOP is programming techniques to support the processing of modularizing Logging, security, transactions, and common functions without changing existing business logic Configuration File AOP Applied OOP OOP + AOP Page l 34
  35. 35. AOP Foundation Layer Main Concept • Advice, JoinPoint, Pointcut, Weaving, Aspect Pointcut JoinPoint Weaving Advice Benefits • Remove duplicate code • Improve readability of the business logic • Improve productivity • Improve reusability • Increase ease of change Page l 35
  36. 36. AOP Foundation Layer Relations for AOP components A set of Join point Join point is the time (condition: select*) which a method is called in Spring Source Code EmployeeService Aspect 소스코드 Processing what you want to apply insertEmployee() updateEmployee() Pointcut selectEmployeeList() Advice selectEmployee() deleteEmployttList() Joinpoint Page l 36
  37. 37. AOP Foundation Layer Aspect definitionAdvice <bean id="adviceUsingXML" class="egovframework.rte.fdl.aop.sample.AdviceUsingXML" /> Pointcut <aop:config> <aop:pointcut id="targetMethod" expression="execution(* egovframework.rte.fdl.aop.sample.*Sample.*(..))" /> <aop:aspect ref="adviceUsingXML"> <aop:before pointcut-ref="targetMethod" method="beforeTargetMethod" /> <aop:after-returning pointcut-ref="targetMethod"JoinPoint method="afterReturningTargetMethod" returning="retVal" /> <aop:after-throwing pointcut-ref="targetMethod" method="afterThrowingTargetMethod" throwing="exception" /> <aop:after pointcut-ref="targetMethod" method="afterTargetMethod" /> <aop:around pointcut-ref="targetMethod" method="aroundTargetMethod" /> </aop:aspect> </aop:config> Aspect <bean id="adviceSample" class="egovframework.rte.fdl.aop.sample.AdviceSample" /> Page l 37
  38. 38. AOP Foundation Layer Advice definition - before public class AdviceUsingXML { public void beforeTargetMethod(JoinPoint thisJoinPoint) { Class clazz = thisJoinPoint.getTarget().getClass(); String className = thisJoinPoint.getTarget().getClass().getSimpleName(); String methodName = thisJoinPoint.getSignature().getName(); // target class name and method name are logged Log logger = LogFactory.getLog(clazz); logger.debug(className + "." + methodName + " executed."); } } Advice definition – after returning public class AdviceUsingXML { public void afterReturningTargetMethod(JoinPoint thisJoinPoint, Object retVal) { System.out.println("AspectUsingAnnotation.afterReturningTargetMethod executed.” + “ return value is [“ + retVal + "]"); } … } Page l 38
  39. 39. AOP Foundation Layer Advice definition – after throwing public class AdviceUsingXML { ... public void afterThrowingTargetMethod(JoinPoint thisJoinPoint, Exception exception) throws Exception{ System.out.println("AdviceUsingXML.afterThrowingTargetMethod executed."); System.err.println(“Error occurs.", exception); throw new BizException(“Error occurs", exception); } ... } Advice definition – after (finally) public class AdviceUsingXML { public void afterTargetMethod(JoinPoint thisJoinPoint) { System.out.println("AspectUsingAnnotation.afterTargetMethod executed."); } … } Page l 39
  40. 40. AOP Foundation Layer Advice definition - around public class AdviceUsingXML { public Object aroundTargetMethod(ProceedingJoinPoint thisJoinPoint) throws Throwable { System.out.println("AspectUsingAnnotation.aroundTargetMethod start."); long time1 = System.currentTimeMillis(); Object retVal = thisJoinPoint.proceed(); System.out.println("ProceedingJoinPoint executed. return value is [“ + retVal + "]"); retVal = retVal + "(modified)"; System.out.println("return value modified to [" + retVal + "]"); long time2 = System.currentTimeMillis(); System.out.println("AspectUsingAnnotation.aroundTargetMethod end. Time(" + (time2 - time1) + ")"); return retVal; } … } Page l 40
  41. 41. Runtime Environment Services ServicesRuntime Environment provides libraries of common modules consisted of 5 service layers and 34services that work as a core foundation for running SW applications eGovFrame Runtime Environment Presentation Layer Business Logic Layer Persistence Layer Integration Layer MVC Internationalization Process Control DataSource Data Access Naming Service Ajax Support Security Exception Handling 2. 공통기반 레이어 ORM Transaction Integration Service UI Adaptor Web Service Foundation Layer AOP Cache Compress/Decompress Encryption/Decryption Excel File Handling File Upload/Download FTP Server Security ID Generation IoC Container Logging Mail Marshalling/Unmarshalling Object Pooling Property Resource Scheduling String Util XML Manipulation Service Group Service Page l 41
  42. 42. Server Security Foundation Layer Overview • Spring Security provides comprehensive security services for J2EE-based enterprise applications. • Security comprises two major operations : authentication, authorization Features • Authentication : the process of establishing a principal is who they claim to be • URL-based Authorization : the process of deciding whether a principal is allowed to perform an access URL in application • Method invocation-based Authorization : the process of deciding whether a principal allowed to perform a method invocation • Session Management Page l 42
  43. 43. Server Security Foundation Layer Architecture • General authentication and authorization process Request resources No Secured Offer resources Resources? Yes No Authenticated? Login User Yes No Error page Login? Yes (HTTP 403) Yes Error page Authorized? No (HTTP 503) Page l 43
  44. 44. Server Security Foundation Layer Architecture • DB Schema Page l 44
  45. 45. Server Security Foundation Layer Architecture • Secured_resources RESOURCE_ID RESOURCE_PATTERN web-000001 A/sample.do.*Z web-000002 A/.*.do.*Z web-000003 A/.*Z web-000004 A/reloadAuthMapping.do.*Z mtd-000001 egovframework.rte.sample.service.EgovSampleService.updateSample mtd-000002 egovframework.rte.sample.service.EgovSampleService.deleteSample mtd-000003 execution(* egovframework.rte.sample..service.*Service.insert*(..)) Page l 45
  46. 46. Server Security Foundation Layer Architecture • Roles AUTHORITY DESCRIPTION IS_AUTHENTICATED_ANONYMOUSLY Anonymous user IS_AUTHENTICATED_REMEMBERED REMEMBERED user IS_AUTHENTICATED_FULLY Authenticated user ROLE_RESTRICTED Restricted user ROLE_USER General user ROLE_ADMIN administrator ROLE_A A Role ROLE_B B Role Page l 46
  47. 47. Server Security Foundation Layer Architecture • Roles_hierarchy CHILD_ROLE PARENT_ROLE ROLE_ADMIN ROLE_USER ROLE_USER ROLE_RESTRICTED ROLE_RESTRICTED IS_AUTHENTICATED_FULLY IS_AUTHENTICATED_FULLY IS_AUTHENTICATED_REMEMBERED IS_AUTHENTICATED_REMEMBERED IS_AUTHENTICATED_ANONYMOUSLY ROLE_ADMIN ROLE_A ROLE_ADMIN ROLE_B ROLE_A ROLE_RESTRICTED ROLE_B ROLE_RESTRICTED Page l 47
  48. 48. Server Security Foundation Layer Authentication • <http> <http auto-config=true> <intercept-url pattern="/**" access="ROLE_USER"/> </http> • auto-config <http> <intercept-url pattern="/**" access="ROLE_USER" /> <form-login /> <anonymous /> <http-basic /> <logout /> <remember-me /> </http> • Authentication Provider <authentication-provider> <user-service> <user name="jimi" password="jimispassword" authorities="ROLE_USER, ROLE_ADMIN" /> <user name="bob" password="bobspassword" authorities="ROLE_USER" /> </user-service> </authentication-provider> Page l 48
  49. 49. Server Security Foundation Layer Authentication • <http> <http access-denied-page="/system/accessDenied.do" path-type="regex"> <form-login login-processing-url="/j_spring_security_check" authentication-failure-url="/cvpl/EgovCvplLogin.do?login_error=1" default-target-url="/index.jsp?flag=L" login-page="/cvpl/EgovCvplLogin.do" /> <logout logout-success-url="/cvpl/EgovCvplLogin.do"/> </http> • Authentication Provider <authentication-provider user-service-ref="jdbcUserService"> <password-encoder hash="md5" base64="true"/> </authentication-provider> Page l 49
  50. 50. Server Security Foundation Layer Authentication • jdbcUserService <jdbc-user-service id=“jdbcUserService“ data-source-ref=“dataSource“ users-by-username-query=“SELECT USER_ID,PASSWORD,ENABLED,BIRTH_DAY FROM USERS WHERE USER_ID = ?“ authorities-by-username-query=“SELECT USER_ID,AUTHORITY FROM AUTHORITIES WHERE USER_ID = ?“/> • JSP Sample <form action="<s:url value=/j_spring_security_check/>" method="POST"> <table> <tr><td>User:</td><td> <input type=text name=j_username> </td></tr> <tr><td>Password:</td><td> <input type=password name=j_password> </td></tr> <tr><td colspan=2 align="center"> <input name="submit" type="submit" value=“Login"> </td></tr> </table> </form> Page l 50
  51. 51. Server Security Foundation Layer Authentication • JdbcUserDetailsManager extension <b:bean id=“jdbcUserService“ class=“egovframework.rte.fdl.security.userdetails.jdbc.EgovJdbcUserDetailsManager“ > <b:property name=“usersByUsernameQuery“ value=“SELECT USER_ID,PASSWORD,ENABLED,USER_NAME,BIRTH_DAY,SSN FROM USERS WHERE USER_ID = ? “/> <b:property name="authoritiesByUsernameQuery“ value=“SELECT USER_ID,AUTHORITY FROM AUTHORITIES WHERE USER_ID = ? “/> <b:property name=“roleHierarchy" ref=“roleHierarchy“/> <b:property name=“dataSource“ ref=“dataSource“/> <b:property name=“mapClass“ value=“egovframework.rte.fdl.security.userdetails.EgovUserDetailsMapping“/> </b:bean> Page l 51
  52. 52. Server Security Foundation Layer Authentication • Map class public class EgovUserDetailsMapping extends EgovUsersByUsernameMapping { public EgovUserDetailsMapping(DataSource ds, String usersByUsernameQuery) { super(ds, usersByUsernameQuery); } @Override protected Object mapRow(ResultSet rs, int rownum) throws SQLException { String userid = rs.getString("user_id"); String password = rs.getString("password"); boolean enabled = rs.getBoolean("enabled"); String username = rs.getString("user_name"); String birthDay = rs.getString("birth_day"); String ssn = rs.getString("ssn"); EgovUserDetailsVO userVO = new EgovUserDetailsVO(); userVO.setUserId(userid); userVO.setPassWord(password); userVO.setUserName(username); userVO.setBirthDay(birthDay); userVO.setSsn(ssn); return new EgovUserDetails(userid, password, enabled, userVO); } } Page l 52
  53. 53. Server Security Foundation Layer Authentication • Session management import egovframework.rte.fdl.security.userdetails.util.EgovUserDetailsHelper; . . . EgovUserDetailsVO user = (EgovUserDetailsVO)EgovUserDetailsHelper.getAuthenticatedUser(); assertEquals("jimi", user.getUserId()); assertEquals("jimi test", user.getUserName()); assertEquals("19800604", user.getBirthDay()); assertEquals("1234567890123", user.getSsn()); • Confirm authentication assertNull(EgovUserDetailsHelper.getAuthenticatedUser()); Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated(); assertFalse(isAuthenticated.booleanValue()); Page l 53
  54. 54. Server Security Foundation Layer Authorization • Role List<String> authorities = EgovUserDetailsHelper.getAuthorities(); // example // 1. check authorities (TRUE/FALSE) assertTrue(authorities.contains("ROLE_USER")); assertTrue(authorities.contains("ROLE_RESTRICTED")); assertTrue(authorities.contains("IS_AUTHENTICATED_ANONYMOUSLY")); assertTrue(authorities.contains("IS_AUTHENTICATED_FULLY")); assertTrue(authorities.contains("IS_AUTHENTICATED_REMEMBERED")); // 2. in case of several authorities for (Iterator<String> it = authorities.iterator(); it.hasNext();) { String auth = it.next(); } // 3. in case of just one authorities String auth = (String) authorities.toArray()[0]; Page l 54
  55. 55. Server Security Foundation Layer Tag Library • Declaration <%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %> • Example <sec:authorize ifNotGranted="ROLE_USER"> <a href=“<c:url value="/login.do"/>">Login</a> </sec:authorize> <sec:authorize ifAnyGranted="ROLE_USER, ROLE_ADMIN"> <b><sec:authentication property="principal.username"/></b> logged in<br> <a href="<c:url value="/j_spring_security_logout"/>">Logout</a> </sec:authorize> • Authentication tag • Property=“principal.usrname” • Authorize tag • ifAllGranted, ifAnyGranted, ifNotGranted, and so on Page l 55
  56. 56. ID Generation Foundation Layer Overview • Service for making ID(identifier) in various format and algorithms Features • UUID (Universal Unique Identifier) generation • Sequence ID generation • DB Sequence ID • Table Sequence ID Page l 56
  57. 57. ID Generation Foundation Layer UUID • A standard for identifier adopted by OSF(Open Software Foundation) • It consists of 16-byte number and expressed in 8-4-4-4-12 format • Ex: 550e8400-e29b-41d4-a716-446655440000 Version • Version 1 (MAC Address) : Computer‟s MAC address • Version 2 (DCE Security) : POSIX UID • Version 3 (MD5 Hash) • Version 4 (Random) • Version 5 (SHA-1) Page l 57
  58. 58. ID Generation Foundation Layer Mac Address Base Service <bean name="UUIdGenerationService“ class="egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService"> <property name="address"> <value>00:00:F0:79:19:5B</value> </property> </bean> IP Address Base Service <bean name=" UUIdGenerationService" class="egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService"> <property name="address"> <value>100.128.120.107</value> </property> </bean> No Address Base Service <bean name=" UUIdGenerationService" class="egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService“/> Page l 58
  59. 59. ID Generation Foundation Layer Java code @Resource(name="UUIdGenerationService") private EgovIdGnrService uUidGenerationService; @Test public void testUUIdGeneration() throws Exception { assertNotNull(uUidGenerationService.getNextStringId()); assertNotNull(uUidGenerationService.getNextBigDecimalId()); } Page l 59
  60. 60. ID Generation Foundation Layer DB Sequence Id Generation • DB Schema CREATE SEQUENCE idstest MINVALUE 0; • Setting <bean name="primaryTypeSequenceIds“ class="egovframework.rte.fdl.idgnr.impl.EgovSequenceIdGnrService“ destroy-method="destroy"> <property name="dataSource" ref="dataSource"/> <property name="query" value="SELECT idstest.NEXTVAL FROM DUAL"/> </bean> Page l 60
  61. 61. ID Generation Foundation Layer DB Table Id Generation • DB Schema CREATE TABLE ids ( table_name varchar(16) NOT NULL, next_id DECIMAL(30) NOT NULL, PRIMARY KEY (table_name)); INSERT INTO ids VALUES(id,0); • Setting <bean name="basicService" class="egovframework.rte.fdl.idgnr.impl.EgovTableIdGnrService" destroy-method="destroy"> <property name="dataSource" ref="dataSource"/> <property name="blockSize" value="10"/> <property name="table" value="ids"/> <property name="tableName" value="id"/> </bean> • blockSize : the number of cached item in memory • table : table name to be used to store • tableName : table‟s record key value to be used Page l 61
  62. 62. ID Generation Foundation Layer Strategy Base Service • Setting <bean name="IdWithGenerationStrategy“ class="egovframework.rte.fdl.idgnr.impl.EgovTableIdGnrService" destroy-method="destroy"> <property name="dataSource" ref="dataSource"/> <property name="strategy" ref="strategy"/> <property name="blockSize" value="1"/> <property name="table" value="idttest"/> <property name="tableName" value="test"/> </bean> <bean name="strategy“ class="egovframework.rte.fdl.idgnr.impl.strategy.EgovIdGnrStrategyImpl"> <property name="prefix" value="TEST-"/> <property name="cipers" value="5"/> <property name="fillChar" value="0"/> </bean> • prefix : letters that is added into the beginning • cipers : length of id excepted prefix • fillChar : character to be filled in id Page l 62
  63. 63. ID Generation Foundation Layer Strategy Base Service • Java code @Resource(name="IdsWithGenerationStrategy") private EgovIdGnrService idsTestWithGenerationStrategy; @Test public void testIdGenStrategy() throws Exception { initializeNextLongId("test", 1); // prefix : TEST-, cipers : 5, fillChar :*) for (int i = 0; i < 5; i++) { assertEquals("TEST-0000" + (i + 1), idsTestWithGenerationStrategy.getNextStringId()); } } Page l 63
  64. 64. Property Foundation Layer Bean configuration Service • Setting <bean name="propertyService“ class="egovframework.rte.fdl.property.impl.EgovPropertyServiceImpl“ destroy-method="destroy"> <property name="properties"> <map> <entry key="AAAA" value="1234"/> </map> </property> </bean> • Java code @Resource(name="propertyService") protected EgovPropertyService propertyService ; @Test public void testPropertiesService() throws Exception { assertEquals("1234",propertyService.getString("AAAA")); } Page l 64
  65. 65. Property Foundation Layer External Property File Service • Setting <bean name="propertyService" class="egovframework.rte.fdl.property.impl.EgovPropertyServiceImpl“ destroy-method="destroy“> <property name="extFileName"> <set> <map> <entry key="encoding" value="UTF-8"/> <entry key="filename" value="file:/home/properties/**/*.properties"/> </map> <value>classpath*:properties/resource.properties</value> </set> </property> </bean> • Properties file AAAA=1234 Page l 65
  66. 66. Data Source Persistence Layer Overview • Service for providing database connection • Remove dependencies about business logic and database connection Key Features • Service to connect database - Create database connection, using JDBC driver <bean id="dataSource” class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${dburl}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> • driverClassName : JDBC driver class name • url : Database access JDBC URL • username : Database access username • password : Database access password Page l 66
  67. 67. Data Source Persistence Layer Key Features • DBCP DataSource - Database connection module, using JDBC driver. This is database connection pool, called Commons DBCP in Jakarta projects. <bean id="dataSource” class="org.apache.commons.dbcp.BasicDataSource” destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${dburl}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <property name="defaultAutoCommit" value="false" /> <property name="poolPreparedStatements" value="true" /> </bean> • driverClassName : jdbc driver class name • url : DataBase url • username : DataBase access user name • password : DataBase access password • defaultAutoCommit : configure auto-commit function about connection • poolPreparedStatements : PreparedStatement configuration (user or not) Page l 67
  68. 68. Data Source Persistence Layer Key Features • JNDI DataSource - JNDI DataSource get DataSource using JNDI Lookup from WAS <jee:jndi-lookup id="dataSource" jndi-name="${jndiName}" resource-ref="true"> <jee:environment> java.naming.factory.initial=${jeus.java.naming.factory.initial} JEUS java.naming.provider.url=${jeus.java.naming.provider.url} </jee:environment> </jee:jndi-lookup> WEBLOGIC <util:properties id="jndiProperties" location="classpath:/META-INF/spring/jndi.properties" /> <jee:jndi-lookup id="dataSource" jndi-name="${jndiName}" resource-ref="true" environment- ref="jndiProperties" /> Page l 68
  69. 69. Data Source Persistence Layer Java code @Resource(name = "dataSource") DataSource dataSource; public void testJdbcDataSource() throws Exception { Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = dataSource.getConnection(); stmt = con.createStatement(); rs = stmt.executeQuery("select x as x from dual"); ……. } Page l 69
  70. 70. Data Access Persistence Layer Overview • Provide a service to respond in a consistent manner for a variety of database solutions and database access technologies • Improve business efficiency by providing abstract data access method • SQL statement can be mapped easily to JavaBeans(or Map), using iBATIS which apply simple XML technology rather than java code to access a relational database Key features • Provide an abstraction access method for JDBC (Do not directly call JDBC related API) • Support removing SQL statement from Java source code (Ensure ease of management / maintenance / tuning) • Support various binding/mapping for input/output objects of Query execution • Support dynamic query change through dynamic SQL • Support a variety of DB processing (Batch SQL, Paging, Callable statement, BLOB/CLOB, etc) Page l 70
  71. 71. Data Access Persistence Layer Features • iBATIS is a persistence framework that emphasize on simplicity and minimize the repetitive and complex DB query using SQL Map - Support Stored Procedure with XML or mapping between SQL statements and Java objects, as emphasis on simplicity, one of iBATIS main ideas - Persistence framework, developed by Clinton Begin(Apache Software Foundation) in 2001 Elements iBATIS Hibernate comparison Hibernate takes more time due to Round Trip Delay Time Short Long features such as automatic generation of query Flexibility Good Poor Learning Curve Short Long iBATIS is much more similar to JDBC SQL knowledge Should be higher Do not required much Page l 71
  72. 72. Data Access Persistence Layer Composition Page l 72
  73. 73. Data Access Persistence Layer SQL Map Config <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <sqlMap resource="egovframework/sqlmap/sample/EgovSample_SQL.xml"/> <sqlMap ../> .. </sqlMapConfig> Page l 73
  74. 74. Data Access Persistence Layer SQL Map <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map- 2.dtd"> <sqlMap namespace="Dept"> <typeAlias alias="deptVO" type="egovframework.DeptVO" /> <resultMap id="deptResult" class="deptVO"> <result property="deptNo" column="DEPT_NO" /> <result property="deptName" column="DEPT_NAME" /> <result property="loc" column="LOC" /> </resultMap> <insert id="insertDept" parameterClass="deptVO"> insert into DEPT (DEPT_NO, DEPT_NAME, LOC) values (#deptNo#, #deptName#, #loc#) </insert> <select id="selectDept" parameterClass="deptVO" resultMap="deptResult"> <![CDATA[ select DEPT_NO, DEPT_NAME, LOC from DEPT where DEPT_NO = #deptNo# ]]> </select> </sqlMap> Page l 74
  75. 75. Data Access Persistence Layer Dynamic SQL .. <typeAlias alias="jobHistVO" type="egovframework.rte.psl.dataaccess.vo.JobHistVO" /> <select id="selectJobHistListUsingDynamicElement" parameterClass="jobHistVO" resultClass="jobHistVO"> <![CDATA[ select EMP_NO as empNo, START_DATE as startDate, END_DATE as endDate, JOB as job, SAL as sal, COMM as comm, DEPT_NO as deptNo from JOBHIST ]]> <dynamic prepend="where"> <isNotNull property="empNo" prepend="and"> EMP_NO = #empNo# </isNotNull> </dynamic> order by EMP_NO, START_DATE </select> Page l 75
  76. 76. Data Access Persistence Layer Dynamic SQL .. <typeAlias alias="egovMap" type="egovframework.rte.psl.dataaccess.util.EgovMap" /> <select id="selectDynamicUnary" parameterClass="map" remapResults="true" resultClass="egovMap"> select <dynamic> <isEmpty property="testEmptyString"> empty String as IS_EMPTY_STRING </isEmpty> <isNotEmpty property="testEmptyString"> not empty String as IS_EMPTY_STRING </isNotEmpty> .. <isPropertyAvailable prepend=", " property="testProperty"> testProperty Available asTEST_PROPERTY_AVAILABLE </isPropertyAvailable> <isNotPropertyAvailable prepend=", " property="testProperty"> testProperty Not Available as TEST_PROPERTY_AVAILABLE </isNotPropertyAvailable> </dynamic> from dual </select> Page l 76
  77. 77. Data Access Persistence Layer Dynamic SQL • Unary operation element description isEmpty If Collection, String(or String.valueOf()) is null or empty(”” or size() < 1) , then true isNotEmpty If Collection, String(or String.valueOf()) is not null and not empty(”” or size() < 1) , then true isNull If property value is null, then true isNotNull If property value is not null, then true isPropertyAvailable If parameter exists, then true isNotPropertyAvailable If parameter isn’t exist, then true • Binary operation 태그 설명 isEqual If property value is equal to ‘compareValue’ or ‘compareProperty’ value, then true isNotEqual If property value is not equal to ‘compareValue’ or ‘compareProperty’ value, then true isGreaterEqual If property value is greater and equals to ‘compareValue’ or ‘compareProperty’ value, then true isGreaterThan If property value is greater than ‘compareValue’ or ‘compareProperty’ value, then true isLessEqual If property value is less and equals to ‘compareValue’ or ‘compareProperty’ value, then true isLessThan If property value is less than ‘compareValue’ or ‘compareProperty’ value, then true Page l 77
  78. 78. Data Access Persistence Layer Dynamic SQL <typeAlias alias="jobHistVO" type="egovframework.rte.psl.dataaccess.vo.JobHistVO" /> <typeAlias alias="empIncludesEmpListVO" type="egovframework.rte.psl.dataaccess.vo.EmpIncludesEmpListVO" /> <select id="selectJobHistListUsingDynamicIterate" parameterClass="empIncludesEmpListVO" resultClass="jobHistVO"> <![CDATA[ select EMP_NO as empNo, START_DATE as startDate, END_DATE as endDate, JOB as job, SAL as sal, COMM as comm, DEPT_NO as deptNo from JOBHIST ]]> <dynamic prepend="where"> <iterate property="empList" open="EMP_NO in (" conjunction=", " close=")"> #empList[].empNo# </iterate> </dynamic> order by EMP_NO, START_DATE </select> Page l 78
  79. 79. MVC Presentation Layer Relationship and flow between Spring MVC components Page l 79
  80. 80. MVC Presentation Layer Relationship and flow between Spring MVC components Page l 80
  81. 81. MVC Presentation Layer Spring MVC core components • DispatcherServlet - The front controller of Spring MVC Framework. Supervise life cycle of web request and respond. • HandlerMapping - Decide which controller will process the target URL when web request comes in. • Controller - Perform the business logic and the result data is reflected in the ModelAndView. • ModelAndView - Consist of model data object which reflects controller‟s result and target page information (or view object). • ViewResolver - Provide a mapping between view names and actual views. • View - Display the model object which is result data. Page l 81
  82. 82. MVC Presentation Layer DispatcherServlet • It is recommended dividing ApplicationContext into two layers • ApplicationContext : created by ContextLoaderListener and contains persistence and service layer beans • WebApplicationContext : created by DispatcherServlet and contains presentation layer beans Page l 82
  83. 83. MVC Presentation Layer DispatcherServlet – web.xml <!-- ApplicationContext --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/config/service/easycompany-service.xml <!-- Service beans--> /WEB-INF/config/service/easycompany-dao.xml <!-- data access beans--> </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- WebApplicationContext --> <servlet> <servlet-name>servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/config/easycompany-servlet.xml <!-- web layer beans --> </param-value> </init-param> </servlet> <!-- WebApplicationContext --> <servlet> <servlet-name>webservice</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/config/easycompany-webservice.xml </param-value> </init-param> </servlet> Page l 83
  84. 84. MVC Presentation Layer HandlerMapping • DefaultAnnotationHandlerMapping • It maps request‟s URL to Controller‟s method using @RequestMapping • Because it‟s a default HandlerMapping, we don‟t need to declare it • But with other HandlerMapping, we need to declare it <bean id="selectAnnotaionMapper“ class="egovframework.rte.ptl.mvc.handler.SimpleUrlAnnotationHandlerMapping” p:order="1"> <property name="interceptors"> <list> <ref local="authenticInterceptor"/> </list> </property> <property name="urls"> <list> <value>/admin/*.do</value> <value>/user/userInfo.do</value> <value>/development/**/code*.do</value> </list> </property> </bean> <bean id="annotationMapper" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping“ p:order="2"/> Page l 84
  85. 85. MVC Presentation Layer Controller import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class HelloController { @RequestMapping(value="/hello.do") public String hello(){ ... } @RequestMapping(value="/helloForm.do", method = RequestMethod.GET) public String helloGet(){ ... } @RequestMapping(value="/helloForm.do", method = RequestMethod.POST) public String helloPost(){ ... } } Page l 85
  86. 86. MVC Presentation Layer Controller @Controller Annotation for setting class as Controller @RequestMapping Annotation for mapping method from requested URL @RequestParam Annotation for mapping request parameter to method argument @ModelAttribute Annotation for binding method argument or return value to model object @SessionAttributes Annotation for saving session object Page l 86
  87. 87. MVC Presentation Layer Controller • Mapping request parameters to method arguments using @RequestParam @Controller public class HelloController { @RequestMapping("/hello.do") public String hello(@RequestParam("name") String name, @RequestParam(value="pageNo", required=false) String pageNo){ ... } } • Using Common/form object @Controller public class HelloController { @RequestMapping("/hello.do") public String hello(HelloData data, @ModelAttribute(“searchCondigion") SearchCondigion condition) { ... } } Page l 87
  88. 88. MVC Presentation Layer Controller’s method signature • Method argument • Servlet API - ServletRequest, HttpServletRequest, ServletResponse, HttpServletResponse, HttpSession • org.springframework.web.context.request.WebRequest, org.springframework.web.context.request.NativeWebRequest • java.util.Locale • java.io.InputStream / java.io.Reader • java.io.OutputStream / java.io.Writer • @RequestParam – for binding request parameter to method argument • java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap – Model data to be sent to View • Command/form Object – for binding request paramters to ValueObject • org.springframework.validation.Errors / org.springframework.validation.BindingResult – Object having validation result • org.springframework.web.bind.support.SessionStatus – for removal session Page l 88
  89. 89. MVC Presentation Layer Controller’s method signature • Return value type • ModelAndView – Object with model and view • Map, Model, or ModelMap – Model data to be sent to view View name is automatically decided by RequestToViewNameTranslator (url –> view name) • String – View name Model data to be declared in method argument • void – in case that we direct control ServletResponse or HttpServletResponses Page l 89
  90. 90. MVC Presentation Layer ViewResolver <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" p:order="1" p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/> <bean id="tilesViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" /> <property name="order" value="0" /> </bean> Page l 90
  91. 91. MVC Presentation Layer View (JSP) ... <%@ page contentType="text/html; charset=utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> ... <form:form commandName="department"> <table> <tr> <th>Department No.</th><td><c:out value="${department.deptid}"/></td> </tr> <tr> <th>Department Name</th><td><form:input path="deptname" size="20"/></td> </tr> <tr> <th>Upper Dept.</th> <td> <form:select path="superdeptid"> <option value="">Select upper dept.</option> <form:options items="${deptInfoOneDepthCategory}" /> </form:select> </td> </tr> <tr> <th>Desc.</th><td><form:textarea path="description" rows="10" cols="40"/></td> </tr> </table> ... <input type="submit" value=“Save"/> <input type="button" value=“List Page" onclick="location.href=/easycompany/departmentList.do?depth=1"/> ... </form:form> Page l 91
  92. 92. Page l 92

×