Persisting many to many Relationship (JPA and Spring Strategy)

This post is inspired by the “Netbeans Generate Entity Class From Database” feature which literally spits out vanilla JPA Entity classes for you while you have some coffee. For many to many relationship types Netbeans reads and generates an JPA Entity class for the join table and an extra class which holds the Primary key values for the two tables involved in a many to many relationship. This class is annotated with the @Embeddable JPA annotation. This i found very cool.

In this post i would like to show how to persist data from the respective tables to the join table.

The database create statement for the chosen table goes as follows:

create table Author (author_id int(10) not null auto_increment, name varchar(55) not null, email varchar(55) not null, primary key (author_id));
create table Book (book_id int(10) not null auto_increment, name varchar(55) not null, publisher varchar(55) not null, primary key (book_id));
create table Author_Book (author_id int(10) not null, book_id int(10) not null, primary key (author_id, book_id));
alter table Author_Book add index FKAuthor_Boo670752 (author_id), add constraint FKAuthor_Boo670752 foreign key (author_id) references Author (author_id);
alter table Author_Book add index FKAuthor_Boo981679 (book_id), add constraint FKAuthor_Boo981679 foreign key (book_id) references Book (book_id);

Netbeans generates the following for you.. No skin pain :)

Class Author Entity

@Entity
@Table(name = "Author")
@NamedQueries({
    @NamedQuery(name = "Author.findAll", query = "SELECT a FROM Author a"),
    @NamedQuery(name = "Author.findByAuthorId", query = "SELECT a FROM Author a WHERE a.authorId = :authorId"),
    @NamedQuery(name = "Author.findByName", query = "SELECT a FROM Author a WHERE a.name = :name"),
    @NamedQuery(name = "Author.findByEmail", query = "SELECT a FROM Author a WHERE a.email = :email")})
public class Author implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "author_id")
    private Integer authorId;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @Basic(optional = false)
    @Column(name = "email")
    private String email;

    public Author() {
    }

    public Author(Integer authorId) {
        this.authorId = authorId;
    }

    public Author(Integer authorId, String name, String email) {
        this.authorId = authorId;
        this.name = name;
        this.email = email;
    }

    public Integer getAuthorId() {
        return authorId;
    }

    public void setAuthorId(Integer authorId) {
        this.authorId = authorId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (authorId != null ? authorId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Author)) {
            return false;
        }
        Author other = (Author) object;
        if ((this.authorId == null && other.authorId != null) || (this.authorId != null && !this.authorId.equals(other.authorId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.Author[authorId=" + authorId + "]";
    }

}

Class For Book Entity..

@Entity
@Table(name = "Book")
@NamedQueries({
    @NamedQuery(name = "Book.findAll", query = "SELECT b FROM Book b"),
    @NamedQuery(name = "Book.findByBookId", query = "SELECT b FROM Book b WHERE b.bookId = :bookId"),
    @NamedQuery(name = "Book.findByName", query = "SELECT b FROM Book b WHERE b.name = :name"),
    @NamedQuery(name = "Book.findByPublisher", query = "SELECT b FROM Book b WHERE b.publisher = :publisher")})
public class Book implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "book_id")
    private Integer bookId;
    @Basic(optional = false)
    @Column(name = "name")
    private String name;
    @Basic(optional = false)
    @Column(name = "publisher")
    private String publisher;

    public Book() {
    }

    public Book(Integer bookId) {
        this.bookId = bookId;
    }

    public Book(Integer bookId, String name, String publisher) {
        this.bookId = bookId;
        this.name = name;
        this.publisher = publisher;
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPublisher() {
        return publisher;
    }

    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (bookId != null ? bookId.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Book)) {
            return false;
        }
        Book other = (Book) object;
        if ((this.bookId == null && other.bookId != null) || (this.bookId != null && !this.bookId.equals(other.bookId))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.Book[bookId=" + bookId + "]";
    }

}

Class for the join Table Author_Book

@Entity
@Table(name = "Author_Book")
@NamedQueries({
    @NamedQuery(name = "AuthorBook.findAll", query = "SELECT a FROM AuthorBook a"),
    @NamedQuery(name = "AuthorBook.findByAuthorId", query = "SELECT a FROM AuthorBook a WHERE a.authorBookPK.authorId = :authorId"),
    @NamedQuery(name = "AuthorBook.findByBookId", query = "SELECT a FROM AuthorBook a WHERE a.authorBookPK.bookId = :bookId")})
