Nearby lessons

30 of 35

Spring - Web MVC with Tiles

📌 What You Will Learn
  • Understand Spring - Web MVC with Tiles
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Spring - Web MVC with Tiles step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Spring WEB MVC with Tiles Integration

In general, in web applications, we have to organize the web pages in a standard mode inorder to improve Look and Feel.

To manage all the web pages in standard manner we have to use templates.

In general, we will use the following templates to prepare web pages in web applications. To manage all the web pages in the above provided templates and to manage flow of execution between all the web pages we have to use a Apache provided Tiles framework.

Apache Software Foundations has provided the complete Tiles Framework in the form of the following JAR files.

 tiles-api-2.2.2.jar  tiles-core-2.2.2.jar  tiles-jsp-2.2.2.jar  tiles-servlet-2.2.2.jar  tiles-template-2.2.2.jar

If we want to use Tiles Framework in our web applications then we have to provide the above Jar files in web application lib folder.

The web frameworks like Struts, JSF, Xwork2 .... are using already Tiles Framework to prepare web applications.

Spring web MVC framework is also providing in built support for Tiles Framework Integration inorder to prepare web applications.

If we want to use Tiles Framework in Spring web MVC applications then we have to use the following steps.

  • Prepare Template page by using Tiles tags.
  • Prepare Tiles pages.
  • Prepare Tiles definitions.
  • Prepare Controller class.

Prepare Template page by using Tiles tags

The main intention of Template page is to define a standard template for web pages.

To prepare Template pages we have to use the following Tiles tag library which is available with the URI "http://tiles.apache.org/tags-tiles".

<tiles:insertAttribute name="--"/>

This tag can be used to define tiles logical names in Template. Where "name" attribute will take logical name of the tile in Template.

Example02
JCode Cell
1 
2<%@taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
3<html>
4<body>
5<table width="100%" height="100%">
6<tr height="20%">
7<td colspan="2" align="center">
8 <tiles:insertAttribute name="header"/>
9</td>
10</tr>
11<tr height="60%">
12<td width="20%">
13<tiles:insertAttribute name="menu"/>
14</td>
15<td width="80%">
16<tiles:insertAttribute name="body"/>
17</td>
18</tr>
19<tr height="15%">
20<td colspan="2" align="center">
21<tiles:insertAttribute name="footer"/>
22</td>
23</tr>
24</table>
25</body>
26</html>
27

Prepare Tiles pages — header.jsp

In Tiles based web applications, Tile is a JSP page it able to represent Header, Footer, Menu, Body,.....

EX:

Example03
JCode Cell
1 
2<html>
3<body>
4<h1 style="color: white;">DURGA SOFTWARE SOLUTIONS</h1>
5</body>
6</html>
7

Prepare Tiles pages — menu.jsp

Example04
JCode Cell
1 
2<html>
3<body>
4<br>
5<h3>
6<a href="add">Add Student</a><br><br>
7<a href="search">Search Student</a><br><br>
8<a href="delete">Delete Student</a>
9</h3>
10</body>
11</html>
12

Prepare Tiles definitions — tiles-defs.xml

The main intention of Tiles Definitions is to define the cobination of tiles pages in the form of Definitions.

In Tiles based web applications, we have to define all tiles definitions in an xml file by using the following xml tags.

<!DOCTYPE ----- > <tiles-definitions>
<definition name="--" template="--"> <put-attribute name="--" value="--"/> ------
</definition> ------ </tiles-definitions>

 Where <tiles-definitions> is root tags, it will include no of definitions.  Where <definition> tag is able to provide single definition which includes tiles pages.  Where "name" attribute in <definition> tag will take definition name.  Where "template" attribute in <definition> tag will take the name and location of the layout

page  Where <put-attribute> tag will assign tile JSP page to the respective logical name of the tile

in JSP page.  Where "name" in <put-attribute> will take logical name of the tile.  Where "value" attribute will take the name and location of the tile JSP page.

In Tiles definitions file, we are able to extend one definition to another definition by using "extends" attribute inorder to reuse tiles configurations and we are able to override one tile configuration to another tiles configuration just like normal inheritance and method overridding. Note: We are able to get DOCTYPE definition in tiles definitions file by using the following dtd file from tiles-core-2.2.2.jar.

org\apache\tiles\resources\tiles-config_2_1.dtd

EX:

Example05
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3 
4<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
5"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
6 
7<tiles-definitions>
8<definition name="welcomeDef" template="/WEB-INF/layout.jsp">
9 <put-attribute name="header" value="/WEB-INF/header.jsp"/>
10 <put-attribute name="menu" value="/WEB-INF/menu.jsp"/>
11<put-attribute name="body" value="/WEB-INF/welcome.jsp"/>
12<put-attribute name="footer" value="/WEB-INF/footer.jsp"/>
13</definition>
14<definition name="addDef" extends="welcomeDef">
15<put-attribute name="body" value="/WEB-INF/addstudent.jsp"/>
16</definition>
17<definition name="searchDef" extends="welcomeDef">
18<put-attribute name="body" value="/WEB-INF/searchstudent.jsp"/>
19</definition>
20<definition name="deleteDef" extends="welcomeDef">
21<put-attribute name="body" value="/WEB-INF/deletestudent.jsp"/>
22</definition>
23<definition name="statusDef" extends="welcomeDef">
24<put-attribute name="body" value="/WEB-INF/status.jsp"/>
25</definition>
26</tiles-definitions>
27

Prepare Tiles definitions — StudentController.java

  • Prepare Controller class.

In Tiles based applications, we will prepare Controller classes as like normal Controller classes , but, the respective Business methods must return tiles definitions logical name only instead of jsp pages names.

EX:

