Notas Spring Framework 1
Notas Spring Framework 1
https://www.jcombat.com/spring
What is dependency
injection?
We, as a java programmers rely on low coupling of the java components/classes. This aims at increasing
the re-usability of the components and also help in independent testing of the component. To
supplement to this feature, Spring came into picture and through its dependency injection capability, it
helped the dependencies of a class to be automatically injected to the dependent class, without the effort
of the dependent class finding or creating the same.
The prime concept behind the Dependency Injection is that a class should not be configured by itself,
rather it should be configured from outside.
To make it simple, suppose there is a class A, which has a dependency to class B. Class A uses class B
as a variable. Now when the dependency injection is applied, class B is given to the class A using two
possible approaches:
1. Constructor Injection
2. Setter Injection
However there are two other types of injections too, namely:
1. Interface Injection
2. Lookup-method Injection
Dependency Injection also known as the Inversion of Control(IoC), is the most basic thing that Spring
provides. It provides with a light weight container for Dependency Injection known as Spring core
container.
Spring core container provides all the required functionality to the Spring framework. BeanFactory is
the primary component of the Spring core container. The BeanFactory helps the core container in
creating the new objects, which are generally created as Singletons if not specified differently.
Spring actually comes with two types of containers:
1. BeanFactory interface
2. ApplicationContext interface
BeanFactory interface provides an advanced configuration mechanism and is capable of managing
objects of any nature.
ApplicationContext interface on the other hand is a sub-interface of BeanFactory (or we can say, it’s
built on top of BeanFactory, thus provides additional enterprise-centric features and functionalities than
that of the BeanFactory) and allows easier integration with Spring’s AOP feature, internationalization,
etc.
Kindly put on your queries as comments to this post. In the next post on Spring, I will be providing the
demo on various dependency injection approaches as mentioned.
Location: /WebContent/WEB-INF/
1 <?xml version="1.0" encoding="UTF-8"?>
5 <display-name>Spring-Hibernate-Mvc-Demo</display-name>
6 <welcome-file-list>
7 <welcome-file>index.jsp</welcome-file>
8 </welcome-file-list>
9 <servlet>
10 <servlet-name>dispatcher</servlet-name>
11 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
12 <load-on-startup>1</load-on-startup>
13 </servlet>
14
15 <servlet-mapping>
17 <servlet-name>dispatcher</servlet-name>
20 <url-pattern>*.obj</url-pattern>
</servlet-mapping>
</web-app>
3 <beans xmlns="http://www.springframework.org/schema/beans"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
5
xmlns:mvc="http://www.springframework.org/schema/mvc"
6
xsi:schemaLocation="http://www.springframework.org/schema/beans
7
http://www.springframework.org/schema/beans/spring-
8 beans-3.0.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-
context-3.0.xsd
11
http://www.springframework.org/schema/mvc
12
http://www.springframework.org/schema/mvc/spring-
13 mvc-3.0.xsd">
14
21 <!-- Configuration for View page resolver.here we are configuring for jsp pages -->
26 </bean>
27
28 <!-- configuration to load properties file from classpath i.e src folder -->
29 <!-- the properties file contains key-value pairs.The keys are used in this xml to -->
31 <context:property-placeholder location="classpath:jdbcConfig.properties"/>
32
33 <!-- DataSource configuration of database coming from the property file -->
39 </bean>
40
42 <bean id="sessionFactory"
43 class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
45 <property name="annotatedClasses">
46 <list>
47 <value>com.jCombat.bean.UserBean</value>
48 <!-- all the hibernate annotated bean should have entry here -->
49 </list>
50 </property>
51 <property name="hibernateProperties">
52 <props>
53 <prop key="hibernate.dialect">${hib.dialect}</prop>
54 <prop key="hibernate.hbm2ddl.auto">false</prop>
56 <!-- below two properties will show you formatted sql query on console -->
57 <prop key="hibernate.show_sql">${hib.showSql}</prop>
58 <prop key="hibernate.format_sql">${hib.showSql}</prop>
59 <prop key="hibernate.connection.release_mode">auto</prop>
60 <prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
61 </props>
62 </property>
63 </bean>
64
68 </bean>
69
70 <!-- configuration for resource bundle where spring-validation messages are resolved -->
71 <bean id="messageSource"
72 class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
75 </bean>
76
78 <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
79 <property name="exceptionMappings">
80 <props>
81 <prop key="java.lang.Exception">exception</prop>
83 </props>
84 </property>
</beans>
jdbcConfig.properties
Location: /src/
Make sure you have the proper property file entries as:
1 jdbc.driverClass=oracle.jdbc.driver.OracleDriver
3 jdbc.url=jdbc:oracle:thin:@localhost:1521:xe
4 jdbc.userName=yourUsername
5 jdbc.password=yourPassword
7 hib.dialect=org.hibernate.dialect.Oracle10gDialect
8 hib.showSql=true
These are the key values used in datasource configuration in dispatcher-servlet.xml file.
The views i.e. index.jsp, login.jsp and welcome.jsp remains the same as for our previous
application. Click here for instant navigation
Now let’s start with creating the Java classes. We would prefer going for the bean first
i.e. UserBean.java inside the package com.jCombat.bean.
1 package com.jCombat.bean;
3 import java.io.Serializable;
4 import javax.persistence.Column;
5 import javax.persistence.Entity;
6 import javax.persistence.Id;
7 import javax.persistence.Table;
8 import org.hibernate.validator.constraints.NotEmpty;
13
15
16 //spring validation
17 @NotEmpty
18 @Id
21 @NotEmpty
24
26 return userId;
27 }
29 this.userId = userId;
30 }
32 return password;
33 }
35 this.password = password;
36 }
37
38 }
3 import com.jCombat.bean.UserBean;
9}
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.orm.hibernate3.HibernateTemplate;
5 import org.springframework.stereotype.Component;
6 import com.jCombat.bean.UserBean;
8 @Component
10
11 @Autowired
13
15 this.hibernateTemplate = hibernateTemplate;
16 }
17
19 return hibernateTemplate;
20 }
21
24
27 */
29 if(userInDb!=null){
30 if(userBean.getPassword().endsWith(userInDb.getPassword())){
31 userExists = true;
32 }
33 }
34 return userExists;
35 }
36
37 }
3 import com.jCombat.bean.UserBean;
9}
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.stereotype.Component;
6 import com.jCombat.bean.UserBean;
7 import com.jCombat.dao.ICombatDAO;
9 @Component
11
12 @Autowired
14
16 this.combatDAO = combatDAO;
17 }
20 }
21
23 return combatDAO.authenticateUser(userBean);
24 }
25 }
3 import javax.validation.Valid;
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.stereotype.Controller;
6 import org.springframework.ui.Model;
7 import org.springframework.validation.BindingResult;
8 import org.springframework.validation.ObjectError;
9 import org.springframework.web.bind.annotation.ModelAttribute;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.servlet.ModelAndView;
12 import com.jCombat.bean.UserBean;
13 import com.jCombat.service.ICombatService;
14
15 @Controller
17
18 @Autowired
20
22 this.combatService = combatService;
23 }
24
27 }
28
29 @RequestMapping("toLogin")
36 return "login";
37 }
38
39 @RequestMapping("doLogin")
42 //if input bean does not have validation error then proceed
43 if(!result.hasFieldErrors()){
46 if(!combatService.authenticateUser(userBean)){
48 }
49 else{
50 view.setViewName("welcome");
51 }
52 }
53 return view;
54 }
55 }
This was all, but do make sure that the following points have been taken care of to avoid unexpected
errors:
1. Make sure you have created table “userbean” in the database with two columns “userid” and
“password” of type varchar2 and provide some values in it.
2. Before executing this project, do make sure the database engine is running otherwise you will get
connection errors.
Now you can execute your project by right-clicking your project in Eclipse and choose Run as->Run on
server
I hope this post was fair enough. Do comment for your queries and feedback on the same.
2. Setup web.xml
Next task is to configure the first entry point of a web application, i.e web.xml.
web.xml
Location: /WebContent/WEB-INF/
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
6 app_2_5.xsd"
7 id="WebApp_ID" version="2.5">
8 <display-name>SpringWithJdbcTemplate</display-name>
9
10 <welcome-file-list>
11 <welcome-file>index.jsp</welcome-file>
12 </welcome-file-list>
13
14 <servlet>
15 <servlet-name>mvc-dispatcher</servlet-name>
16 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
17 <load-on-startup>1</load-on-startup>
18 </servlet>
19
20 <servlet-mapping>
21 <servlet-name>mvc-dispatcher</servlet-name>
22 <!-- only url's with extension mentioned in following url-pattern will
23 be directed to spring controller -->
24 <url-pattern>*.obj</url-pattern>
25 </servlet-mapping>
</web-app>
4. Create Views
Create the view pages, index.jsp, login.jsp and welcome.jsp inside the webapp directory.
index.jsp
1 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
2 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3 pageEncoding="ISO-8859-1"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8 <title>Spring Mvc Login Demo</title>
9 <link href="style.css" rel="stylesheet" type="text/css" />
10 </head>
11 <body>
12 <div class="content">
13 <fieldset>
14 <legend>Navigation menu</legend>
15 <!-- Here the href's value will be used to decide the method from
16 controller to be executed on click of this link -->
17 <a href="toLogin.obj" style="margin:50;">Login</a>
18 </fieldset>
19 </div>
20 </body>
21 </html>
login.jsp
1 <%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
2 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3 pageEncoding="ISO-8859-1"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
8 <title>Login page</title>
9 <link href="style.css" rel="stylesheet" type="text/css" />
10 </head>
11 <body>
12 <div class="content">
13 <fieldset>
14 <legend>Navigation menu</legend>
15 <a href="index.jsp">Home</a>
16 <!-- here the action's value will be used to map the corresponding
17 method in controller needs to be executed on form submit.
18 modelAttribute value should be camelCase name of bean
19 added earlier as model in spring controller
20 -->
21 <sf:form action="doLogin.obj" modelAttribute="userBean">
22 <!-- to display error message from action method if any -->
23 <sf:errors />
24 <br />
25 <sf:label path="userId">UserName:</sf:label>
26 <sf:input path="userId" />
27 <br />
28 <!-- to display validation error message if any -->
29 <sf:errors path="userId" />
30 <br />
31 <sf:label path="password">Password:</sf:label>
32 <sf:password path="password" />
33 <br />
34 <sf:errors path="password" />
35 <br />
36 <input type="submit" value="Login" /><br />"
37 </sf:form>
38 </fieldset>
39 </div>
40 </body>
41 </html>
welcome.jsp
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
2 pageEncoding="ISO-8859-1"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
7 <title>User Home Page</title>
8 <link href="style.css" rel="stylesheet" type="text/css" />
9 </head>
10 <body>
11 <div class="content">
12 <fieldset>
13 <legend>Navigation menu</legend>
14 <a href="index.jsp">Home</a>
15 <br /><br />
16 <h2>User page</h2>
17 <br/>
18 <!-- display the userId just logged in -->
19 Welcome ${userBean.userId }
20 </fieldset>
21 </div>
22 </body>
23 </html>
1. Make sure you have created table “login” in the database with two columns “uname” and
“password” of type varchar2 and provide some values in it.
2. Before executing this project, do make sure the database engine is running otherwise you will get
connection errors.
7. Project Execution
Now you can execute your project by right-clicking your project in Eclipse and choose Run as->Run on
server.
Below are the browser window snapshots when the application is run and we do a basic navigation.