public class AuthorBook implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected AuthorBookPK authorBookPK;

    public AuthorBook() {
    }

    public AuthorBook(AuthorBookPK authorBookPK) {
        this.authorBookPK = authorBookPK;
    }

    public AuthorBook(int authorId, int bookId) {
        this.authorBookPK = new AuthorBookPK(authorId, bookId);
    }

    public AuthorBookPK getAuthorBookPK() {
        return authorBookPK;
    }

    public void setAuthorBookPK(AuthorBookPK authorBookPK) {
        this.authorBookPK = authorBookPK;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (authorBookPK != null ? authorBookPK.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof AuthorBook)) {
            return false;
        }
        AuthorBook other = (AuthorBook) object;
        if ((this.authorBookPK == null && other.authorBookPK != null) || (this.authorBookPK != null && !this.authorBookPK.equals(other.authorBookPK))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.AuthorBook[authorBookPK=" + authorBookPK + "]";
    }

}

Below we have the class that holds the primary key values of the participating tables, also generated for you by netbeans:

@Embeddable
public class AuthorBookPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "author_id")
    private int authorId;
    @Basic(optional = false)
    @Column(name = "book_id")
    private int bookId;

    public AuthorBookPK() {
    }

    public AuthorBookPK(int authorId, int bookId) {
        this.authorId = authorId;
        this.bookId = bookId;
    }

    public int getAuthorId() {
        return authorId;
    }

    public void setAuthorId(int authorId) {
        this.authorId = authorId;
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) authorId;
        hash += (int) bookId;
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof AuthorBookPK)) {
            return false;
        }
        AuthorBookPK other = (AuthorBookPK) object;
        if (this.authorId != other.authorId) {
            return false;
        }
        if (this.bookId != other.bookId) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.testing.jsf.AuthorBookPK[authorId=" + authorId + ", bookId=" + bookId + "]";
    }

}

At this point in order to persist, we require a component, service and repository (DAO) objects to do this.
For the view component, what ever is your web framework of choice, be it jsf, spring mvc, gwt or wicket, etc all you need to do is inject the service and call the respective method for saving that you have defined in your service object. the below is based on JSF.

Note: at this point you need to persist both sides of the divide at the same time (the join table entity in this case AuthorBook and anyone of the participating sides). For the AuthorBook Entity you instantiate the constructor for the join table entity class that accepts the ids of the participating table (for this example this is achieved by passing to the constructor the get method for retrieving the ids for the participating tables for the join table.) Like this

authorBookService.save(new AuthorBook(book.getBookId(), author.getAuthorId())); 

The code for this goes as follows:

@Component
@Scope("request")
public class ComponentBean implements Serializable {

    private AuthorBook authorbook = new AuthorBook();
    private Author author = new Author();
    private Book book = new Book();
    private AuthorService authorSerivce;
    private AuthorBookService authorbookSerivce;

    @Autowired
    public ComponentBean(AuthorService authorSerivce, AuthorBookService authorbookSerivce) {
        this.authorSerivce = authorSerivce;
        this.authorbookSerivce = authorbookSerivce;
    }

    public Author getAuthor() {
        return author;
    }

    public void setAuthor(Author author) {
        this.author = author;
    }
public void setAuthorbook(AuthorBook authorbook) {
        this.authorbook = authorbook;
    }
 public AuthorBook getAuthorbook() {
 return authorbook;
 }

 public void setBook(Book book) {
 this.book = book;
 }
public Book getBook() {
        return book;
    }
public void save(ActionEvent actionEvent) {
 authorService.save(author);
 authorBookService.save(new AuthorBook(book.getBookId(), author.getAuthorId())); // you instantiate the constructor for the join table entity  class and pass it the get method for retrieving the ids for the participating tables for the join table

 }
}

Service interface to define the the save operation:

public interface AuthorBookService {

public void save(AuthorBook authorBook);
}

Next the implementation for the AuthorBookService Service Interface:


@Service("authorBookService")
public AuthorBookServiceImpl implements AuthorBookService  {
private AuthorBookDAO authorbookdao;
@Autowired
public ModelServiceImpl(AuthorBookDAO authorbookdao) {
        this. authorbookdao = authorbookdao;
    }
    @Transactional
    public void save(AuthorBook authorBook) {
        authorbookdao.persist(AuthorBook authorBook);
    }
}