Example06
JCode Cell
1 
2@Controller
3public class StudentController {
4 
5@RequestMapping(value="/welcome", method=RequestMethod.GET)
6public String welcome() {
7 return "welcomeDef";
8}
9 
10@RequestMapping(value="/add", method=RequestMethod.GET)
11public ModelAndView addStudent() {
12return new ModelAndView("addDef", "student", new Student());
13}
14 
15@RequestMapping(value="/search", method=RequestMethod.GET)
16public ModelAndView searchStudent() {
17return new ModelAndView("searchDef", "student", new Student());
18}
19 
20@RequestMapping(value="/delete", method=RequestMethod.GET)
21public ModelAndView deleteStudent() {
22return new ModelAndView("deleteDef", "student", new Student());
23}
24 
25@RequestMapping(value="/add", method=RequestMethod.POST)
26public ModelAndView add(Student student) {
27String status = studentService.addStudent(student);
28return new ModelAndView("statusDef", "status", status);
29}
30 
31@RequestMapping(value="/search", method=RequestMethod.POST)
32public ModelAndView search(Student student) {
33Student std = studentService.searchStudent(student.getSid());
34if(std == null) {
35 return new ModelAndView("statusDef", "status", "Student Not Existed");
36}else {
37 return new ModelAndView("studentDetailsDef", "student", std);
38}
39}
40@RequestMapping(value="/delete", method=RequestMethod.POST)
41public ModelAndView delete(Student student) {
42String status = studentService.deleteStudent(student.getSid());
43return new ModelAndView("statusDef", "status", status);
44}
45}
46

Prepare Spring Configuration File — ds-servlet.xml

In Spring configuration file we have to provide the following configuration details.

  • UrlBasedViewResolver with TilesView class.
  • TilesConfigurer with "definitions" property of list type with tiles definitions xml file.

EX:

Example07
JCode Cell
1 
2<beans>
3 -----
4<bean id="viewResolver"
5 class="org.springframework.web.servlet.view.UrlBasedViewResolver">
6 <property name="viewClass">
7 <value>
8 org.springframework.web.servlet.view.tiles2.TilesView
9 </value>
10 </property>
11</bean>
12 
13<bean id="tilesConfigurer"
14class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
15<property name="definitions">
16 <list>
17 <value>/WEB-INF/tiles-defs.xml</value>
18 </list>
19</property>
20</bean>
21------
22</beans>
23

Prepare Spring Configuration File — index.jsp

Example:

Example08
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<jsp:forward page="welcome"/>
12</body>
13</html>
14

Prepare Spring Configuration File — layout.jsp

Example09
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4 
5<%@taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
6<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
7<html>
8<head>
9<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
10<title>Insert title here</title>
11</head>
12<body>
13<table width="100%" height="550">
14<tr height="20%">
15<td colspan="2" align="center" bgcolor="maroon">
16<tiles:insertAttribute name="header"/>
17</td>
18</tr>
19<tr height="60%">
20<td width="20%" bgcolor="lightyellow">
21<tiles:insertAttribute name="menu"/>
22</td>
23<td width="80%" bgcolor="lightblue">
24<tiles:insertAttribute name="body"/>
25</td>
26</tr>
27<tr height="15%">
28<td colspan="2" align="center" bgcolor="blue">
29<tiles:insertAttribute name="footer"/>
30</td>
31</tr>
32</table>
33</body>
34</html>
35

Prepare Spring Configuration File — header.jsp

Example10
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<h1 style="color: white;">DURGA SOFTWARE SOLUTIONS</h1>
12</body>
13</html>
14

Prepare Spring Configuration File — menu.jsp

Example11
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<br>
12<h3>
13<a href="add">Add Student</a><br><br>
14<a href="search">Search Student</a><br><br>
15<a href="delete">Delete Student</a>
16</h3>
17</body>
18</html>
19

Prepare Spring Configuration File — welcome.jsp

Example12
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<br><br><br>
12<h1 style="color: red;">
13<marquee>
14Welcome To Durga Software Solutions
15</marquee>
16</h1>
17</body>
18</html>
19

Prepare Spring Configuration File — footer.jsp

Example13
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<h3 style="color: white" align="center">
12Durgasoft India Pvt Ltd., 202, HMDA, Mitrivanam, Ameerpet, Hyd-38
13</h3>
14</body>
15</html>
16

Prepare Spring Configuration File — addstudent.jsp

Example14
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4 
5<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
6<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
7<html>
8<head>
9<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
10<title>Insert title here</title>
11</head>
12<body><br><br>
13<form:form method="POST" action="add" commandName="student">
14<center>
15<table>
16<tr>
17<td>Student Id</td>
18<td><form:input path="sid"/></td>
19</tr>
20<tr>
21<td>Student Name</td>
22<td><form:input path="sname"/></td>
23</tr>
24<tr>
25<td>Student Address</td>
26<td><form:input path="saddr"/></td>
27</tr>
28<tr>
29<td><input type="submit" value="ADD"/></td>
30</tr>
31</table>
32</center>
33</form:form>
34</body>
35</html>
36

Prepare Spring Configuration File — searchstudent.jsp

Example15
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4 
5<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
6<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
7<html>
8<head>
9<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
10<title>Insert title here</title>
11</head>
12<body><br><br>
13<form:form method="POST" action="search" commandName="student">
14<center>
15<table>
16<tr>
17<td>Student Id</td>
18<td><form:input path="sid"/></td>
19</tr>
20<tr>
21<td><input type="submit" value="SEARCH"/></td>
22</tr>
23</table>
24</center>
25</form:form>
26</body>
27</html>
28

Prepare Spring Configuration File — deletestudent.jsp

Example16
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="ISO-8859-1"%>
4<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
5<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
6<html>
7<head>
8<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
9<title>Insert title here</title>
10</head>
11<body><br><br>
12<form:form method="POST" action="delete" commandName="student">
13<center>
14<table>
15<tr>
16<td>Student Id</td>
17<td><form:input path="sid"/></td>
18</tr>
19<tr>
20<td><input type="submit" value="DELETE"/></td>
21</tr>
22</table>
23</center>
24</form:form>
25</body>
26</html>
27

Prepare Spring Configuration File — studentdetails.jsp

Example17
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<br><br>
12<center>
13<table border="1">
14<tr>
15<td>Student Id</td>
16<td>${student.sid}</td>
17</tr>
18<tr>
19<td>Student Name</td>
20<td>${student.sname}</td>
21</tr>
22<tr>
23<td>Student Address</td>
24<td>${student.saddr}</td>
25</tr>
26</table>
27</center>
28</body>
29</html>
30

Prepare Spring Configuration File — status.jsp

Example18
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<br><br>
12<h1 style="color: red;" align="center">${status}</h1>
13</body>
14</html>
15

Prepare Spring Configuration File — StudentController.java

