03.egovframe runtime environment training book supplement
DESCRIPTION
eGovFrame - Framework for e-government Runtime Environment Training Book SupplementTRANSCRIPT
eGovFrame Training BookRuntime Environment
<Supplement>
eGovFrame Center
2012
Table of contents
Overview
Foundation Layer
Persistence Layer
Presentation Layer
Page l 2
I
II
III
IV
Page l 3
Runtime Environment Composition Overview
Runtime Environment is the foundation of software applications and provides the basic
functionality required to run software
eGovFrame Runtime Environment
Foundation Layer
Service Group
Presentation Layer Business Logic Layer Persistence Layer Integration Layer
Page l 4
Runtime Environment Composition Overview
Runtime Environment provides libraries of common modules consisted of 5 service layers and 34
services that work as a core foundation for running SW applications
Service Group Service
Foundation Layer
AOP
FTP
Object Pooling
XML Manipulation
Cache
Server Security
Marshalling/Unmarshalling
Compress/Decompress
ID Generation
Property
Encryption/Decryption
IoC Container
Resource
Excel
Logging
Scheduling
File Handling
String Util
Integration LayerPersistence LayerBusiness Logic LayerPresentation Layer
2. 공통기반 레이어
DataSource
Transaction
Process Control
Exception Handling Integration Service
Naming Service
Web Service
Data Access
ORMAjax Support
MVC
UI Adaptor
Internationalization
Security
File Upload/Download
eGovFrame Runtime Environment
Page l 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 6
Runtime Environment OSS Overview
Runtime 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.0XML Manipulation
http://xerces.apache.org/xerces2-j/
JDOM 1.1 http://www.jdom.org/
java simplified encryption (jasypt) 1.7 Encryption/Decryption http://www.jasypt.org/
Apache POI 3.2Excel
http://poi.apache.org/
jXLS 0.9.8 http://jxls.sourceforge.net/
Castor 1.2Marshalling/Unmarshalling
http://www.castor.org/
Apache XML Beans 2.4 http://xmlbeans.apache.org/
Quartz 1.8.5 Scheduling http://www.opensymphony.com/quartz/
Page l 7
RE*) Open Source - Spring Framework Overview
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
Foundation Layer
· RE*) : Runtime Environment
Page l 8
Spring Framework Composition
Spring Framework consists of DAO, ORM, AOP, JEE, Web, based on the core that governs the
Bean object life cycle
Foundation Layer
Page l 9
IoC Container
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
Foundation Layer
Page l 10
IoC Container - Container
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
Foundation Layer
Page l 11
IoC Container - Container
Example
Foundation Layer
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 12
IoC Container
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>
Foundation Layer
Page l 13
IoC Container
Bean configuration (XML)
• Bean definitions contain information about initialization dependency injection
Foundation Layer
<bean id=""
name=""
class=""
factory-bean=""
factory-method=""
lazy-init=""
dependency-check=""
depends-on=""
scope=""
init-method=""
destroy-method=""
autowire=""
autowire-candidate=""
primary=""
abstract=""
parent="">
<constructor-arg/>
<property/>
<lookup-method/>
<replaced-method/>
<qualifier/>
</bean>
[Bean Name] Setting Bean id or name
[Bean Class] Setting Class to be initialized
[Bean Instantiation] Setting instance mehtod
[Dependency Check] Setting dependency check info.
[Bean Scope] Setting bean scope
[Bean lifecycle callback] Setting lifecycle callback method
[Autowiring] Setting autowiring injection method
[Bean inheritance] Setting inheritance info.
[Dependency Injection] Setting dependency injection
[Method Injection] Setting lookup method injection
[Autowiriing setting] Setting additional info for autowiring
Page l 14
IoC Container
Bean name
• All bean definitions have only one id, and more than one name. id must be unique in container
• Bean definition can supply more than one name by using <alias/> element
Bean Class
• All bean definitions need java class for instantiation
<bean id="exampleBean" class="example.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>
<alias name="fromName" alias="toName"/>
<bean id="exampleBean" class="example.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>
Foundation Layer
Page l 15
IoC Container
Bean instantiation
• Generally bean instantiation is equal to java‟s „new‟ operator
• In addition, bean instantiated by static factory method as below
• Or by static method of other Factory class as below
• Traditional method
Foundation Layer
<bean id="exampleBean"
class="examples.ExampleBean“
factory-method="createInstance"/>
<!-- 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"/>
ExampleBean exampleBean = new ExampleBean();
ExampleBean exampleBean = ExampleBean.createInstance();
ExampleBean exampleBean = DefaultServiceLocator.createInstance();
Page l 16
IoC Container
Dependency Injection
• Constructor injection and Setter injection
• Constructor Injection : Injected by constructor with arguments
Foundation Layer
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 17
IoC Container
Dependency Injection
• type of index specified
Foundation Layer
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 index="0" value="7500000"/>
<constructor-arg index="1" value="42"/>
</bean>
<bean id="exampleBean" class="examples.ExampleBean">
<constructor-arg type="int" value="7500000"/>
<constructor-arg type="java.lang.String" value="42"/>
</bean>
Page l 18
IoC Container
Dependency Injection
• Setter injection with <property/> element
Foundation Layer
<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“
class="examples.ExampleBean">
<property name="beanOne">
<ref bean="anotherExampleBean"/>
</property>
</bean>
public class ExampleBean {
public void setBeanOne(
AnotherBean beanOne)
{
this.beanOne = beanOne;
}
}
Page l 19
IoC Container
Dependency Injection
• Straight values (primitives, Strings, and so on)
Foundation Layer
<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 20
IoC Container
Dependency Injection
• References to other beans
• Inner beans
Foundation Layer
<ref bean="someBean"/>
<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 21
IoC Container
Dependency Injection
• Collections : <list/>, <set/>, <map/>, and <props/> elements
Foundation Layer
<bean id="moreComplexObject" class="example.ComplexObject">
<!-- results in a setAdminEmails(java.util.Properties) call -->
<property name="adminEmails">
<props>
<prop key="administrator">[email protected]</prop>
<prop key="support">[email protected]</prop>
<prop key="development">[email protected]</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 22
IoC Container
Dependency Injection
• Collections : <list/>, <set/>, <map/>, and <props/> elements
Foundation Layer
...
<!-- 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 23
IoC Container
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
requestScopes a single bean definition to the lifecycle of a single HTTP requestOnly valid in the context of a web-aware Spring ApplicationContext
sessionScopes a single bean definition to the lifecycle of an HTTP SessionOnly valid in the context of a web-aware Spring ApplicationContext
global sessionScopes a single bean definition to the lifecycle of a global HTTP SessionOnly valid when used in a portlet context
Bean Scope
• Spring framework supports five scopes as follows .
Foundation Layer
Page l 24
IoC Container
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"/>
Foundation Layer
Page l 25
IoC ContainerFoundation 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 26
IoC ContainerFoundation Layer
Lifecycle callbacks
• Initialization callbacks
• InitializingBean interface allows to perform initialization work
• InitializingBean specifies a sinlge method:
• POJO initialization method
void afterPropertiesSet() throws Exception;
public class ExampleBean {
public void init() {
// do some initialization work
}
}
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
Page l 27
IoC ContainerFoundation Layer
Lifecycle callbacks
• Destruction callbacks
• DisposableBean interface allows to perform disposable work
• DisposableBean specifies a sinlge method:
• POJO initialization method
void destroy() throws Exception;
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 28
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.
IoC Container Foundation Layer
Page l 29
IoC Container
Annotation Type
• Using Java Annotation, Spring Bean definitions can be set, then need to add namespace and element
• Auto scan configuration, based on Annotation
Foundation Layer
<?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>
<?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 30
IoC Container
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
Foundation Layer
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
• @PostConstruct, @PreDestroy : Use to assign Instantiation callback, Destruction callback methods
@Service public UserServiceImpl implements UserService {
@Resource (name="userDAO")
private UserDAO userDAO;
}
Page l 31
IoC Container
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
Foundation Layer
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
• @PostConstruct, @PreDestroy : Use to assign Instantiation callback, Destruction callback methods
@Service
public UserServiceImpl implements UserService {
@Resource (name="userDAO")
private UserDAO userDAO;
}
Page l 32
IoC Container
Auto-detecting components
• Set bean name with @Component, @Repository, @Service, @Controller annotation‟s name value
• If name isn‟t set, camel case of class name is used
Foundation Layer
@Service("myMovieLister")
public class SimpleMovieLister {
// ...
}
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
Page l 33
IoC Container
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)
Foundation Layer
<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 34
AOP
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
OOP OOP + AOP
AOP
Applied
Configuration
File
Foundation Layer
Page l 35
AOP
Main Concept
• Advice, JoinPoint, Pointcut, Weaving, Aspect
Benefits
• Remove duplicate code
• Improve readability of the business logic
• Improve productivity
• Improve reusability
• Increase ease of change
Advice
Weaving JoinPoint
Pointcut
Foundation Layer
Page l 36
AOP
Relations for AOP components
Aspect
Advice
소스코드
Join point is the time
which a method is called in Spring
A set of Join point(condition: select*)
Processing what you want to apply
Joinpoint
EmployeeService
insertEmployee()
updateEmployee()
selectEmployeeList()
selectEmployee()
deleteEmployttList()
Pointcut
Source Code
Foundation Layer
Page l 37
AOP
Aspect definition
Foundation Layer
<bean id="adviceUsingXML" class="egovframework.rte.fdl.aop.sample.AdviceUsingXML" />
<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"
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>
<bean id="adviceSample" class="egovframework.rte.fdl.aop.sample.AdviceSample" />
Aspect
Pointcut
JoinPoint
Advice
Page l 38
AOP
Advice definition - before
Foundation Layer
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 39
AOP
Advice definition – after throwing
Foundation Layer
Advice definition – after (finally)
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);
}
...
}
public class AdviceUsingXML {
public void afterTargetMethod(JoinPoint thisJoinPoint) {
System.out.println("AspectUsingAnnotation.afterTargetMethod executed.");
}
…
}
Page l 40
AOP
Advice definition - around
Foundation Layer
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 41
Runtime Environment Services Services
Runtime Environment provides libraries of common modules consisted of 5 service layers and 34
services that work as a core foundation for running SW applications
Service Group Service
Foundation Layer
AOP
FTP
Object Pooling
XML Manipulation
Cache
Server Security
Marshalling/Unmarshalling
Compress/Decompress
ID Generation
Property
Encryption/Decryption
IoC Container
Resource
Excel
Logging
Scheduling
File Handling
String Util
Integration LayerPersistence LayerBusiness Logic LayerPresentation Layer
2. 공통기반 레이어
DataSource
Transaction
Process Control
Exception Handling Integration Service
Naming Service
Web Service
Data Access
ORMAjax Support
MVC
UI Adaptor
Internationalization
Security
File Upload/Download
eGovFrame Runtime Environment
Page l 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 43
Server Security Foundation Layer
Architecture
• General authentication and authorization process
Request resources
Offer resourcesSecured
Resources?
Authenticated?
Authorized?
Login User
Login? Error page
(HTTP 403)
Error page
(HTTP 503)
No
Yes
Yes
Yes
No
Yes
No
No
Page l 44
Server Security Foundation Layer
Architecture
• DB Schema
Page l 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 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 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 48
Server Security Foundation Layer
Authentication
• <http>
• auto-config
• Authentication Provider
<http auto-config='true'>
<intercept-url pattern="/**" access="ROLE_USER"/>
</http>
<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>
<http>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login />
<anonymous />
<http-basic />
<logout />
<remember-me />
</http>
Page l 49
Server Security Foundation Layer
Authentication
• <http>
• Authentication Provider
<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 user-service-ref="jdbcUserService">
<password-encoder hash="md5" base64="true"/>
</authentication-provider>
Page l 50
Server Security Foundation Layer
Authentication
• jdbcUserService
• JSP Sample
<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 = ?“/>
<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 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 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 53
Server Security Foundation Layer
Authentication
• Session management
• Confirm authentication
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());
Boolean isAuthenticated = EgovUserDetailsHelper.isAuthenticated();
assertFalse(isAuthenticated.booleanValue());
assertNull(EgovUserDetailsHelper.getAuthenticatedUser());
Page l 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 55
Server Security Foundation Layer
Tag Library
• Declaration
• Example
• Authentication tag
• Property=“principal.usrname”
• Authorize tag
• ifAllGranted, ifAnyGranted, ifNotGranted, and so on
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<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>
Page l 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 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 58
ID Generation Foundation Layer
Mac Address Base Service
IP Address Base Service
No 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>
<bean name=" UUIdGenerationService"
class="egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService">
<property name="address">
<value>100.128.120.107</value>
</property>
</bean>
<bean name=" UUIdGenerationService"
class="egovframework.rte.fdl.idgnr.impl.EgovUUIdGnrService“/>
Page l 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 60
ID Generation Foundation Layer
DB Sequence Id Generation
• DB Schema
• Setting
CREATE SEQUENCE idstest MINVALUE 0;
<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 61
ID Generation Foundation Layer
DB Table Id Generation
• DB Schema
• Setting
• 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
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');
<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>
Page l 62
ID Generation Foundation Layer
Strategy Base Service
• Setting
• prefix : letters that is added into the beginning
• cipers : length of id excepted prefix
• fillChar : character to be filled in id
<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>
Page l 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 64
Property Foundation Layer
Bean configuration Service
• Setting
• Java code
<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>
@Resource(name="propertyService")
protected EgovPropertyService propertyService ;
@Test
public void testPropertiesService() throws Exception {
assertEquals("1234",propertyService.getString("AAAA"));
}
Page l 65
Property Foundation Layer
External Property File Service
• Setting
• Properties file
<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>
AAAA=1234
Page l 66
Data Source
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
Persistence Layer
<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 67
Data Source
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)
Persistence Layer
Page l 68
Data Source
Key Features
• JNDI DataSource
- JNDI DataSource get DataSource using JNDI Lookup from WAS
Persistence Layer
<jee:jndi-lookup id="dataSource" jndi-name="${jndiName}" resource-ref="true">
<jee:environment>
java.naming.factory.initial=${jeus.java.naming.factory.initial}
java.naming.provider.url=${jeus.java.naming.provider.url}
</jee:environment>
</jee:jndi-lookup>
JEUS
<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" />
WEBLOGIC
Page l 69
Data Source
Java code
Persistence Layer
@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 70
Data Access
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)
Persistence Layer
Page l 71
Data Access
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
Round Trip Delay Time Short Long
Hibernate takes more time due to
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
Persistence Layer
Page l 72
Data Access
Composition
Persistence Layer
Page l 73
Data Access
SQL Map Config
Persistence Layer
<?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 74
Data Access
SQL Map
Persistence Layer
<?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 75
Data Access
Dynamic SQL
Persistence Layer
..
<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 76
Data Access
Dynamic SQL
Persistence Layer
..
<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 77
Data Access
Dynamic SQL
• Unary operation
• Binary operation
Persistence Layer
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
태그 설명
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 78
Data Access
Dynamic SQL
Persistence Layer
<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 79
MVC
Relationship and flow between Spring MVC components
Presentation Layer
Page l 80
MVC
Relationship and flow between Spring MVC components
Presentation Layer
Page l 81
MVC
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.
Presentation Layer
Page l 82
MVC
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
Presentation Layer
Page l 83
MVC
DispatcherServlet – web.xml
Presentation Layer
<!-- 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 84
MVC
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
Presentation Layer
<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 85
MVC
Controller
Presentation Layer
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 86
MVC
Controller
Presentation Layer
@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 87
MVC
Controller
• Mapping request parameters to method arguments using @RequestParam
• Using Common/form object
Presentation Layer
@Controller
public class HelloController {
@RequestMapping("/hello.do")
public String hello(@RequestParam("name") String name,
@RequestParam(value="pageNo", required=false) String pageNo){
...
}
}
@Controller
public class HelloController {
@RequestMapping("/hello.do")
public String hello(HelloData data, @ModelAttribute(“searchCondigion") SearchCondigion condition) {
...
}
}
Page l 88
MVC
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
Presentation Layer
Page l 89
MVC
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
Presentation Layer
Page l 90
MVC
ViewResolver
Presentation Layer
<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 91
MVC
View (JSP)
Presentation Layer
...<%@ 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 92