Jersey Async REST



  • Jersey 1 uses com.sun.jersey
  • Jersey 2 uses org.glassfish.jersey.*
  • Make sure you know which version you are using


  • Jersey does not require servlet framework
  • Grizzly HTTP container can be used
  • Grizzly is a framework using Java NIO API
  • Divided into Core Framework and HTTP Services

HTTP vs. Servlet Containers

  • Servlet Container uses War file with web.xml file and source
  • HTTP Container uses a Main classto launch rest of source and deploys in Jar
  • Lots of other containers can be used (jetty, jdk, simple http, tomcat)

Generating starter project

  • Use Maven archetype

  • Generates Plain Old Resource (

  • Generates with resource config elements


  • Scans for components using packages() and files()
  • Register custom JAX-RS componenets with register()
  • Get and set application properties

Simple example

Testing with JerseyTest

  • Leverages existing jersey components
  • JerseyTest provide both Container and Client
  • Tests use the client to invoke API’s deployed in container
  • Important methods:
    • configure()
    • configureClient()
    • target()
    • enable()

Configuring Container and Client

Invoking an endpoint

Example tests

Test properties

  • It is possible to configure features and properties when running tests

Dependency injection and POST support

  • Using the @Context annotation
  • Many different Classes available for injection

  • Using HK2 to add to @Context and inject our own objects

  • Requires a Binder registered with ResourceConfig

Async requests

  • @ManagedAsync and @Suspended are commonly used annotations

  • Grizzly Threads receives request -> Passes on to Jersey Async Threads

  • Databases (or other Applications) may provide their own async interfaces

  • Application Threads can be combined with Jersey Async Threads

  • AsyncResponse can be used in many different ways

  • Guava can be used in DAO to give it an asynchronous interface

  • URI invoked -> Resource method -> DAO method | ListenableFuture.onSuccess(stuff) <-|

  • Collections and Concurrent hashmaps may cause issues using the built-in Moxy JSON support

  • Good thing we can use Jackson instead!


  • Jackson can process data (json, xml etc.)
  • Register in resource config
  • Watch out for format changes on dates, enums, properties etc.
  • Has many annotations and configs for changing behaviour and formats

  • Jackson can store arbitrary elements that are submitted using annotations

  • Adding XML support

  • Prioritize json over xml

  • Other XML annotations


  • Converts Java type to Stream
  • Can be used to format json and xml differently
  • Uses isWrtieable to determine which MBW to use

Bean Validation, Exceptions and Conditional GET

  • Beans can be validated with Annotations
  • Hibernate Validator is used in Jersey
  • Setup in pom.xml and can be configured in resource config
  • Possible to write custom ValidationConfig class

  • Validate using @Valid and @NotNull annotations

  • Possible to map Exceptions to Responses

  • Use EntityTags to support “If-None-Match” and conditional GETs

  • Use ResponseBuilder to build() response to client

  • ResponseBuild can set any header (cache, cookie, encoding, links, last modified etc.)

PATCH support

  • Extend Jerseys supported HTTP verbs with PATCH
  • Can be used through a custom annotation
  • Needs a custom client connector like Grizzly’s

  • Can be extended by supporting the If-Match header

  • Uses evaluatePreconditions as conditional GETs

  • The caller supply an entity tag which must match the servers

  • If not, it’s assumed the servers tag has changed

Filters in Jersey

  • Supports JAX-RS filters
  • Can modify requests and responses
  • Pre-Matching Request Filter
    • Applied to incoming request before method is selected
  • Post-Matching Request Filter
    • Applied after Resource method is selected but before execution
  • Response Filter
    • Applied after Resource method
  • Filters need modification to use async functionality, runs in Grizzly Thread by default
  • Can use Name Binding to control usage of filters

Filters vs Interceptors

  • Filters
    • Modify headers, entity and other request/response params
    • Executed regardless of wheter there is an entity to read/write
    • Can abort a request and prevent resource method from executing
  • Interceptor

    • Primarily to manipulate the entity
    • Can change properties to affect choice of Message Body Reader/Writer
    • Only executed if there is an entity to read/write
  • Execution Order

    1. Pre-Match filters
    2. Post-Match filters
    3. Reader Interceptor
    4. Response Filter
    5. Writer Interceptor
  • Jersey Filters

    • Logging
    • JAX-RS to Spring Request attribute bridge
    • CSRF protection

    • HTTP method overrides

    • URI-based content negotiation

Custom filters

  • Possible to write custom request/response filters
  • Can use annotations to decide which type of request filter
  • Implements a filter method

  • Use name binding to choose when filter is applied

    1. Define a name binding annotation

    2. Associate annotation with filter or interceptor

    3. Use annotation to flag a resource method (or application)

Java Servlets and Faces Fundamentals

JavaEE Servlets and Faces


  • Java Applet designed to run on a server
  • Extend capabilities of server
  • Java counter part to PHP,
  • Request/Response model
  • Implements Java Servlet API (javax.servlet)


  • GenericServlet
  • HttpServlet


  • 3 phases
    1. Initialize: init()
    2. Send request to servlet: service()
    3. Remove: destroy()


  • Defines user interface
  • Has pre-built tags


  1. Create web page
  2. Associate page with components via tags
  3. Associate components with server side data through managed beans
  4. Create web deployment descriptor


  • 2 main phases

    1. Execute: Translates user input and executes code on the input
      • Build or refresh application view
      • Apply parameters of request
      • Recalculate components
      • Run the code
    2. Render: Translate machine output and renders it to human readable form
      • Generate new UI
  • 6 phases

    1. Restore view
      • When a request for a JSF page is made
      • Builds view and sets up event handlers
      • Put view in faces context index
      • If initial request, go straight to 6.
    2. Apply request values
      • Called on postback
      • Components extract values from request
      • Events that are queued can be broadcast and executed by listeners
    3. Process validations
      • Validates values for components
    4. Update model values
      • Stores local component values to server side components
    5. Invoke application
      • Application level events like submit form and navigate to other page
      • Can go to Complete face or Render response depending on target
    6. Render response
    7. Complete

Managed bean

  • Java object that represents a resource in the JVM
  • Bound to a:
    • Component value to validate some data
    • Component instance to handle events for that component (like page navigation)
    • Converter instance
    • Listener instance
    • Validator instance

Component rendering

  • javax.faces.component.UIComponent
    • Command
    • Form
    • Output
    • SelectOne
  • Behavioral interface
    • ActionSource2
    • StateHolder
    • ValueHolder

Web context

  • Normally one context per application
  • Can also be distributed (1 context per vm)
  • Basic parts
    • Init parameters
      • Specific values to be passed to certains components when application is run
        • Font type
        • Encoding
        • Data
      • Stored in web.xml
    • Associated resources and object value attributes
      • Stored in web context
      • Data and attributes available to all servlets
      • Basically a global storage
    • Functions dealing with logging data
      • Log error messages
      • Store and analyze user traffic data
      • Monitor latency

Client state

  • Requests are not independent
  • Need client state in application (session)


  • Represented by HttpSession object
  • Can store object-value attributes
  • Can listen to binding and activation events for the HttpSession
  • Session uses timeout for expiry
  • Calling a service method resets the TTL counter for the session

JavaEE Fundamentals

Java EE

Difference to SE

  • EE extends SE
  • EE tiers include web, client, business and information tiers with separate tools


  • Web Components
    • JSP/Servlets/EL/JSF/JavaBeans
  • Web Services
    • JAX-WS, JAX-RS
  • Data Access
    • JDBC, JPA (persistance api), JTA (transaction api)
  • Persistent Entities and Java Beans

HTTP Servlet

  • Allows client to interact with server
  • Similar to applet but run by server
  • Generally tightly focused in purpose
  • All servlets have the same methods available
    • init()
    • service()
  • Base class is GenericServlet extended by HttpServlet
  • Can execute Java code and generate HTML

JSP Overview

What is it?

  • A web page
  • A servlet
  • A view
  • Allows for more then just HTML


  • Include: can include files for use in the page
  • Page: gives ability to control things on page, import, sessions, ignores
  • Tag: allows for the use of tags to control libraries of code


  • Use <% %> to wrap code blocks
  • Allows Java execution in JSP file
  • May need additional imports
  • May require use of declarations


  • Use <%! %> to wrap declarations
  • Instantiate objects/variables/methods for use in scriptlets


  • Use <%= %> to wrap an expression
  • Renders object info to screen
    • Fill in forms
    • Render dynamic content

Expression language

  • Expressions to get managed information
  • Communicate well with objects
  • Chaining to get to properties
  • Use ${} to interact with EL

Tag libraries

  • Can be included for use in the page, pre-defined or custom
  • Accessed via the prefix assigned and valid methods from the library
    <%@ taglibname prefix="variable" uri="..." %>

JSP Actions

  • Standard
    • jsp:include
    • jsp:forward
    • jsp:useBean
    • jsp:getProperty
    • jsp:setProperty
  • Other
    • Core library actions on included in standard actions

Implicit objects


  • JSP allows for programming on the View
  • Interaction with the Controller
  • Other ways to navigate
  • Render dynamic content
  • Lots of tools already in place

Actions, JavaBeans and Expression Langage (EL)

Standard Actions

  • Available on JSP pages
  • Syntax is tag/markup language format
  • Most common
    • include – imports resources
    • forward – forwards the request
    • useBean – work with objects get/create
    • setProperty – set the bean object properties
    • getProperty – get the bean object properties
  • Other
    • element – xml
    • attribtue – xml
    • body – xml
    • text – template text for JSP page
    • plugin – embedded objects

Java Beans

  • Serializable class, used as Model
  • Contains a default no argument constructor
  • All properties use get/set/is methods
  • Other properties named in camelCase
  • Not the same thing as an Enterprise Java Bean
    • EJB is more persistance focused on services

Expression Language

  • Expressions give direct access to objects/beans
  • Access to every scope through implicit objects
    • sessionScope
    • pageContext
    • applicationScope
    • header
    • initParam
    • param
    • requestScope
    • cookie
  • Simple and powerful
  • Expressions are wrapped with ${}


  • Actions provide tag-like syntax for common operations
  • Beans is the specification we use to build models
  • EL is used to access the Bean data

Tag Libraries

  • Not included by default
  • Included as directive on JSP page
  • Core tags used for program/flow control on the page without having to use Java
  • Tags reference with prefix “c”

Custom tags

  • Declared with:

    • mlns, xmlns, xsi:schemalocation, version


    • The namespace/package
    • Must match or wont work
    • Link/location is irreleveant
    • Can be a simple identifier [i.e myTags]


Body content

  • Tag-dependent: Embedded commands handled by tag library
  • Empty: No body
  • Scriptless: String literals, EL expressions or tags only. No scriptlets.



  • Create class that extends SimpleTagSupport (tag-class)
  • Implement the doTag() method for execution
  • Must have public mutators for any attributes on the tag

EL Functions

  • Define in TLD file
  • Map to Java class that performs the function
  • Must also define which method to run with its return type and parameter


  • Passed in chains
  • Can be used to parse request and response data for specified paths
  • Filter can for example validate a user before the filter chain can complete
  • If auth filter fails, the filter can redirect to login rather then continue the chain
  • Some older filters have to be defined in web.xml


  • Can intercept data and inspect parameters for validation or authentication
  • Can also modify parameters (uppercase, lowercase, validate)
  • Uses a filter on the request
  • Applied in a filter as the request/response goes through the chain

HTTP Server authentication and authorization (Tomcat)


  • Copy config file for backup
  • Remove all comments
  • Add roles

  • Add users


  • Copy config file for backup
  • Remove all comments (except realm info and ssl port)
  • Comment out
  • Add Realm for memory


Security constraint




  • Configure webserver with keystore
  • Configure web.xml

Spring JPA Hibernate Fundamentals


  • Interface for a specific ORM implementation
  • Actually just a specification thought of as an Object Relational Mapping tool
  • CRUD for Java objects and a relational database
  • Uses JPQL (Java Persistence Query Language)
  • Heavy focus on POJO and its mapping to the database
  • Many providers: EclipseLink (TopLink), DataNucleus, ObjectDB, OpenJPA, Versant, Hibernate
  • Using JPA to talk to ORM makes transitioning easy


  • Controller <-> Service <-> Repository <-> DB
  • Controllers handle requests
  • Service handles business logic
  • Repository saves data to db through EntityManager


  • ORM (sql)
  • OGM (nosql)
  • Search
  • Validation

Configuring JPA

  • Add ContextLoaderListener to web.xml to load jpaContext.xml


  • Add namespaces beancs, xsi, tx, context
  • Add context annotation config and scanner that points to package with classes
  • Add persistance annotation bean post processor to inject persistence context into entity manager factory
  • Create local entity manager factory
    • persistence unit
    • data source
    • vendor adapter
    • turn on to show sql
    • map to jpa property map to set dialect and sql formatting
  • Create transaction manager and enable tx annotations for the transaction manager
  • Create datasource with user, password, url and driver class name

jpaPropertyMap properties
  • hibernate.dialect (MySQLInnoDB)
  • hibernate.format_sql (formats output)
  • (creates database for us automatically)
    • create
    • create-drop
    • update
    • validate
    • none

Entity and Business Objects

  • Is a POJO with @Entity annotation and @Id

  • Good for storing data and maps to the database

  • Business objects can join several entities and be presented to user

Java Persistence Query Language (JPQL)

  • This is not SQL
  • Centered around objects, take care of naming!

JPA Annotations

  • xml and hbm files can also be used to bind objects
  • use @PersistenceContext to get the entityManagerFactory and inject it into code

Fetch types

  • Lazy queries when property is called

    • Can throw LaxyInitializationExeption which is very common when session is clsed
    • OpenEntityManagerInViewFilter can be used to prevent sesion being closed to early

  • Eager queries when object is created


  • Selects the fields we are actually interested in
  • Great way to present objects to UI
  • Objects are added using JPQL-syntax
  • Projection objects can be Jpa Entities
  • Need a constructor for the projection
  • Can join entities into a non-entity (requires getters and setters)


  • Cleaner than adhoc JPQL
  • Not required but focuses on the domain and is stored in domain objects
  • Has named parameters

Spring Data JPA

  • In JPA Persist and Merge (Create and Update) are different methods that return different objects
  • Framework to eliminate boiler plate code in the DAO layer

  • Spring JPA wraps JPA by replacing the Repository Tier to eliminate boiler plate code

  • Can be extended for more complex functionality
  • No support for named queries



  • Uses Spring Data JPA jar (contains incompatable jar with Spring AOP)
  • Spring JPA uses the interfaces to perform the functionality so we don’t need implementation classes
  • Interfaces extend JpaRepository<T, T(id)> and uses @Repository

Java Enterprise Beans Fundamentals

JavaEE Essentials – Enterprise Beans


Session Bean

  • Series of methos encapsulated in a bean
  • Stores only local data
  • Used to execute main bulk of program
  • Associated with single client session
  • Can execute a single or series of transactions
  • State is managed by the EJB container


  • Runs i a client bean session
  • Associated with a client state


  • Any client can invoke the methods
  • Can keep state that lasts for the duration of the invocation


  • Once per application
  • Keeps state for duration of application execution
  • Bean equivalent of global variables
  • Perform startup and cleanup tasks

Entity Bean

  • Associated with a data set not a session
  • Esentially permanent
  • Uniquely identified by a primary key
  • Don’t necessarily require a client

Message Bean

  • Receives JMS messages asynchronously and acts upon them
  • Does not have a client interface
  • Can only respond to single client message
  • Used to handle special events

Programming on a Server

  • Watch out for latency and rw conflicts


  • Limited communication speed
  • Reduce through workflow balancing

Concurrent access

  • Mutliple requests to shared resources

Session & Entity Objects (Coarse Grained)

  • Interfaces with blocks of data
  • Deals with more complex data

Session objects

  • Created within a specific client session
  • Lasts as long as the client
  • Keeps Conversational State (a connection with one or more clients)
  • Coarse grained

Entity objects

  • Persistent across multiple clients and instantiations
  • Keeps state with a primary key that identifies the bean
  • Client uses key to reconnect to bean if it exists
  • If bean is not available, it can be recreated with the persistent data
  • Coarse grained

Client vs Server side

  • Main difference is program output
    • Server produces data for client
    • Client presents data to user
  • Beans primarily for server programs


  • Work with databases
  • Display pages
  • Validate and handle user input
  • Authentication, verification and monitoring


  • Interface with server
  • Generate dynamic web pages
  • Taking in user input
  • Work with local storage
  • Send/receive requests with server

Bean lifecycle

Stateless Session Bean

Uncreated -> setSessionContext -> Active -> ejbRemove -> Destroyed

Stateful Session Bean

Uncreated -> setSessionContext -> Active -> ejbPassivate -> Passive
ejbCreate ejbActivate <- Passive -> ejbRemove -> Destroyed

Entity Bean

Uncreated -> setEntity -> Pool -> ejbActivate -> Active
Pool <——————— remove

Message Bean

Uncreated -> setSessionContext -> Active -> ejbRemove -> Destroyed
-> onMessage -> OnMessage
Active <—————–


  • Most beans don’t use concurrency since they are only accessible by one client at a time
  • Multiple clients -> multiple beans
  • Databases must also handle paralellism
  • Singleton Session Beans must take parallelism into consideration to handle multiple clients
    • Use @Lock(Write) at methods to protect from writing and writing
    • Use @Lock(Read) at methods to protect from duplicate reading
    • Use @AccessTimeout(value=100) to control timeout for concurrent access
    • Use @ConcurrencyManagement(Bean) for bean control
      • “volatile, synchronized” and other mechanisms can also be used

Exclusive Read Exclusive Write (EREW)

  • One CPU can access a memory location at a given time
  • Other CPU’s will be locked out
  • Safe but slow

Concurrent Read Exclusive Write (CREW)

  • Allows multiple reads
  • Only 1 can write
  • Faster the EREW

Concurrent Read Concurrent Write (CRCW)

  • No restrictions on reading and writing
  • No locking algorithm
  • Very fast but requires careful programming

Maximising performance

  • Minimize computations
  • Minimize length of non-parallizable sections
  • Minimize overhead cpu<->cpu communication
  • Find paralellism possibilities, refactor
  • Load balance to keep processors working at all times
  • Minimize communication overhead



  • Simple
  • Based on user roles and access methods
  • Uses access levels
  • Can map users to more general roles with lots of users
  • On class: @DeclareRoles(values = {“admin,guest”})
  • On method: @RolesAllowed(value = {“admin”}) (@Deny @Allow)


  • Harder
  • More powerful and easy to make mistakes
  • Methods:
    • Invoked in method
    • SessionContext.getCallerPrinciple()
    • SessionContext.isUserInRole()

Asynchronous methods

  • Apply to method or entire class
  • Methods return void or Future result type
  • Use: @Asynchronous annotation
  • Use: AsyncResult to cast result


  • Failures are ok, clients can re-send
  • Much more efficient to allow occasional failures
  • Sometimes necessary to NOT fail or fail in SPECIFIC way
  • Multiple steps trated as single unit of work
  • Use: @TransactionAttribute to mark methods for transactional behaviour
    • required
    • requiresNew
    • mandatory
    • supports
    • notSupported
    • never

Spring Fundamentals

Spring overview

  • Framework to reduce complexity around EJB
  • Allows enterprise development without Application Server
  • POJO based and Interface driven
  • Lightweight and unobtrusive compared to older J2EE methodoligies
  • Uses AOP and Proxies to remove Cross-Cutting Concerns
  • Increases Scalability, Testabiliy and Maintainability
  • Puts focus on the Business
  • Can be seen as a glorified HashMap
  • Can be used as a Registry

Project setup

  • Add libraries to build path
  • Define mappings in applicationContext.xml
  • ApplicationContext can be instantiated in main() using ClassPathXmlApplicationContext()

XML Configuration


  • Can be defined in applicationContext
  • Needs ID or Name
    • Id has to be valid xml identifier
    • Name can contain special chars
  • Default no-args constructor
    • Setter injection uses properties on beans
    • Construction injection uses constructor-arg element
  • Regular class with getters and setters


  • Spring wires beans together instead of mapping in xml
  • Can be wired by:
    • Type: bean of property type must be unique in the container
    • Name: wire by property name
    • Constructor: same as type but for constructors
    • None
  • Can be configured in xml or class


  • Uses component scanner from the context namespace

  • 3 main types of annotations (stereotype annotations)

    • @Service and @Repository extend @Component but do not add features
    • @Component used for components/beans, any POJO
    • @Service, service tier where business logic is contained
    • @Repository, data access tier (dao’s)
  • Can perform Autowiring on member variables, constructor and setters


  • Light weight dependency injection specification for Java
  • Simple annotations
  • Spring offers more features

Java Configuration

  • No need to configure with xml, we can use Java annotations
  • Not all spring releases are fully supported
  • @Configuration annotation replace applicationContext at class level
  • Methods used in conjunction with @Bean are used to get instances of beans

  • No applicationContext.xml needed, we use an app config class instead

  • Beans can be fetched from the context

Setter injection

  • Setter injection is as simple as a method call (mystery of injection goes away)
  • Call the setter

Cosntructor injection

  • Same as setter injection but uses constructor instead
  • Requires constructor in implementation class (CustomerServiceImpl here)


  • Add @ComponentScan annotation on the app config class

  • Just like xml configuration we mark what we want with @AutoWired (byName uses bean name byType uses instance type)

  • Possible to mix configurations with injection and autowired


  • Classes and instances can have different scope
  • Defines with @Scope in java or xml bean attribtue
  • Singleton is default
  • Prototype gives new instance for each request from bean
  • Web scopes (Request, Session, GlobalSession)covered in Spring MVC

Property files

  • Good to keep environmental information out of app
  • Context Namespace has utilities to help load files

XML configuration

Java configuration

  • Use @PropertySource(“”) annotation in AppConfig
  • To use in POJO, bean configuration is needed

  • Much cleaner in xml

Spring MVC fundamentals

Spring MVC

Other framworks

  • Struts
  • Tapestry
  • Wicket
  • GWT
  • JSF
  • Seam
  • Stripes

What is Spring MVC

  • General Web (JSP/REST/Headless/Remoting) framework
  • POJO based and interface driven
  • Based on Dispatcher Servlet / Front Controller pattern


  • DispatcherServlet – Entry point for the application
  • Controller – Command pattern object that handles request and routes to a view
  • RequestMapping – URL and Request Type that method is tied to (GET/PUT/POST…)
  • ViewResolver – Used to locate JSP pages or whatever view we are using
  • Servlet-config – Configuration per DispatcherServlet

Spring MVC Configuration

  • Configure web.xml
  • Configure servlet-config.xml
  • Add Controller
    • Controllers are annotation based using @Controller
    • Controller path is set using annotations @RequestMapping
  • Add View
    • Put views under WEB-INF/jsp/*.jsp and redirect using InternalResourceViewResolver




Controller (@Controller)

  • Routes requests
  • Builds response
  • Handles exceptions
  • Recommended to put request mapping on methods

Service (@Service)

  • Handles actions of a system
  • Service contains business logic
  • Ensures the business object is in valid state
  • Transactions begin here
  • Often same method as Repository but different focus (set default etc.)

Repository (@Repository)

  • Repository accesses data through database
  • Usually mapped 1-1 with db-tables
  • Focuses on persisting and interacting with database (CRUD)

Request/Response lifecycle

  1. Incoming request -> Front Controller -> Delegate Request -> Controller -> Handle Request -> Backend
  2. Backend -> Create Model -> Controller -> Delegate Rendering (Model) -> Front Controller -> Model -> View Template -> Front Controller -> Return Response

Passing params

  • Request[‘params’] -> Controller[‘model’] -> Response
  • Model used for both get/post to database
  • Use @ModelAttribute to send data or retrieve data to/from Controller
  • Use with GET/POST on POJOs


  • Convention to place views in /WEB-INF/jsp/ directory
  • Allows us to completely control all routing, can make site more secure
  • View Resolver uses string returned from controller method
  • Controller can build model and return to View Resolver
  • Many different resolvers for different templating tools and return types
  • Possible to create static view resource mapping to publish images, pdf’s etc.

Tag Libraries

  • Two libs in Spring MVC
  • Can bind to objects from model
  • Can connect to css
  • Can escape data
  • Spring ex.
    • bind
    • escapeBody
    • hasBindErrors
    • htmlEscapt
    • message
    • nestedPath
    • theme
    • transform
    • url
    • eval
  • Spring Form ex.
    • checkbox(es)
    • errors
    • form
    • hidden
    • input
    • label
    • option
    • password
    • select


  • Registered and part of request lifecycle
  • Have ability to pre/post handle web requests before and after controller
  • Callback methods used to override or change values
  • Commonly used for locale changing


  • Constraint validation
    • Expecting data like “firstname”, “password” must not be null and contain some specific data
  • Business logic validation
    • Rather constraints on what values are handled
    • Should be handled i service tier, not controller
  • Form tags have an error class for displaying errors

  • Validator interface

    • ValidationUtils helper class used with simple form controller
    • Implements Validator Interface
    • Requires lots of hands on coding for validation
    • Binds to a BindingResult
    • Can be used in Service tier to do things outside of spring
    • Can use SimpleFormController
    • Limited use and not annotation supported
  • JSR 303 validation

    • Java standard for validation
    • Integrates well with Spring for validation and reporting errors
    • Annotation based and can use custom validation rules
    • Reference implementation is the Hibernate Validator (not same as Hibernate ORM!)
    • POJO based

Application request types

  • Can set up to handle json and xml etc.
  • Configure in servlet xml

  • Dispatcher Servlet needs to be configured to allow different request types

Dynamic localization of JSR 303 validation messages with wildcards

Lets say you have a class like this

And you want to localize the messages in a file, you might do something like this:

Now you have hardcoded the values in multiple places, imagine if you have multiple properties files for different languages, you would define the values everywhere!

Instead you can do this:

And this:

Now, why are we using {2} and {1}?

The attributes are ordered alphabetically! From the board:

For the first option, Spring-managed field error arguments include the actual constraint annotation attributes in alphabetical order now. So for @Size(min=1,max=5), it’ll include the field name as {0} , the max value as {1} , and the min value as {2}

Has caught me many times.