Spring Core

Spring Professional Certification

Spring Professional Certification


Ursula Fernes
Diese Lernkarten bieten einen umfassenden Einblick in die Spring Core-Funktionen, insbesondere im Bereich der Konfiguration, JMS, RMI und JMX. Sie behandeln Themen wie die Konfiguration von MBeans, die Nutzung von JMS für asynchrone Nachrichtenverarbeitung und die Implementierung von Remote Services mit RMI. Entwickler, die Spring Core für die Erstellung robuster und skalierbarer Anwendungen nutzen möchten, profitieren von diesen Lernkarten, da sie praktische Beispiele und Best Practices für die Integration und Verwaltung von Services bereitstellen.
Flashcards
227
Students
2
Language
German
Category
Computer Science
Level
Other
Created / Updated
21.10.2012 / 30.07.2016

Flashcards

@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

  1. retrieve object by primary key
  2. HQL (= Hibernate Query Language)
  3. Criteria Queries
  4. 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

  1. annotated classes
  2. 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

  1. DispatcherServlet(Request) gets HandlerMapping
    => which Controller is responsible for which url?
  2. HandlerMapping(Request) returns Controller
  3. Controller(Request) returns Model & View
  4. ViewResolver(View Name) returns View
  5. View(Model) returns Response
  6. 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

  1. ApplicationServer => http://www.homegate.ch
  2. webapp => /hg
  3. Servlet Mapping => /advertise
  4. 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

  1. define listener to load root ApplicationContext  before initializing DispatcherServlet
  2. 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)

  1. Servlet API - HttpSession, HttpServletRequest, HttpServletRespons
  2. Stream - InputStream, Reader, OutputStream, Writer
  3. Annotated - @PathVariable, @RequestParam, @RequestHeader, @RequestBody
  4. Model - Map, Model, ModelMap
  5. Others

Spring Security: 5 Motivations

  1. Portability
  2. Flexibility
  3. Extensibility
  4. Seperation of Concerns
  5. 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)

  1. business logic is decoupled from security concerns
  2. authentication and authorization are decoupled
    => changes to authentication process have no
          impact on authorization

Spring Security & Consistency (2)

  1. goal of authentication is always the same regardless of mechanism
  2. process of authorization is always the same regardless of resource type

Security filter chain

5 filters

  1. HttpSessionContextIntegrationFilter
    establishes SecurityContext and maintains between HTTP requests
  2. LogoutFilter
    logging out if needed / clears SecurityContext
  3. AuthenticationProcessingFilter
    authenticating if needed / puts authentication into SecurityContext on login request
  4. ExceptionTranslationFilter
    converts SpringSecurity exception into HTTP response or redirect
  5. 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

  1. hasRole('role')
  2. hasAnyRole('role1', 'role2', ...)
    => "or" clause
  3. isAnonymous()
    => allows access for unauthenticated principals
  4. isAuthenticated()
    => allows access for authenticated or
          remembered principals
  5. 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

  1. Database
  2. In-Memory (properties file)
  3. 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 = ?

Study