Example19
JCode Cell
1 
2package com.durgasoft.controller;
3 
4import org.springframework.beans.factory.annotation.Autowired;
5import org.springframework.stereotype.Controller;
6import org.springframework.web.bind.annotation.RequestMapping;
7import org.springframework.web.bind.annotation.RequestMethod;
8import org.springframework.web.servlet.ModelAndView;
9 
10import com.durgasoft.beans.Student;
11import com.durgasoft.service.StudentService;
12 
13@Controller
14public class StudentController {
15 
16@Autowired
17private StudentService studentService;
18 
19@RequestMapping(value="/welcome", method=RequestMethod.GET)
20public String welcome() {
21return "welcomeDef";
22}
23 
24@RequestMapping(value="/add", method=RequestMethod.GET)
25public ModelAndView addStudent() {
26return new ModelAndView("addDef", "student", new Student());
27}
28 
29@RequestMapping(value="/search", method=RequestMethod.GET)
30public ModelAndView searchStudent() {
31return new ModelAndView("searchDef", "student", new Student());
32}
33 
34@RequestMapping(value="/delete", method=RequestMethod.GET)
35public ModelAndView deleteStudent() {
36return new ModelAndView("deleteDef", "student", new Student());
37}
38 
39@RequestMapping(value="/add", method=RequestMethod.POST)
40public ModelAndView add(Student student) {
41String status = studentService.addStudent(student);
42return new ModelAndView("statusDef", "status", status);
43}
44 
45@RequestMapping(value="/search", method=RequestMethod.POST)
46public ModelAndView search(Student student) {
47Student std = studentService.searchStudent(student.getSid());
48if(std == null) {
49 return new ModelAndView("statusDef", "status", "Student Not Existed");
50}else {
51 return new ModelAndView("studentDetailsDef", "student", std);
52}
53}
54@RequestMapping(value="/delete", method=RequestMethod.POST)
55public ModelAndView delete(Student student) {
56String status = studentService.deleteStudent(student.getSid());
57return new ModelAndView("statusDef", "status", status);
58}
59}
60

Prepare Spring Configuration File — StudentService.java

Example20
JCode Cell
1 
2package com.durgasoft.service;
3 
4import com.durgasoft.beans.Student;
5 
6public interface StudentService {
7public String addStudent(Student std);
8public Student searchStudent(String sid);
9public String deleteStudent(String sid);
10}
11

Prepare Spring Configuration File — StudentServiceImpl.java

Example21
JCode Cell
1 
2package com.durgasoft.service;
3 
4import org.springframework.beans.factory.annotation.Autowired;
5import org.springframework.stereotype.Service;
6import org.springframework.transaction.annotation.Transactional;
7 
8import com.durgasoft.beans.Student;
9import com.durgasoft.dao.StudentDao;
10import com.durgasoft.entity.StudentEntity;
11 
12 
13@Service("studentService")
14public class StudentServiceImpl implements StudentService {
15 
16@Autowired
17private StudentDao studentDao;
18 
19@Transactional
20@Override
21public String addStudent(Student std) {
22StudentEntity stdEntity = new StudentEntity();
23stdEntity.setSid(std.getSid());
24stdEntity.setSname(std.getSname());
25stdEntity.setSaddr(std.getSaddr());
26 
27String status = studentDao.add(stdEntity);
28return status;
29}
30 
31@Override
32public Student searchStudent(String sid) {
33StudentEntity stdEntity = studentDao.search(sid);
34Student std = null;
35if(stdEntity == null) {
36 std = null;
37}else {
38 std = new Student();
39 std.setSid(stdEntity.getSid());
40 std.setSname(stdEntity.getSname());
41 std.setSaddr(stdEntity.getSaddr());
42}
43return std;
44}
45 
46@Transactional
47@Override
48public String deleteStudent(String sid) {
49String status = studentDao.delete(sid);
50return status;
51}
52}
53

Prepare Spring Configuration File — StudentDao.java

Example22
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import com.durgasoft.entity.StudentEntity;
5 
6public interface StudentDao {
7public String add(StudentEntity stdEntity);
8public StudentEntity search(String sid);
9public String delete(String sid);
10}
11

Prepare Spring Configuration File — StudentDaoImpl.java

Example23
JCode Cell
1 
2package com.durgasoft.dao;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.springframework.beans.factory.annotation.Autowired;
7import org.springframework.orm.hibernate4.HibernateTemplate;
8import org.springframework.stereotype.Repository;
9import org.springframework.transaction.annotation.Propagation;
10import org.springframework.transaction.annotation.Transactional;
11 
12import com.durgasoft.entity.StudentEntity;
13 
14@Repository("studentDao")
15 
16public class StudentDaoImpl implements StudentDao {
17 
18 
19 
20@Autowired
21private HibernateTemplate hibernateTemplate;
22String status = "";
23 
24@Override
25public String add(StudentEntity stdEntity) {
26try {
27 
28 StudentEntity std = (StudentEntity)hibernateTemplate.get(StudentEntity.class, stdEntity.getSid());
29 if(std == null) {
30 String pk_Val = (String) hibernateTemplate.save(stdEntity);
31 if(pk_Val.equals(stdEntity.getSid())) {
32 status = "Student Inserted Successfully";
33 }else {
34 status = "Student Insertion Failure";
35 }
36 }else {
37 status = "Student Existed Already";
38 }
39} catch (Exception e) {
40 status = "Student Insertion Failure";
41 e.printStackTrace();
42}
43return status;
44}
45 
46@Override
47public StudentEntity search(String sid) {
48StudentEntity stdEntity = null;
49try {
50 stdEntity = (StudentEntity) hibernateTemplate.get(StudentEntity.class, sid);
51 
52} catch (Exception e) {
53 e.printStackTrace();
54}
55return stdEntity;
56}
57 
58@Override
59public String delete(String sid) {
60try {
61 StudentEntity stdEntity = hibernateTemplate.get(StudentEntity.class, sid);
62 if(stdEntity == null) {
63 status = "Student Not Existed";
64 }else {
65 hibernateTemplate.delete(stdEntity);
66 status = "Student Deleted SUccessfully";
67 }
68} catch (Exception e) {
69 e.printStackTrace();
70 status = "Student Deletion Failure";
71}
72return status;
73}
74 
75}
76

Prepare Spring Configuration File — Student.java

Example24
JCode Cell
1 
2package com.durgasoft.beans;
3 
4public class Student {
5private String sid;
6private String sname;
7private String saddr;
8 
9public String getSid() {
10 return sid;
11}
12public void setSid(String sid) {
13this.sid = sid;
14}
15public String getSname() {
16return sname;
17}
18public void setSname(String sname) {
19this.sname = sname;
20}
21public String getSaddr() {
22return saddr;
23}
24public void setSaddr(String saddr) {
25this.saddr = saddr;
26}
27 
28 
29}
30