The Data Access object interface:

public interface AuthorBookDAO {

public void persist(AuthorBook authorBook);
}

The Data Access object implementation proper:

@Repository
public class AuthorBookDAOImpl implements ModelDAO {

    @PersistenceContext
    protected EntityManager entityMgr;

    public EntityManager getEntityMgr() {
        return entityMgr;
    }

    public void setEntityMgr(EntityManager entityMgr) {
        this.entityMgr = entityMgr;
    }

    public void persist(AuthorBook authorBook) {

      this.entityMgr.persist(authorBook)

    }
}

Note: the service and repository for Author and Book will follow the same pattern. See the my previous blog post for more hints.. Ciao for now..

Populating JSF Combo Box with Database values. (or drop down list)…

I am presently working on my AISD project, and i am using jsf(primefaces) spring and jpa to build the system. i would like to commend the efforts of the brains behind jsf 2.0 and primefaces (1.* and 2.*) :) in particular for making the life of java web devs much easier. I remember back in the days the first versions of jsf were simply nightmares, which lead my cohorts and i  to move to frameworks like wicket :) .

This blog post seeks to show how to populate a jsf Combo box with values from a database table and also you would notice that the implementation for this case includes both jsf 1.* and jsf 2.*. I assume some familiarity with spring jpa and jsf.

Most relational database records have a primary key to uniquely identify it. This key appears on other tables as foreign keys. In my application i needed to display one or more of the attributes of a record from a table on a form and persist its unique identifier .

Below i provide some sample code that gives some hint on how this can be achieved using plain old java objects..

First lets paint the screen.. For JSF 1.*:


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<head>
<p:resources />
</head>
<body>
<h:form prependId="false" styleClass="cmxform">
<fieldset>
  <legend> </legend>
<p:panel id="panel" header="Combo Box Example">
<h:panelGrid columns="2"  columnClasses="label,value" styleClass="grid">
<h:outputLabel for="cb" value="comboItem" />
<h:selectOneMenu id="selectOneCb" value="#{pageBean.model.modelid}">
<f:selectItem itemLabel="Select Model" itemValue="" />
<f:selectItems value="#{pageBean.myModelValues}" />
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</fieldset>
</h:form>
</body>
</html>

For JSF 2.* this is even easier (thanks to Çağatay Çivici the primefaces lead for pointing this out to me :) ):


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.prime.com.tr/ui">
<head>
<p:resources />
</head>
<body>
<h:form prependId="false" styleClass="cmxform">
<fieldset>
  <legend> </legend>
<p:panel id="panel" header="Combo Box Example">
<h:panelGrid columns="2"  columnClasses="label,value" styleClass="grid">
<h:outputLabel for="cb" value="comboItem" />
<h:selectOneMenu id="selectOneCb" value="#{pageBean.model.modelid}">
<f:selectItem itemLabel="Select Model" itemValue="" />
<f:selectItems value="#{pageBean.mlist}" var="model" itemLabel="#{model.modelvalue}" itemValue="#{model.modelId}"/>
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</fieldset>
</h:form>
</body>
</html>

Next lets define the backing page bean… For JSF 1.* this is ok :

@Component("pageBean")
@Scope("request")
public class PageBean implements Serializable {
private model = new Model();
private ModelService modelService;
private Map<String, String> myModelValues = new HashMap<String, String>();
private List<Model> mList;
public PageBean(){
}

 @Autowired
public PageBean(ModelService modelService){
this. modelService = modelService;
        mList = modelService.findAll();
        for (Model m : mList) {
            myModelValues.put(m.getmyModelValue(), m.getmyModelId());
     }
}
public Map<String, String> getMyModelValues() {
return myModelValues;
    }
public void setMyModelValues(Map<String, String> myModelValues) {
this.myModelValues= myModelValues;
 }
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}

For JSF 2.* it is even better => You don’t need  use a Map or Hash Map as the case may be above (thanks to Çağatay Çivici the primefaces lead for pointing this out ):

@Component("pageBean")
@Scope("request")
public class PageBean implements Serializable {
private model = new Model();
private ModelService modelService;
private List<Model> list;
public PageBean(){
}

@Autowired
public PageBean(ModelService modelService){
        this. modelService = modelService;
        list = modelService.findAll();
}

public List<Model> getList() {
	return list;
}
public Model getModel() {
return model;
}
public void setModel(Model model) {
this.model = model;
}
}

