0% found this document useful (0 votes)
49 views

Notas Spring Framework 1

Dependency injection is a core feature of Spring that allows classes to have their dependencies automatically injected without having to configure them directly. Spring provides a lightweight container that handles dependency injection through the BeanFactory interface. The BeanFactory helps create singleton objects and manage dependencies. ApplicationContext is a sub-interface of BeanFactory that provides additional enterprise features like AOP integration. This document provides an overview of dependency injection in Spring and how to integrate Spring with Hibernate using the HibernateTemplate.

Uploaded by

Ariel Cupertino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Notas Spring Framework 1

Dependency injection is a core feature of Spring that allows classes to have their dependencies automatically injected without having to configure them directly. Spring provides a lightweight container that handles dependency injection through the BeanFactory interface. The BeanFactory helps create singleton objects and manage dependencies. ApplicationContext is a sub-interface of BeanFactory that provides additional enterprise features like AOP integration. This document provides an overview of dependency injection in Spring and how to integrate Spring with Hibernate using the HibernateTemplate.

Uploaded by

Ariel Cupertino
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Notas Spring Framework

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.

Spring integration with


hibernate
Almost similar to what we have done in our previous article on a login application in Spring using JDBC
template. To demonstrate the Spring integration with Hibernate, we will instead be
using HibernateTemplate.
Quickly moving ahead with the application, lets configure the web.xml first
web.xml

Location: /WebContent/WEB-INF/
1 <?xml version="1.0" encoding="UTF-8"?>

2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"


xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
3
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
4 id="WebApp_ID" version="2.5">

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>

16 <!-- make sure servlet-name is same as in <servlet> configuration -->

17 <servlet-name>dispatcher</servlet-name>

18 <!-- only url's with extension mentioned in following url-pattern

19 will be directed to spring controller -->

20 <url-pattern>*.obj</url-pattern>

</servlet-mapping>

</web-app>

Next, let’s configure the dispatcher-servlet.xml


dispatcher-servlet.xml
Location: /WebContent/WEB-INF/
1 <?xml version="1.0" encoding="UTF-8"?>

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

15 <!-- declare mvc to be annotation driven -->


16 <mvc:annotation-driven/>
17 <context:annotation-config />
18 <!-- provide Your Base package to scan annotations for components -->
19 <context:component-scan base-package="com.jCombat" />
20

21 <!-- Configuration for View page resolver.here we are configuring for jsp pages -->

22 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">

23 <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />

24 <property name="prefix" value="/" />

25 <property name="suffix" value=".jsp" />

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 -->

30 <!-- to configure various configuration constants. used as ${key} -->

31 <context:property-placeholder location="classpath:jdbcConfig.properties"/>

32

33 <!-- DataSource configuration of database coming from the property file -->

34 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

35 <property name="driverClassName" value="${jdbc.driverClass}" />

36 <property name="url" value="${jdbc.url}" />

37 <property name="username" value="${jdbc.userName}" />

38 <property name="password" value="${jdbc.password}" />

39 </bean>

40

41 <!-- Hibernate configuration of database and annotated bean-->

42 <bean id="sessionFactory"

43 class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

44 <property name="dataSource" ref="dataSource" />

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>

55 <!-- only above two property configuration is enough -->

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

65 <!-- configuration for HibernateTemplate we will use in DAO -->

66 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">

67 <property name="sessionFactory" ref="sessionFactory"/>

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">

73 <!-- will resolve to /WEB_INF/messages.properties file-->

74 <property name="basename" value="/WEB-INF/messages" />

75 </bean>

76

77 <!-- Exception Mapping -->

78 <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

79 <property name="exceptionMappings">

80 <props>

81 <prop key="java.lang.Exception">exception</prop>

82 <!-- all the exceptions will be directed to exception.jsp -->

83 </props>

84 </property>

85 <property name="defaultErrorView" value="exception"/>


86 </bean>