Prepare Spring Configuration File — StudentEntity.java

Example25
JCode Cell
1 
2package com.durgasoft.entity;
3 
4import javax.persistence.Column;
5import javax.persistence.Entity;
6import javax.persistence.Id;
7import javax.persistence.Table;
8 
9@Entity
10@Table(name="student")
11public class StudentEntity {
12@Id
13@Column(name="SID")
14private String sid;
15@Column(name="SNAME")
16private String sname;
17@Column(name="SADDR")
18private String saddr;
19 
20public String getSid() {
21return sid;
22}
23public void setSid(String sid) {
24this.sid = sid;
25}
26public String getSname() {
27return sname;
28}
29public void setSname(String sname) {
30this.sname = sname;
31}
32public String getSaddr() {
33return saddr;
34}
35public void setSaddr(String saddr) {
36this.saddr = saddr;
37}
38}
39

Prepare Spring Configuration File — tiles-defs.xml

Example26
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3 
4<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN"
5"http://tiles.apache.org/dtds/tiles-config_2_1.dtd">
6 
7<tiles-definitions>
8<definition name="welcomeDef" template="/WEB-INF/layout.jsp">
9 <put-attribute name="header" value="/WEB-INF/header.jsp"/>
10 <put-attribute name="menu" value="/WEB-INF/menu.jsp"/>
11<put-attribute name="body" value="/WEB-INF/welcome.jsp"/>
12<put-attribute name="footer" value="/WEB-INF/footer.jsp"/>
13</definition>
14<definition name="addDef" extends="welcomeDef">
15<put-attribute name="body" value="/WEB-INF/addstudent.jsp"/>
16</definition>
17<definition name="searchDef" extends="welcomeDef">
18<put-attribute name="body" value="/WEB-INF/searchstudent.jsp"/>
19</definition>
20<definition name="deleteDef" extends="welcomeDef">
21<put-attribute name="body" value="/WEB-INF/deletestudent.jsp"/>
22</definition>
23<definition name="statusDef" extends="welcomeDef">
24<put-attribute name="body" value="/WEB-INF/status.jsp"/>
25</definition>
26<definition name="studentDetailsDef" extends="welcomeDef">
27<put-attribute name="body" value="/WEB-INF/studentdetails.jsp"/>
28</definition>
29</tiles-definitions>
30

Prepare Spring Configuration File — ds-servlet.xml

Example27
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<beans xmlns="http://www.springframework.org/schema/beans"
4xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5xmlns:p="http://www.springframework.org/schema/p"
6xmlns:context="http://www.springframework.org/schema/context"
7xmlns:aop="http://www.springframework.org/schema/aop"
8xmlns:tx="http://www.springframework.org/schema/tx"
9 
10xsi:schemaLocation="
11http://www.springframework.org/schema/beans
12http://www.springframework.org/schema/beans/spring-beans.xsd
13http://www.springframework.org/schema/context
14http://www.springframework.org/schema/context/spring-context.xsd
15http://www.springframework.org/schema/tx
16http://www.springframework.org/schema/tx/spring-tx.xsd
17http://www.springframework.org/schema/aop
18http://www.springframework.org/schema/aop/spring-aop.xsd">
19 
20<context:component-scan base-package="com.durgasoft" />
21<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
22 
23<bean id="viewResolver"
24class="org.springframework.web.servlet.view.UrlBasedViewResolver">
25<property name="viewClass">
26 <value>
27 org.springframework.web.servlet.view.tiles2.TilesView
28 </value>
29</property>
30</bean>
31 
32<bean id="tilesConfigurer"
33class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
34<property name="definitions">
35 <list>
36 <value>/WEB-INF/tiles-defs.xml</value>
37 </list>
38</property>
39</bean>
40 
41<bean id="dataSource"
42class="org.springframework.jdbc.datasource.DriverManagerDataSource">
43<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
44<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/>
45<property name="username" value="system"/>
46<property name="password" value="durga"/>
47</bean>
48 
49<bean id="sessionFactory"
50class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
51<property name="dataSource" ref="dataSource"/>
52<property name="annotatedClasses">
53 <list>
54 <value>com.durgasoft.entity.StudentEntity</value>
55 </list>
56</property>
57<property name="hibernateProperties">
58 <props>
59 <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
60 <!-- <prop key="hibernate.show_sql">true</prop> -->
61 </props>
62</property>
63</bean>
64 
65<bean id="hibernateTransactionManager"
66class="org.springframework.orm.hibernate4.HibernateTransactionManager">
67<property name="sessionFactory" ref="sessionFactory"/>
68</bean>
69 
70<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
71<property name="sessionFactory" ref="sessionFactory"/>
72</bean>
73 
74</beans>
75

Prepare Spring Configuration File — web.xml

Example28
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>tilesapp</display-name>
5<welcome-file-list>
6 <welcome-file>index.html</welcome-file>
7 <welcome-file>index.htm</welcome-file>
8 <welcome-file>index.jsp</welcome-file>
9 <welcome-file>default.html</welcome-file>
10 <welcome-file>default.htm</welcome-file>
11<welcome-file>default.jsp</welcome-file>
12</welcome-file-list>
13 
14<servlet>
15<servlet-name>ds</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>ds</servlet-name>
22<url-pattern>/</url-pattern>
23</servlet-mapping>
24 
25</web-app>
26

Prepare Spring Configuration File

To run this application we have to use the following JARs in web application lib folder.

1) Spring MVC + Spring ORM + Spring Tx + Spriong JDBC + Spring AOP 2) Tiles Jars and its supportig jars 3) jstl jars If we use JstlView class. 4) Hibernate Jars 5) ojdbc6.jar 6) Commons bean utils+commons digester + log4j + slf4j-log4j12 + slf4j

Spring JARS

spring-aop-4.3.9.RELEASE.jar spring-aspects-4.3.9.RELEASE.jar spring-beans-4.3.9.RELEASE.jar spring-context-4.3.9.RELEASE.jar spring-context-support-4.3.9.RELEASE.jar spring-core-4.3.9.RELEASE.jar spring-expression-4.3.9.RELEASE.jar spring-jdbc-4.3.9.RELEASE.jar spring-orm-4.3.9.RELEASE.jar spring-tx-4.3.9.RELEASE.jar spring-web-4.3.9.RELEASE.jar spring-webmvc-4.3.9.RELEASE.jar