Below is a service interface to define the the findAll method:

public interface ModelService {

public List< Model> findAll();
}

Next the implementation for the Model Service Interface:


@Service("modelService")
public ModelServiceImpl implements ModelService  {
private ModelDAO modeldao;
@Autowired
public ModelServiceImpl(ModelDAO modeldao) {
        this. modeldao = modeldao;
    }
    @Transactional(readOnly = true)
    public List<Model> findAll() {
        return modeldao.findAll();
    }
}

The Data Access object interface:

public interface ModelDAO {

public List< Model> findAll();
}

The Data Access object implementation proper:

@Repository
public class ModelDAOImpl implements ModelDAO {

    @PersistenceContext
    protected EntityManager entityMgr;

    public EntityManager getEntityMgr() {
        return entityMgr;
    }

    public void setEntityMgr(EntityManager entityMgr) {
        this.entityMgr = entityMgr;
    }

    public List<Model> findAll() {
        Query query = entityMgr.createNamedQuery("Model.findAll");
        return query.getResultList();
    }
}

Finally lets define the jpa model object:

@Entity
@Table(name = "MODEL")
@NamedQuery(name = "Model.findAll", query = "SELECT m FROM Model m") // this query returns distinct values from the database.
public class Model implements Serializable {

    @Id
    @Basic(optional = false)
    @Column(name = "MODEL_ID")
    private String modelId;
    @Basic(optional = false)
    @Column(name = "MODEL_VALUE")
private String modelValue;
 public Model() {
    }
 public Model(String modelId, String modelValue) {
this.modelId = modelId;
this.model = modelValue;
}
 public String getModelId() {
        return modelId;
    }

    public void setModelId(String modelId) {
        this.modelId = modelId;
    }

    public String getModelValue() {
        return modelValue;
    }

    public void setModelValue(String modelValue) {
        this. modelValue = modelValue;
    }
    }

The code above steps through it all… Ciao for now..

Configuring Spring Security..

Over the years web application security has continued to be a critical issue. This area of concern is a major source of worry for most enterprise application developers. We as software developers, are faced with the task of securing valuable data that exist within our applications. This data could vary from  email account secured with a username / password pair or a brokerage account secured with a trading PIN, protecting an application is a important aspect of most applications, if not all.  (Walls C., 2007).

According to Craig Walls (2007, pg 248), Security is a concern that transcends an application’s functionality. For the most part, an application should play no part in securing itself. Although you could write security functionality directly into your application’s code (and that’s not uncommon), it is better to keep security concerns separate from application concerns.

One of the popular options for the enterprise java world is spring’s security framework (formerly Acegi).

Craigs Walls in his spring in action book defined spring security as  “a security framework that provides declarative security for your Spring-based applications.”

In this blog post, I intend to share my personal experience configuring spring security.

Firstly there are a few requirements (jars). you will need to define the following in your maven pom.xml file.

<dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-core</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-core-tiger</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-taglibs</artifactId>
 <version>2.0.4</version>
 </dependency>
 <dependency>
 <groupId>org.springframework.security</groupId>
 <artifactId>spring-security-acl</artifactId>
 <version>2.0.4</version>
 </dependency>
<dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjrt</artifactId>
 <version>1.5.4</version>
 </dependency>

Next task is configuring the Web.xml file:


 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 classpath:applicationContext.xml
 </param-value>
 </context-param>

 <listener>
 <listener-class> org.springframework.web.context.ContextLoaderListener</listener-class>

 </listener>

 <filter>
 <filter-name>springSecurityFilterChain</filter-name>
 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>

 <filter-mapping>
 <filter-name>springSecurityFilterChain</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

Every Spring application requires an applications context, this is a primary requirement of all spring based applications, this is a trimmed down version focusing on the topic of this blog post.

<?xml version="1.0" encoding="MacRoman"?>
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">
<context:component-scan base-package="com.example" />
<security:http auto-config='false'>
<security:intercept-url pattern="/includes/**" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/favicon.ico" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/login.jsp" filters="none"/>
<security:intercept-url pattern="/**" access="ROLE_USER" filters="none" />
<security:form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1" />
<security:concurrent-session-control max-sessions="1"/>
<security:logout logout-url="/logout" logout-success-url="/"/>
</security:http>
<security:authentication-provider>
<security:password-encoder hash="md5" />
<security:user-service>
<security:user name="ikenna" password="3d801aa532c1cec3ee82d87a99fdf63f" authorities="ROLE_USER" />
<security:user name="admin" password="21232f297a57a5a743894a0e4a801fc3" authorities="ROLE_USER" />
<security:user name="test" password="098f6bcd4621d373cade4e832627b4f6" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</beans>

