Spring Core
Spring Professional Certification
Spring Professional Certification
-
- 1 / 227
-
Cartes-fiches
@Table
@Table(name="T_CUSTOMER")
- optional
- overrides table name
@Id
- mandatory
- marks primary key
@Column
@Column(name="first_name")
- optional
- overrides column name
@Transient
- optional
- marks data-memvers that are not stored in database
@Access
By default Hibernate uses field access and not property (getter/setter) access.
@Access(AccessType.PROPERTY) on class level
=> setter and getter of class will be used
@Access(AccessType.FIELD) on field level (= overriding)
=> direct field access will be used
Hibernate Querying: 4 ways
- retrieve object by primary key
- HQL (= Hibernate Query Language)
- Criteria Queries
- standard SQL
Hibernate Querying: By primary key example
Long customerId = new Long(123);
Customer customer = (Customer) session.get(Customer.class, customerId);
NOTE: returns null if no object exists for identifier!
Hibernate Querying: HQL example
Query query = session.createQuery("from Customer c where c.address.city = :city")K
query.setString("city", "Chicago");
List customers = query.list();
NOTE: for single result use query.uniqueResult()
NOTE: cast is necessary!!
Hibernate SessionFactory:
2 ways of declaration
- annotated classes
- packages to scan
Hibernate SessionFactory:
example with annotated classes
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.
AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>example.Customer</value>
<value>example.Address</value>
</list>
</property
</bean>
NOTE: wildcards for entities are NOT supported!
Hibernate SessionFactory:
example with packages to scan
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.
AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan">
<list>
<value>com/springsource/*/entity</value>
</list>
</property
</bean>
Hibernate & read-only transactions:
characteristics
@Transactional(readOnly=true)
public List<Confirmation> listConfirmationsFrom(Date d) {
// read-only, atomic unit-of-work
}
- prevents hibernate from flushing its session
=> possibliy dramatic performance improvement - marks JDBC Connection as read-only
=> provides additional safeguards with some db's
(e.g. Oracle only accepts SELECT statements)
DispatcherServlet
characteristics
= heart of Spring Web MVC (≈ front controller)
- coordinates all request handling activities
- delegates to web infrastructure beans
(handler mapping, view resolver, type converter) - invokes user web components
DispatcherServlet configuration
4 characteristics
- defined in web.xml
- uses spring for its configuration
- creates seperate "servlet" application context
(= DispatcherServlet ApplicationContext) - full access to parent "root" contect
(= Root ApplicationContext)
NOTE: Root ApplicationContext can NOT see DispatchServlet ApplicationContext!!!
Spring MVC: general configuration
2 entries
<mvc:annotation-driven/>
- registers DefaultAnnotationHandlerMapping and AnnotationMethodHandlerAdapter beans
=> dispatch requests to @Controller
<context:component scan />
- enables autodetection of @Controller annotated beans as well as other stereotype components
DispatcherServlet ApplicationContext vs
Root ApplicationContext
- DispatcherServlet ApplicationContext can see configuration of Root ApplicationContext but
Root ApplicationContext can NOT see DispatchServlet ApplicationContext - DispacthServlet ApplicationContext can override root context beans
Spring MVC Request Processing
6 steps
- DispatcherServlet(Request) gets HandlerMapping
=> which Controller is responsible for which url? - HandlerMapping(Request) returns Controller
- Controller(Request) returns Model & View
- ViewResolver(View Name) returns View
- View(Model) returns Response
- DispatcherServlet renders Response
Handlers in Spring @MVC
=> typically called ...
=> annotations
=> ... controllers
@Controller
public class AccountController
{
@RequestMapping("/listAccounts.htm")
public String list(Model model) { ... }
}
NOTE: At load time RequestMapping string is passed to HandlerMapping!
Spring @MVC calling URL
4 parts
http://www.homegate.ch/hg/advertise/updateObject.htm
- ApplicationServer => http://www.homegate.ch
- webapp => /hg
- Servlet Mapping => /advertise
- Request Mapping => /updateObject.htm
Spring @MVC: Handler Method Parameters
=> 2 annotations
@RequestParam
@RequestMapping("/showAccount")
public String show(@RequestParam("entityId") long id, Model model) { ... }
http://localhost:8080/.../.../showAccount.htm?entityId=123
@PathVariable
@RequestMapping("/accounts/{accountId}")
public String show(@PathVariable("accountId") long id, Model model) { ... }
http://localhost:8080/.../.../accounts/123
Spring @MVC: View Resolver
=> when is it called
=> function
=> default rules
=> DispatcherServlet delegates to View Resolver
=> View Resolver maps view names returned by
controller to correct view to call
=> by default view name is interpreted as web application
relative file path
Bootstrapping root WebApplicationContext:
2 steps
- define listener to load root ApplicationContext before initializing DispatcherServlet
- define DispatcherServlet
NOTE: conifg goes to web.xml
Bootstrapping root WebApplicationContext:
define listener (step 1)
web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appl-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.
web.context.ContextLoaderListener</listener-class>
</listener>
Bootstrapping root WebApplicationContext:
define servlet (step 2)
web.xml:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.
web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigListener</param-name>
<param-value>/WEB-INF/web-appl-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
...
</servlet-mapping>
@RequestMapping
1. characteristics
2. definition (incl. conditions)
1. characteristics
=> URL-based mapping telling what method to execute
=> wildcards allowed
=> normally on method level, optionally on class level
(get combined but slashes have to be added)
2. definition
=> header condition example
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String ownerId, Model model) { ... }
=> headers condition: ... headers="content-type=text/*"
@RequestMapping
main parameter types (5)
- Servlet API - HttpSession, HttpServletRequest, HttpServletRespons
- Stream - InputStream, Reader, OutputStream, Writer
- Annotated - @PathVariable, @RequestParam, @RequestHeader, @RequestBody
- Model - Map, Model, ModelMap
- Others
Spring Security: 5 Motivations
- Portability
- Flexibility
- Extensibility
- Seperation of Concerns
- Consistency
Spring Security & Portability
Spring Security is portable across containers (WebLogic, Websphere, etc.)
Spring Security & Flexibility
- supports all common authentication mechanism
(Basic, Form, Single-Sign-On, X.509, Cookies) - provides configurable credential storage options
(RDBMS, LDAP, Properties file, comman DAO's, etc.) - uses Spring for configuration
Spring Security & Extensibility (4)
With Spring security all of the following points are extensible:
- principal definition
- storage place of authentication
- authorization decisions
- storage place of security constraints
Spring Security & Separation of Concerns (2)
- business logic is decoupled from security concerns
- authentication and authorization are decoupled
=> changes to authentication process have no
impact on authorization
Spring Security & Consistency (2)
- goal of authentication is always the same regardless of mechanism
- process of authorization is always the same regardless of resource type
Security filter chain
5 filters
- HttpSessionContextIntegrationFilter
establishes SecurityContext and maintains between HTTP requests - LogoutFilter
logging out if needed / clears SecurityContext - AuthenticationProcessingFilter
authenticating if needed / puts authentication into SecurityContext on login request - ExceptionTranslationFilter
converts SpringSecurity exception into HTTP response or redirect - FilterSecurityInterceptor
authorizes web requests based on config attributes and authorities / checking role
Spring Security: intercept-url
=> evaluation rules
=> 2 ways of configuration
=> first match will be used (specific matches on top!)
NEW way with Security EL:
<security:http use-expressions="true">
<security:intercept-url pattern="/accounts/edit*"
access="hasRole('ROLE_ADMIN')" />
...
</security:http>
OLD way:
<security:http>
<security:intercept-url pattern="/accounts/edit*"
access="ROLE_ADMIN" />
...
</security:http>
NOTE: can NOT be mixed!
Intercept-url with Expression Language
=> advantages
=> 5 expressions example
provides more flexibility
- hasRole('role')
- hasAnyRole('role1', 'role2', ...)
=> "or" clause - isAnonymous()
=> allows access for unauthenticated principals - isAuthenticated()
=> allows access for authenticated or
remembered principals - hasRole('role1') and hasRole('role2')
=> "and" clause
login & logout configuration example
<beans...>
<security:http>
<security:form-login login-page="/login.htm" />
<security:intercept-url pattern="..." />
...
<security:logout />
</security:http>
</beans>
configure authentication (basics)
<beans ...>
<security:http> ... </security:http>
<security:authentication-manager>
<security:authentication-provider>
...
</security:authentication-provider>
</security:authentication-manager>
</beans>
mechanisms to store user details
- Database
- In-Memory (properties file)
- Others (LDAP, JAAS, SSO, ...)
Authentication configuration: In-Memory
<security:authentication-manager>
<security:authentication-provider>
<security:password-encoder hash="md5" />
<security:user-service
properties="/WEB-INF/users.properties" />
</security:authentication-provider>
</security:authentication-manager>
NOTE: password encoding is optional!
Authentication configuration: JDBC
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service
data-source-ref="myDataSource" />
</security:authentication-provider>
</security:authentication-manager>
NOTE: Default RDBMS queries are provided!
SELECT username, password, enabled FROM users WHERE username = ?
SELECT username, authority FROM authorities
WHERE username = ?