Tiles and dependent JARS

commons-beanutils-1.8.3.jar commons-digester-2.1.jar log4j.jar slf4j-log4j12.jar slf4j.jar tiles-api-2.2.2.jar tiles-core-2.2.2.jar tiles-jsp-2.2.2.jar tiles-servlet-2.2.2.jar tiles-template-2.2.2.jar

Jstl Jars taglibs-standard-impl-1.2.5.jar taglibs-standard-spec-1.2.5.jar

Hibernate Jars

antlr-2.7.7.jar commons-logging-1.2.jar dom4j-1.6.1.jar hibernate-commons-annotations-4.0.5.Final.jar hibernate-core-4.3.11.Final.jar hibernate-entitymanager-4.3.11.Final.jar hibernate-jpa-2.1-api-1.0.0.Final.jar jandex-1.1.0.Final.jar javassist-3.18.1-GA.jar jboss-logging-3.1.3.GA.jar jboss-logging-annotations-1.2.0.Beta1.jar jboss-transaction-api_1.2_spec-1.0.0.Final.jar ojdbc6.jar

ALL Jars Together antlr-2.7.7.jar commons-beanutils-1.8.3.jar commons-digester-2.1.jar commons-logging-1.2.jar dom4j-1.6.1.jar hibernate-commons-annotations-4.0.5.Final.jar hibernate-core-4.3.11.Final.jar hibernate-entitymanager-4.3.11.Final.jar hibernate-jpa-2.1-api-1.0.0.Final.jar jandex-1.1.0.Final.jar javassist-3.18.1-GA.jar jboss-logging-3.1.3.GA.jar jboss-logging-annotations-1.2.0.Beta1.jar jboss-transaction-api_1.2_spec-1.0.0.Final.jar log4j.jar ojdbc6.jar slf4j-log4j12.jar slf4j.jar spring-aop-4.3.9.RELEASE.jar spring-aspects-4.3.9.RELEASE.jar spring-beans-4.3.9.RELEASE.jar spring-context-4.3.9.RELEASE.jar spring-context-support-4.3.9.RELEASE.jar spring-core-4.3.9.RELEASE.jar spring-expression-4.3.9.RELEASE.jar spring-jdbc-4.3.9.RELEASE.jar spring-orm-4.3.9.RELEASE.jar spring-tx-4.3.9.RELEASE.jar spring-web-4.3.9.RELEASE.jar spring-webmvc-4.3.9.RELEASE.jar taglibs-standard-impl-1.2.5.jar taglibs-standard-spec-1.2.5.jar tiles-api-2.2.2.jar tiles-core-2.2.2.jar tiles-jsp-2.2.2.jar tiles-servlet-2.2.2.jar tiles-template-2.2.2.jar

Struts Overview

 Framework is a semi implemented application, it will be used to design applications in simplified manner.

 Framework is prefabricated software units that programmer can share, customize, reuse in order to simplify application development.

 Framework is the collection of predefined classes and interfaces to simplify application development.

In general, in Applications development, Frameworks will provide the following advantages.

  • Frameworks will provide common implementation in all the projects as predefined implementation

EX: Controller Servlets and the services like I18N, Exception Handling, Validations ,.....

  • Frameworks will provide standard template to design applications.
  • Frameworks will provide standard flow of execution between the components.
  • Frameworks will reduce application development time.
  • Frameworks will reduce application development cost.
  • Frameworks will improve productivity.
  • Frameworks will provide modularity in application development.

There are two types of Frameworks.

  • Web Frameworks
  • Application Frameworks

What is the difference between web frameworks and Application Frameworks?

Ans

Web Frameworks will provide very good environment to prepare and execute web applications only. EX: Struts, JSF.

Application Frameworks will provide very good environment to prepare and execute any type of JAVA/J2EE Applications including Standalone Applications, Web applications, Distributed Applications, EX: Spring

Struts is MVC based web framework provided by Apache Software Foundations.

Struts is existed in two versions.

  • Struts1.x
  • Struts2.x

If we want to prepare Struts applications in Struts1.x version then we have to use the following components

  • View
  • Deployment Descriptor
  • Controller [ActionServlet]
  • Action class
  • Action Form
  • Struts Configuration File

View

In Struts applications, View part is representing presentation part. In web applications, there are two types of presentation part.

  • Informational Presentation part
  • Form Based Presentation part

Informational Presentation part

This type view part is able to provide only information to the user, which includes status of the server side actions like Success, failure, ... and display a particular database table data,.....

EXAMPLE: success.html

<h1> Login Success </h1>

Form Based Presentation part

This type of view part is able to provide a form to collect data from users and to submit data to the server side applications.

In Struts applications, to prepare Presentation part we are able to use plain HTML tags, but, which are not suggestible. In Struts applications it is suggestible to use Struts provided tag library.

EX: loginform.html

  • <html>
  • <body>
  • <form method="POSt" action="login.*">
  • <table>
  • <tr>
  • <td>User Name</td>
  • <td><input type="text" name="uname"/></td>
  • </tr>
  • <tr>
  • <td>Password</td>
  • <td><input type="password" name="upwd"/></td>
  • </tr>
  • <tr>
  • <td><ipnut type="submit" value="Login"/></td>
  • </tr>
  • </table></form></body></html>

The above login form with Struts provided html tag library EX: loginform.jsp

  • <%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
  • <html:html>
  • <body>
  • <html:form method="POST" action="login.do">
  • <table>
  • <tr>
  • <td>User Name</td>
  • <td><html:text property="uname"/></td>
  • </tr>
  • <tr>
  • <td>Password</td>
  • <td><html:password property="upwd"/></td>
  • </tr>
  • <tr>
  • <td><html:submit>Login</html:submit></td>
  • </tr>
  • </table></html:form></body></html>

Deployment Descriptor

Deployment descriptor is web.xml file, it will provide description about our web application which is required by the container in order to perform server side actions. In general, in web applications, web.xml file will provide the following configuration details.

  • Display names configurations.
  • Welcome Files Configurations.
  • Servlets configurations
  • Filters Configurations
  • Listeners Configurations.
  • Session time out configurations
  • Error Pages Configurations
  • Taglib configurations

In Struts based web applications, the main intention of web.xml file is to configure controller Servlet that is ActionServlet.