Finally the login.jsp page. This page hold the form tags and should be placed in the root of the webapps foilder.

<%@page contentType="text/html" pageEncoding="MacRoman"%>
<%@ taglib prefix='c' uri='http://java.sun.com/jstl/core_rt' %>
<%@ page import="org.springframework.security.ui.AbstractProcessingFilter" %>
<%@ page import="org.springframework.security.ui.webapp.AuthenticationProcessingFilter" %>
<%@ page import="org.springframework.security.AuthenticationException" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
 <title> Login Page</title>
 <link href="<c:url value="includes/stylesheets/main.css" />" media="screen"  rel="Stylesheet" type="text/css" />
 <link href="<c:url value="includes/stylesheets/calendar.css" />" media="screen" rel="Stylesheet" type="text/css" />
 <link href="<c:url value="includes/stylesheets/forms.css" />" media="screen" rel="Stylesheet" type="text/css" />
 </head>
 <body>
 <h1>Login </h1>
<c:if test="${not empty param.login_error}">
 <font color="red">
 Your login attempt was not successful, try again.<br/><br/>
 Reason: <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.
 </font>
 </c:if><br><br>
 <form name="f" action="<c:url value='j_spring_security_check'/>" method="POST">
 <fieldset>
 <legend>Log In Form</legend> <hr>
 <ol>
 <li><label for="login">Username:</label>
 <input type='text' name='j_username' value='<c:if test="${not empty param.login_error}"><c:out value="${SPRING_SECURITY_LAST_USERNAME}"/></c:if>'/>
 </li>
 <li>
 <label for="password">Password:</label>
 <input type='password' name='j_password'/>
 </li>
 <li>
 <label for="remember_me">Remember me:</label>
 <input type="checkbox" name="_spring_security_remember_me">
 </li>
 </ol>
 <div>
 <input name="reset" type="reset" value="Reset"  onclick="return confirm('Are you sure you want to Clear or Reset this form');">
 <input name="submit" type="submit" value="Log In">
 </div>
 </fieldset>
 </form
 </div>
</body>
</html>

One thing though, I struggled with is spring security not by passing the resources (*.js, *.css, and images etc..) declared the head section of my login.jsp file.

I noticed Spring security takes into account all the resources that are declared in the *.jsp pages and will atempt to display the last resource it remembered (declared in the login.jsp page).Also modern browsers request for the favicon.ico file from the web pages, I notice spring security required me to let it know that the resources should not be a priority to it.

I would suggest copying all your *.js, *.css, and images etc.. in to one folder (includes) and then declare the folder as IS_AUTHENTICATED_ANONYMOUSLY also setting the filters off.

<security:intercept-url pattern="/includes/**" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />
<security:intercept-url pattern="/favicon.ico" access="IS_AUTHENTICATED_ANONYMOUSLY" filters="none" />

REFERENCE:
Walls C., Breidenbach R. 2007. Spring in Action Second Edition, Manning Publishers.

Dependency injection

Dependency injection is the mechanism through which the container injects the requested environmental entry to make available to the bean instance before any bean instance is invoked on that particular instance. Then the container injects these entries into bean variables or methods.

It is a form of push configuration; the container “pushes” dependencies into application objects at runtime. This is the opposite of traditional pull configuration, in which the application object “pulls” dependencies from its environment. Thus, Dependency Injection objects never load custom properties or go to a database to load configuration — the framework is wholly responsible for actually reading configuration.

Dependency Injection is based on Java language constructs, rather than the use of framework-specific interfaces. Instead of application code using framework APIs to resolve dependencies such as configuration parameters and collaborating objects, application classes expose their dependencies through methods or constructorsthat the framework can call with the appropriate values at runtime, based on configuration.

It is bean provider’s duty to tell the container that which method or variables should be injected at runtime. The bean provider can do this by using the deployment descriptor or annotations. Bean methods used for dependency injection should follow the java naming convention(JavaBeans) for properties in that they should follow the setXYZ() convention.

Consider the situations like dependency injection fails due to some reasons, the container can not make available the environmental entries due to which the bean is functioning properly, in such situations the container discards the bean instances and creates new instances.