</beans>

jdbcConfig.properties
Location: /src/
Make sure you have the proper property file entries as:

1 jdbc.driverClass=oracle.jdbc.driver.OracleDriver

2 #provide url configuration

3 jdbc.url=jdbc:oracle:thin:@localhost:1521:xe

4 jdbc.userName=yourUsername

5 jdbc.password=yourPassword

6 #dialect for oracle

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;

10 @Entity //hibernate mapping configuration

11 @Table(name="UserBean") //hibernate table configuration

12 public class UserBean implements Serializable{

13

14 private static final long serialVersionUID = 4657462015039726030L;

15

16 //spring validation
17 @NotEmpty

18 @Id

19 @Column(name="userId") //hibernate column configuration

20 private String userId;

21 @NotEmpty

22 @Column(name="password")//hibernate column configuration

23 private String password;

24

25 public String getUserId() {

26 return userId;

27 }

28 public void setUserId(String userId) {

29 this.userId = userId;

30 }

31 public String getPassword() {

32 return password;

33 }

34 public void setPassword(String password) {

35 this.password = password;

36 }

37

38 }

Create the DAO interface as ICombatDAO.java in package com.jCombat.dao as:


1 package com.jCombat.dao;

3 import com.jCombat.bean.UserBean;

5 public interface ICombatDAO {

7 public abstract boolean authenticateUser(UserBean userBean);

9}

Create the DAO class as CombatDAO.java in the package com.jCombat.dao


1 package com.jCombat.dao;

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

9 public class CombatDAO implements ICombatDAO {

10

11 @Autowired

12 private HibernateTemplate hibernateTemplate;

13

14 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

15 this.hibernateTemplate = hibernateTemplate;

16 }

17

18 public HibernateTemplate getHibernateTemplate() {

19 return hibernateTemplate;

20 }

21

22 public boolean authenticateUser(UserBean userBean){

23 boolean userExists = false;

24

25 /* the arguments in hibernate.get are the class that is mapped

26 * and the primary key to find

27 */

28 UserBean userInDb = hibernateTemplate.get(UserBean.class, userBean.getUserId());

29 if(userInDb!=null){

30 if(userBean.getPassword().endsWith(userInDb.getPassword())){

31 userExists = true;

32 }

33 }
34 return userExists;

35 }

36

37 }

Create service interface as ICombatService.java in package com.jCombat.service, as:


1 package com.jCombat.service;

3 import com.jCombat.bean.UserBean;

5 public interface ICombatService {

7 public abstract boolean authenticateUser(UserBean userBean);

9}

Create service class as CombatService.java in package com.jCombat.service, as:


1 package com.jCombat.service;

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

10 public class CombatService implements ICombatService {

11

12 @Autowired

13 private ICombatDAO combatDAO;

14

15 public void setCombatDAO(ICombatDAO combatDAO) {

16 this.combatDAO = combatDAO;

17 }

18 public ICombatDAO getCombatDAO() {


19 return combatDAO;

20 }

21

22 public boolean authenticateUser(UserBean userBean){

23 return combatDAO.authenticateUser(userBean);

24 }

25 }

Finally let’s create the controller class as CombatController.java in


package com.jCombat.controller as:
1 package com.jCombat.controller;

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