Example38
JCode Cell
1 
2<web-app>
3<servlet>
4<servlet-name>actionServlet</servlet-name>
5<servlet-class>org.apache.struts.action.ActionServlet
6</servlet-class>
7<load-on-startup>1</load-on-startup>
8</servlet>
9<servlet-mapping>
10<servlet-name>actionServlet</servlet-name>
11<url-pattern>*.do</url-pattern>
12</servlet-mapping>
13</web-app>
14

Controller [ActionServlet]

In Struts Framework, ActionServlet is predefined Controller, it was provided in the form of org.apache.struts.action.ActionServlet .

In Struts applications, ActionServlet will perform the following actions.

  • ActionServlet will take request from Client.
  • ActionServlet will identify the names and locations of the ActionForm and Action class

through Struts configuration file.

  • ActionServlet will load , instantiate ActionForm class.
  • ActionServlet will store form data in ActionForm object.
  • ActionServlet will load and instantiation Action class.
  • ActionServlet will execute execute(--) method in Action class.
  • ActionServlet will identify view page through Struts configuration file.
  • ActionServlet will forward request to view page inorder to generate response.

Note: In Struts applications, ActionServlet is performing all the above actions by using "RequestProcessor" internally.

Action Class or Controller Component — LoginActionForm.java

In Struts based web applications, the main intention of ActionForm or FormBean component is to manage a particular form data at Server side inorder to perform Server side data validations, to transfer data from Controller layer to model layer or Vie layer,.....

To prepare Form Bean components in Struts applications we have to use the following rules and regulations.

  • Declare an user defined class, it must be extended from org.apache.struts.action.ActionForm .
  • Form Bean class must be public, it must not be abstract and final.
  • In Form Bean class, we must declare properties with the same names of the form

properties.

  • In Form Bean class we must declare all properties as private and all bahaviours as public.
  • In FormBean class , we must provide a seperate set of setXXX() and getXXX() methods

for each and every property.

  • In FormBean class, if we want to provide any constructor then we can provide constructor

but that constructor must be public and 0-arg constructor.

  • In FormBean class, we can override equals(-) method and hashCode() method as per

the requirement.

EXAMPLE:

Example40
JCode Cell
1 
2public class LoginActionForm extends org.apache.struts.action.ActionForm{
3private String uname;
4private String upwd;
5public void setUname(String uname){
6this.uname = uname;
7}
8public void setUpwd(String upwd){
9this.upwd = upwd;
10}
11public String getUname(){
12return uname;
13}
14public String getUpwd(){
15return upwd;
16}
17}
18

Action Class or Controller Component

In Struts based web applications, the main intention of Action class is to manage application logic which we want to execute by getting request from client.

In Struts based web applications, to prepare Action class we have to use the following steps.

  • Declare an user defined class and it must be extended from org.apache.struts.action.Action class.
  • Action class must be public class and it must not be abstract class.
  • In Action class we must override either of the following methods.

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest reques, HttpServletResponse response)throws Exception

public ActionForward execute(ActionMapping mappinig, ActionForm form, ServletRequest request, ServletResponse response)throws Exception.

Note:In execute() method we must return ActionForward object with a particular Forward key inorder to identify target view page, for this, we have to use the following method from ActionMapping.

public ActionForward findForward(String key)

EX: LoginAction.java

  • public class LoginAction extends org.apache.struts.action.Action{
  • public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequ

est request, HttpServletResponse response)throws Exception{

  • ----Appl logic-----
  • String status = "success"/"failure";
  • return mapping.findForward(status);

struts-config.xml

 In Struts based web applications, the main intention of struts configuration file is to provide mappings between user forms amd the respective ActionForm classes and Action classes ,...... which are required by the ActionServlet inorder to perform Server side actions.

 In Struts based web applications, the default name and location of configuration file is "struts-config.xml" and "WEB-INF" location, but, it is possible to change this default name and location but we must give that new name and location to the Struts Framework.

 In Struts based web applications, configuration file is able to provide the following configurations.

  • Datasource configurations.
  • Global Forwards configurations.
  • Form Beans Configurations.
  • Action classes configurations.
  • Message Resources configurations.
  • Controller configurations.
  • Plugin configurations
  • Global Exceptions configurations.

To prepare basic Struts based web applications we need to provide ActionForm class configuration and action class configuration in struts connfiguration file.

  • <!DOCTYPE ---- >
  • <struts-config>
  • <form-beans>
  • <form-bean name="--" type="--"/>
  • </form-beans>
  • <action-mappings>
  • <action path="/---" name="--" type="--">
  • <forward name="--" path="/---"/>
  • </action>
  • </action-mappings>
  • </struts-config>

 Where <struts-config> is a root tag, it will include struts application configuration details.  Where <form-beans> tag is able to include no of form beans configurations.  Where <form-bean> tag is able to provide single form bean class configuration.  Where "name" attribute in <form-bean> tag is able to provide logical name to Form Bean

component.  Where "type" attribute in <form-bean> tag will take fully qualified name of the respective

form bean class.  Where <action-mappings> tag is able to include no of actions configurations.  Where <action> tag is able to provide mapping between user form, ActionForm class and

the respective Action class.  Where "path" attribute in <action> tag is able to take url pattern which we specified in User

form.  Where "name" attribute in <action> tag will take logical name of the form bean class which

we specified in struts configuration file under form beans configurations.  Where "type" attribute in <action> tag is able to take fully qualified name of the Action

class.  Where <forward> tag is able to provide mapping between forward key which is returned

from execute() method in Action class and the target view page.  Where "name" attribute in <forward> tag is able to take forward key.  Where "path" attribute in <forward> tag is able to take the name and location of target view

page.

Example42
JCode Cell
1 
2<!DOCTYPE ..... >
3<struts-config>
4<form-beans>
5<form-bean name="loginForm" type="com.durgasoft.beans.LoginActionForm"/>
6</form-beans>
7<action-mappings>
8<action path="/login" name="loginForm" type="com.durgasoft.action.LoginAction">
9 <forward name="success" path="/success.html"/>
10 <forward name="failure" path="/failure.html"/>
11</action-mappings>
12</struts-config>
13

Steps — loginform.html

  • Download Struts JARs from internet.
  • Create Dynamic Project in Eclipse.
  • Copy all Struts related JARs in lib folder in dynamic web project.
  • Configure ActionServlet in web.xml file.
  • Prepare User forms
  • Prepare Form Bean class.
  • Create Action class.
  • Create Struts configuration file.
  • Run dynamic web application.

Example (struts Application)

Example43
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>User Login Form</h3>
11<form method="POST" action="login.do">
12<table>
13<tr>
14<td>User Name</td>
15<td><input type="text" name="uname"/></td>
16</tr>
17<tr>
18<td>Password</td>
19<td><input type="password" name="upwd"/></td>
20</tr>
21<tr>
22<td><input type="submit" value="Login"/></td>
23</tr>
24</table>
25</form>
26</body>
27</html>
28

Steps — success.html

Example44
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>User Login Status</h3>
11<font color="red" size="6">
12<b>User Login Success</b>
13</font>
14<h5>
15<a href="./loginform.html">|User Login Form|</a>
16</h5>
17</body>
18</html>
19

Steps — Failure.html

Example45
JCode Cell
1 
2<!DOCTYPE html>
3<html>
4<head>
5<meta charset="ISO-8859-1">
6<title>Insert title here</title>
7</head>
8<body>
9<h2>Durga Software Solutions</h2>
10<h3>User Login Status</h3>
11<font color="red" size="6">
12<b>User Login Failure</b>
13</font>
14<h5>
15<a href="./loginform.html">|User Login Form|</a>
16</h5>
17</body>
18</html>
19

Steps — LoginActionForm.java

Example46
JCode Cell
1 
2package com.durgasoft.beans;
3 
4import org.apache.struts.action.ActionForm;
5 
6public class LoginActionForm extends ActionForm {
7private String uname;
8private String upwd;
9 
10public String getUname() {
11return uname;
12}
13public void setUname(String uname) {
14this.uname = uname;
15}
16public String getUpwd() {
17return upwd;
18}
19public void setUpwd(String upwd) {
20this.upwd = upwd;
21}
22}
23

Steps — LoginAction.java

Example47
JCode Cell
1 
2package com.durgasoft.action;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.apache.struts.action.Action;
8import org.apache.struts.action.ActionForm;
9import org.apache.struts.action.ActionForward;
10import org.apache.struts.action.ActionMapping;
11 
12import com.durgasoft.beans.LoginActionForm;
13 
14public class LoginAction extends Action {
15@Override
16public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
17 HttpServletResponse response) throws Exception {
18 LoginActionForm laf = (LoginActionForm)form;
19 String uname = laf.getUname();
20 String upwd = laf.getUpwd();
21 String status = "";
22 if(uname.equals("durga") && upwd.equals("durga")) {
23 status = "success";
24 }else {
25 status = "failure";
26 }
27 return mapping.findForward(status) ;
28}
29}
30