16 public class CombatController {

17

18 @Autowired

19 private ICombatService combatService;

20

21 public void setCombatService(ICombatService combatService) {

22 this.combatService = combatService;

23 }

24

25 public ICombatService getCombatService() {


26 return combatService;

27 }

28

29 @RequestMapping("toLogin")

30 public String toLogin(Model model){

31 //make sure to add model of UserBean in which login

32 //userName and password will be stored from the login-form

33 model.addAttribute("userBean", new UserBean());

34 //"login" will be resolved to login.jsp

35 //where login-form is presented to user

36 return "login";

37 }

38

39 @RequestMapping("doLogin")

40 public ModelAndView doLogin(@ModelAttribute @Valid UserBean userBean,BindingResult result){

41 ModelAndView view = new ModelAndView("login");

42 //if input bean does not have validation error then proceed

43 if(!result.hasFieldErrors()){

44 //if not a valid user then add error

45 //else proceed to user welcome page

46 if(!combatService.authenticateUser(userBean)){

47 result.addError(new ObjectError("err", "Invalid Credentials"));

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.

Spring MVC based login


application using JDBC
template
In this tutorial, we will create a simple login application using Spring MVC, in which we will be getting
familiar to the basic Spring MVC application flow, the MVC based layered architecture with Spring and
the interaction with database using Jdbc template. We will also understand the
usage of @ModelAttribute and bean validation with the Validator API.
1. Maven Dependencies
Quickly moving ahead with the application, let’s first configure the dependencies in pom.xml file of our
application.
pom.xml
1 <!-- JUnit dependencies -->
2 <dependency>
3 <groupId>junit</groupId>
4 <artifactId>junit</artifactId>
5 <version>3.8.1</version>
6 <scope>test</scope>
7 </dependency>
8
9 <!-- Spring dependencies -->
10 <dependency>
11 <groupId>org.springframework</groupId>
12 <artifactId>spring-core</artifactId>
13 <version>4.0.0.RELEASE</version>
14 </dependency>
15
16 <dependency>
17 <groupId>org.springframework</groupId>
18 <artifactId>spring-web</artifactId>
19 <version>4.0.0.RELEASE</version>
20 </dependency>
21
22 <dependency>
23 <groupId>org.springframework</groupId>
24 <artifactId>spring-webmvc</artifactId>
25 <version>4.0.0.RELEASE</version>
26 </dependency>
27
28 <dependency>
29 <groupId>org.springframework</groupId>
30 <artifactId>spring-jdbc</artifactId>
31 <version>4.0.0.RELEASE</version>
32 </dependency>
33
34 <!-- DB Connection Pooling -->
35 <dependency>
36 <groupId>org.apache.commons</groupId>
37 <artifactId>commons-dbcp2</artifactId>
38 <version>2.0</version>
39 </dependency>
40
41 <dependency>
42 <groupId>commons-dbcp</groupId>
43 <artifactId>commons-dbcp</artifactId>
44 <version>1.2.2</version>
45 </dependency>
46
47 <!-- MySQL Connector -->
48 <dependency>
49 <groupId>mysql</groupId>
50 <artifactId>mysql-connector-java</artifactId>
51 <version>5.1.30</version>
52 </dependency>
53
54 <!-- JSTL Dependency -->
55 <dependency>
56 <groupId>jstl</groupId>
57 <artifactId>jstl</artifactId>
58 <version>1.2</version>
59 </dependency>
60
61 <dependency>
62 <groupId>javax.servlet</groupId>
63 <artifactId>jstl</artifactId>
64 <version>1.2</version>
65 </dependency>
66
67 <!-- Validation API -->
68 <dependency>
69 <groupId>javax.validation</groupId>
70 <artifactId>validation-api</artifactId>
71 <version>1.1.0.Final</version>
72 </dependency>
73
74 <!-- Validation API provider -->
75 <dependency>
76 <groupId>org.hibernate</groupId>
77 <artifactId>hibernate-validator</artifactId>
78 <version>5.2.2.Final</version>
79 </dependency>

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>

3. Setup Dispatcher Servlet context xml


Create and configure the mvc-dispatcher-servlet.xml that will have all the configuration beans
needed to handle the user requests.
This file contains spring-related configuration. The name dispatcher-servlet.xml comes
from <servlet-name> configured in web.xml suffixed with “-servlet.xml”. Also, make sure to add
namespace and schema location for MVC context.
mvc-dispatcher-servlet.xml
Location: /WebContent/WEB-INF/
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:context="http://www.springframework.org/schema/context"
4 xmlns:mvc="http://www.springframework.org/schema/mvc"
5 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-
11 context-3.0.xsd
12 http://www.springframework.org/schema/mvc
13 http://www.springframework.org/schema/mvc/spring-
14 mvc-3.0.xsd">
15
16 <!-- declare mvc to be annotation driven -->
17 <mvc:annotation-driven />
18 <context:annotation-config />
19
20 <!-- provide Your Base package to scan annotations for components -->
21 <context:component-scan base-package="com.jcombat" />
22
23 <!-- Configuration for View page resolver.here we are using jsp pages -->
24 <bean id="viewResolver"
25 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
26 <property name="viewClass">
27 <value>org.springframework.web.servlet.view.JstlView</value>
28 </property>
29 <property name="prefix">
30 <value>/</value>
31 </property>
32 <property name="suffix">
33 <value>.jsp</value>
34 </property>
35 </bean>
36
37 <bean id="combatService" class="com.jcombat.service.CombatService" />
38 <bean id="combatDAO" class="com.jcombat.dao.CombatDAO" />
39
40 <!-- DataSource configuration of database -->
41 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
42 destroy-method="close">
43 <property name="driverClassName" value="com.mysql.jdbc.Driver" />
44 <property name="url" value="jdbc:mysql://localhost:3306/sample_db" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>

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>

4. Create Java Entities


Now let’s start with creating the Java entity classes UserBean.java inside the
package com.jCombat.bean.
UserBean.java
1 package com.jcombat.bean;
2
3 import org.hibernate.validator.constraints.NotEmpty;
4
5 public class UserBean {
6
7 @NotEmpty(message="UserId cannot be empty")
8 private String userId;
9 @NotEmpty(message="Password cannot be empty")
10 private String password;
11
12 public String getUserId() {
13 return userId;
14 }
15
16 public void setUserId(String userId) {
17 this.userId = userId;
18 }
19
20 public String getPassword() {
21 return password;
22 }
23
24 public void setPassword(String password) {
25 this.password = password;
26 }
27 }

5. Creating DAO and Service layer classes


Create the DAO interface as ICombatDAO.java under the package com.jcombat.dao as –
1 package com.jcombat.dao;
2
3 import javax.sql.DataSource;
4 import com.jcombat.bean.UserBean;
5
6 public interface ICombatDAO {
7 public abstract void setDataSource(DataSource dataSource);
8 public abstract boolean authenticateUser(UserBean userBean);
9 }
Create the DAO class as CombatDAO.java in the package com.jcombat.dao as –
1 package com.jcombat.dao;
2 import javax.sql.DataSource;
3
4 import org.springframework.beans.factory.annotation.Autowired;
5 import org.springframework.jdbc.core.JdbcTemplate;
6
7 import com.jcombat.bean.UserBean;
8
9 public class CombatDAO implements ICombatDAO {
10
11 private JdbcTemplate jdbcTemplate;
12
13 @Autowired
14 public void setDataSource(DataSource dataSource) {
15 this.jdbcTemplate = new JdbcTemplate(dataSource);
16 }
17
18 @SuppressWarnings("deprecation")
19 public boolean authenticateUser(UserBean userBean){
20 boolean userExists = false;
21 int rowcount = jdbcTemplate.queryForInt("select count(*) from login " +
22 " where uname = ? and password = ?",
23 userBean.getUserId(),userBean.getPassword());
24 if(rowcount==1){
25 userExists = true;
26 }
27 return userExists;
28 }
29 }
In the above snippet, note that setter injection of the dataSource property happens via autowiring by
Type.
Note that there is only one bean of the type DataSource defined in the dispatcher-servlet.xml. Had
there been more than one matching beans by Type, there would have been a Type conflict
while autowiring. The spring container in that case would have switched to try autowiring by
Name. Still if the autowired-property-variable-name do not make a match any that of the bean ids
defined (via XML configuration) or Component/Qualifier names specified (via Annotations),
autowiring would have failed then-and-there, with a nice exception thrown. We will be exploring
more on the @Qualifier annotation soon some time later.
Similarly create service interface as ICombatService.java in package com.jCombat.service, as –
ICombatService.java
1 package com.jcombat.service;
2
3 import com.jcombat.bean.UserBean;
4
5 public interface ICombatService {
6 public abstract boolean authenticateUser(UserBean userBean);
7 }
Create service class as CombatService.java in package com.jCombat.service, as –
CombatService.java
1 package com.jcombat.service;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4
5 import com.jcombat.bean.UserBean;
6 import com.jcombat.dao.ICombatDAO;
7
8 public class CombatService implements ICombatService {
9
10 @Autowired
11 private ICombatDAO combatDAO;
12
13 public boolean authenticateUser(UserBean userBean){
14 return combatDAO.authenticateUser(userBean);
15 }
16 }
Likewise, in the above snippet too, field based injection of combatDAO happens via autowiring by
Type. There is only one component we have defined of the type ICombatDAO. Hence, there are no Type
conflicts (since there is one and only one component of the type ICombatDAO defined), hence
the CombatDAO implementation-object-reference injects itself to the @Autowired combatDAO property
of the above CombatService.java class.
6. Create the application Controller
Finally let’s create the controller class as CombatController.java in the
package com.jCombat.controller.
CombatController.java
1 package com.jcombat.controller;
2
3 import javax.validation.Valid;
4
5 import org.springframework.beans.factory.annotation.Autowired;
6 import org.springframework.stereotype.Controller;
7 import org.springframework.ui.Model;
8 import org.springframework.validation.BindingResult;
9 import org.springframework.validation.ObjectError;
10 import org.springframework.web.bind.annotation.ModelAttribute;
11 import org.springframework.web.bind.annotation.RequestMapping;
12 import org.springframework.web.servlet.ModelAndView;
13
14 import com.jcombat.bean.UserBean;
15 import com.jcombat.service.ICombatService;
16
17 @Controller
18 public class DemoController {
19
20 @Autowired
21 private ICombatService combatService;
22
23 @RequestMapping("toLogin")
24 public String toLogin(Model model) {
25 // Make sure to add model of UserBean in which login
26 // userName and password will be stored from the login form
27 model.addAttribute("userBean", new UserBean());
28 // "login" will be resolved to login.jsp
29 // where login-form is presented to user
30 return "login";
31 }
32
33 @RequestMapping("doLogin")
34 public ModelAndView doLogin(@ModelAttribute @Valid UserBean userBean,BindingResult result) {
35 ModelAndView view = new ModelAndView("login");
36 // If input bean does not have any validation error then proceed
37 if(!result.hasFieldErrors()) {
38 // If not a valid user then add error
39 // else proceed to user welcome page
40 if(!combatService.authenticateUser(userBean)) {
41 result.addError(new ObjectError("err", "Invalid Credentials"));
42 } else {
43 view.setViewName("welcome");
44 }
45 }
46 return view;
47 }
48 }
If we don’t specify the component-scan element in application context (dispatcher-servlet.xml),
we would then need to define the beans in the context XML (dispatcher-servlet.xml) before we
would have been able to autowire them. Since we are using the component-scan in our application
here, we didn’t have to specify the bean for each of the classes, except for the DataSource, which
references the class from the Apache API.

Important points while trying out this demo


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 “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.

7.1 Landing page

7.2 Login page


Clicking on the login link, the application navigates to the login page as shown below –

7.3 Check validation


Click on the login button without entering anything into any of the textboxes. We get an error message
as –
Enter any wrong credentials and click on the login button, we get an error message as shown below –

7.4 Successful login


Now login with the correct credentials (username – test and password – 123), we get logged-in
successfully to the user page as shown below –

You might also like