Steps — struts-config.xml

Example48
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE struts-config PUBLIC
4 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
5 "http://struts.apache.org/dtds/struts-config_1_3.dtd">
6<struts-config>
7<form-beans>
8 <form-bean name="loginForm" type="com.durgasoft.beans.LoginActionForm"/>
9</form-beans>
10<action-mappings>
11<action path="/login" name="loginForm" type="com.durgasoft.action.LoginAction">
12 <forward name="success" path="/success.html"/>
13 <forward name="failure" path="/failure.html"/>
14</action>
15</action-mappings>
16</struts-config>
17

Steps — web.xml

Example49
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
4<display-name>loginapp</display-name>
5<welcome-file-list>
6<welcome-file>loginform.html</welcome-file>
7</welcome-file-list>
8<servlet>
9<servlet-name>actionServlet</servlet-name>
10<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
11<load-on-startup>1</load-on-startup>
12</servlet>
13<servlet-mapping>
14<servlet-name>actionServlet</servlet-name>
15<url-pattern>*.do</url-pattern>
16</servlet-mapping>
17</web-app>
18

Steps

If we want to integrate Struts application with Spring Framework then we have to use the following steps.

  • Prepare User Forms and View part.
  • Prepare ActionForm class.
  • Prepare Action class.
  • Prepare Business class.
  • Prepare Struts configuration File.
  • Prepare Spring Configuration File.
  • Prepare web.xml file.

Prepare User Forms and View part

In Struts and Spring Integration applications, we have to prepare presentation part as per Struts rules and regulations only. To prepare User Interface in Struts applications we will use either normal html tags or we will use Struts provided tag library.

EX:

<form method="POST" action="login.do"> User Name<input type="text" name="uname"/><br> Password<input type="password" name="upwd"/><br> <input type="submit" value="Login"/> </form>

success.jsp

<h1> User Login Success</h1>

failure.jsp

<h1> User Login Failure </h1>
  • Prepare ActionForm class.

In Struts based web applications, we have to prepare ActionForm class inorder to manage user form data at Server side .

In Struts applications, to prepare ActionForm class we will use the following steps.

  • Declare an USer defined class.
  • Extend org.apache.struts.action.ActionForm class to user defined class.
  • Declare properties as per user form in ActionForm class and provide setXXX() and getXXX() methods for each and every property.

EX:

public class LoginActionForm extends ActionForm{ private String uname; private String upwd; setXXX() and getXXX() }

  • Prepare Action class.

In Struts based web applications, the main intention of Action class is to include business logic or to provide Business Components provided business method calls. In Struts with Spring integration applications we will provide application business logic in Spring Bean components and it must be accessed from Struts Action classes.

To prepare Action class in Struts with Spring integration applications we have to use the following steps.

a) Declare an user defined class. b) Extend org.springframework.web.struts.ActionSupport class to user defined class. c) Provide application logic by overriding execute() method. d) In execute() method get ApplicationContext object by accessing

getWebApplicationContext() method and get Spring Bean objcts by using getBean() method. e) Access Business methods which we provided in Spring bean objects.

Note: The main intention of org.springframework.web.struts.ActionSupport class is to provide getWebApplicationContext() method inorder to get ApplicationContext object inorder to get Spring provided Bean objects.

public ApplicationContext getWebApplicationcontext()

EX:

public class LoginAction extends ActionSupport { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception {

LoginActionForm laf = (LoginActionForm)form; String uname = laf.getUname(); String upwd = laf.getUpwd(); ApplicationContext context = getWebApplicatinContext(); UserService us =(UserService)context.getBean(―userService‖); String status = us.checkLogin(uname, upwd); return mapping.findForward(status); } }

Prepare Business class

In Struts with Spring Integration application, we will provide Business component as per Spring rules and regulation.

EX:

public class UserService{ String status = ""; public String checkLogin(String uname, String upwd){ if(uname.equals("durga") && upwd.equals("durga")){ status = "success"; }else{ status = "failure"; }

Prepare Struts configuration File — loginform.jsp

In Struts with Spring Integration applications, we have to provide provide all Struts configurations like FormBeans, Action classes,... and we must provide plug-in coinfiguration with the "org.springframework.web.struts.ContextLoaderPlugIn" with the property "contextConfigLocation" inorder to provide name and location of the Spring configuration.

<struts-config>
<form-beans>
<form-bean name="loginActionForm"

type="com.durgasoft.formbeans.LoginActionForm"/>

</form-beans>
<action-mappings>
<action path="/login" name="loginActionForm"

type="com.durgasoft.action.LoginAction">

<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/failure.jsp"/>
</action>
</action-mappings>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-

INF/applicationContext.xml" />

</plug-in>
</struts-config>
  • Prepare Spring Configuration File.

In Struts with Spring Integration application we will prepare Spring configuration file with all the beans configuration.

EX:

<beans> <bean id="userService" class="com.durgasoft.service.UserService"/>
</beans>
  • Prepare web.xml file.

In Struts with Spriong integration application , we will provide ActionServlet Configuration in web.xml file as per Struts rules and regulations.

EX:

<web-app> <display-name>struts_spring_app</display-name> <welcome-file-list> <welcome-file>loginform.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>actionServlet</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>actionServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
</web-app>

Example:

Example55
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<h2 style="color: red;" align="center">Durga Software Solutions</h2>
12<h3 style="color: blue;" align="center">User Login Page</h3>
13<form method="POST" action="login.do">
14<center>
15<table>
16<tr>
17<td>User Name</td>
18<td><input type="text" name="uname"/></td>
19</tr>
20<tr>
21<td>Password</td>
22<td><input type="password" name="upwd"/></td>
23</tr>
24<tr>
25<td><input type="submit" value="Login"/></td>
26</tr>
27</table>
28</center>
29</form>
30</body>
31</html>
32

Prepare Struts configuration File — success.jsp

Example56
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<br><br>
12<h1 style="color: red;" align="center">User Login Success</h1>
13</body>
14</html>
15

Prepare Struts configuration File — failure.jsp

Example57
JCode Cell
1 
2<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3pageEncoding="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>Insert title here</title>
9</head>
10<body>
11<br><br>
12<h1 style="color: red;" align="center">User Login Failure</h1>
13</body>
14</html>
15

Prepare Struts configuration File — LoginActionForm.java

Example58
JCode Cell
1 
2package com.durgasoft.formbeans;
3 
4import org.apache.struts.action.ActionForm;
5 
6public class LoginActionForm extends ActionForm {
7private String uname;
8private String upwd;
9 
10public String getUname() {
11return uname;
12}
13public void setUname(String uname) {
14this.uname = uname;
15}
16public String getUpwd() {
17return upwd;
18}
19public void setUpwd(String upwd) {
20this.upwd = upwd;
21}
22 
23 
24}
25

Prepare Struts configuration File — LoginAction.java

Example59
JCode Cell
1 
2package com.durgasoft.action;
3 
4import javax.servlet.http.HttpServletRequest;
5import javax.servlet.http.HttpServletResponse;
6 
7import org.apache.struts.action.ActionForm;
8import org.apache.struts.action.ActionForward;
9import org.apache.struts.action.ActionMapping;
10import org.springframework.web.struts.ActionSupport;
11 
12import com.durgasoft.formbeans.LoginActionForm;
13import com.durgasoft.service.UserService;
14 
15public class LoginAction extends ActionSupport {
16 
17 
18 
19@Override
20public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
21 HttpServletResponse response) throws Exception {
22LoginActionForm laf = (LoginActionForm)form;
23String uname = laf.getUname();
24String upwd = laf.getUpwd();
25UserService userService = (UserService) getWebApplicationContext().getBean("userService");
26String status = userService.checkLogin(uname, upwd);
27return mapping.findForward(status);
28}
29}
30

Prepare Struts configuration File — UserService.java

Example60
JCode Cell
1 
2package com.durgasoft.service;
3 
4public class UserService {
5String status = "";
6public String checkLogin(String uname, String upwd) {
7 if(uname.equals("durga") && upwd.equals("durga")) {
8 status = "success";
9 }else {
10 status = "failure";
11}
12return status;
13}
14}
15

Prepare Struts configuration File — struts-config.xml

Example61
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE struts-config PUBLIC
4 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
5 "http://struts.apache.org/dtds/struts-config_1_3.dtd">
6<struts-config>
7<form-beans>
8 <form-bean name="loginActionForm" type="com.durgasoft.formbeans.LoginActionForm"/>
9</form-beans>
10<action-mappings>
11<action path="/login" name="loginActionForm" type="com.durgasoft.action.LoginAction">
12 <forward name="success" path="/success.jsp"/>
13 <forward name="failure" path="/failure.jsp"/>
14</action>
15</action-mappings>
16<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
17<set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" />
18</plug-in>
19</struts-config>
20

Prepare Struts configuration File — applicationContext.xml

Example62
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
4 "http://www.springframework.org/dtd/spring-beans.dtd">
5<beans>
6<bean id="userService" class="com.durgasoft.service.UserService"/>
7</beans>
8

Prepare Struts configuration File — web.xml

Example63
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
4<display-name>struts_spring_app</display-name>
5<welcome-file-list>
6<welcome-file>loginform.jsp</welcome-file>
7</welcome-file-list>
8<servlet>
9<servlet-name>actionServlet</servlet-name>
10<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
11<load-on-startup>1</load-on-startup>
12</servlet>
13<servlet-mapping>
14<servlet-name>actionServlet</servlet-name>
15<url-pattern>*.do</url-pattern>
16</servlet-mapping>
17</web-app>
18

Prepare Struts configuration File

To run this application we have to use the following JARs. o Struts1.3.10 Jars + Spring2.5 jars

antlr-2.7.2.jar bsf-2.3.0.jar commons-beanutils-1.8.0.jar commons-chain-1.2.jar commons-digester-1.8.jar commons-fileupload-1.1.1.jar commons-io-1.1.jar commons-logging-1.0.4.jar commons-validator-1.3.1.jar jstl-1.0.2.jar oro-2.0.8.jar spring-aop.jar

📝 Key Takeaways
  • Key ideas of Spring - Web MVC with Tiles explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end