109
SPRING TUTORIAL: 18/04/11 10:39 AM Flow of typical Spring MVC application: ‘Flow of typical Spring MVC application’ or in other words ‘How exactly user gets served?’. We will see how data and control flows through all the stages of this process. Let me start with one diagram,

SPRING_TUTORIAL1.1(2)-2-1(1)

Embed Size (px)

DESCRIPTION

sample tutorials on spring

Citation preview

19/05/11 6:39 PMFlow of typical Spring MVC application:

Flow of typical Spring MVC application or in other words How exactly user gets served?. We will see how data and control flows through all the stages of this process. Let me start with one diagram,

Heres the transition explanation below,Transition 1 User sends request to server by submitting form / by clicking hyperlink etc. Request is initially given to WEB.XML.

Transition 2 WEB.XML routes request to DispatcherServlet by looking at tag.

Transition 3 Inside DispatcherServlet, First HandlerMapping handed over request to suitable Controller.

Transition 4 Controller maps request to proper Model class. All BUSINESS LOGIC is done inside Model class.

Transition 5 If database operation is needed then Model class will route request to suitable DAO. All database operations should be carried out in DAO.

Transition 6 If needed then attach attributes into request/session/application scope and return back to Model.

Transition 7 If needed then attach attributes into request/session/application scope and return back to Controller.

Transition 8 Controller simply returns it to any View(JSP/HTML etc).

Transition 9 JSP/Html is viewed back to user.

SPRING TUTORIAL:18/04/11 10:39 AM

****This article is relevant for Spring MVC and Hibernate*****

Spring MVC is a web framework to handle web requests using Model View Controller pattern. Spring MVC works around a DisptacherServlet which handles all the request. If you take any web request than the fundamental steps required to process a request is as follows. The request is recieved in the form of Http request from client browser. The request is converted into a HttpRequest object and passed to a Servlet. In the case of Spring it is DisptacherServlet. The DispatcherServlet consults a handler mapping and decides the controller which is going to process the request. The request is processed by the controller and it returns a ModelAndView object. The ModelAndView contains both the Model and View. Model contains the data and view contains a logical id which can be resolved into an actual view which in most cases is a jsp file though there are many choices here. The view uses the Model data and generates the response which is returned back to the client browser.

In this tutorial, I have taken only log-in of the Application. I have used spring3.0 and Hibernate3.

Make a web application structure in your IDE. In eclipse you can make a Dynamic web application..

Flow of Request:-Web.xmlindex.jspLogin.jspweb.xmlmytjprep-servlet.xmlcontrollerservicesDAO--hibernate.hbm.xmlapplicationCotext.xmlview(.jsp)

1.> Configure the Spring container in web.xml:-

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

contextConfigLocation/WEB-INF/classes/applicationContext.xml

org.springframework.web.context.ContextLoaderListener

springMvc org.springframework.web.servlet.DispatcherServlet

springMvc *.html index.jsp

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

The jars required for the application are:-

login.jsp:-

Login Page Name:Password:

Now let's write the data access layer code. This is similar to Spring JDBC? classes . Right now we will be calling the data access layer code directly from front layer. In real life you might want to put one more layer of indirection by putting a service layer in the middle.

LoginBean.java:-

/* Java bean which will be used to save and retrieve data. */package com.exilant.beans;

public class LoginBean {private String name;private String password;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}

}

2.>Dispatcher-servlet.xml:-

Also let's write another configuration XML in WEB-INF directory. The name of this file will be springMvc -servlet.xml. The pattern is -servlet.xml.

registrationControllerid

Now the controller redirect the request to particular model or view or both.

3.> Let's now look into the controller class.

/** * The controller class which is used to take the user input and * process the data at the backend */

formBackingObject():-This object which is used to set the values when the form is displayed first time.

onSubmit():-This method is called when the form is submitted by the user.The command class is LoginBean so Spring automatically parses the HttpRequest object, retrieves the name value pair out of it and sets the properties in the command object.

Inversion ofControl:-private LoginService loginService;public void setLoginService(LoginService loginService) {this.loginService = loginService;}

// loginService.authenticateDetails(regBean);it will call the authenticateDetails method of LoginService.java class.This class is to map the beans object to the pojoClass.

4.> LoginService.java Class:-

// loginspringDao.save(loginSpringpojo);

Here this authenticateUser() is used to insert the data into the data base instead of writing Query manually. it is the one of Hibernate template method.

5.> LoginSpringDAO.java:-

6.> LoginSpring.hbm.xml:- Hibernate mapping

7.> ApplicationContext.xml:-

-------------------------------------------------------------------

8.> To complete the exercise let's put the jsp files which are our actual views.:-

login.jsp:-

Login Page NamePassword

Success.jsp:-

Login Success

WElCOME:

add InformationUpdate Informationedit InformationRemove Information

Controllers:-

We saw above two examples of Spring controller. Spring comes with a handful of controllers which are used to handle different kind of situations. The different controllers in Spring are:

AbstractController : It's the basic Controller and gives access to underlying HttpRequest and HttpResponse object. The ModelAndView object is returned from it. However you can build the response yourself, in that case return null in place of ModelAndView object.

MultiActionController : This controller can handle multiple requests using one Controller. The different request can be mapped to different methods of the controller.

AbstractCommandController : This follows command pattern. The request object is parsed and the values retrieved from request object is set to the command object. This controller is good for list kind of functioanlity where serach parameters can be set to command objects.

AbstractFormController : Provides Form submission support.SimpleFormController : Provides more support for form submission. Provides support similar to AbstractFormController and beyond that supports the initial view to be shown and the view to which the request should go after success.

AbstractWizardFormController : Provides support for wizard kind of situation where the user can be directed to follow a pattern of pages to execute a specific task or workflow. For example booking of online tickets.

Handler Mapping:-

Now let's understand how DispatcherServlet comes to know that which controller should be invoked for a particular request. Spring again delegates this task to a handler mapper, which helps the DispatcherServlet to do the job. For example in the springMvc-servlet.xml .we have used the handler mapper with name simpleUrlMapping. The property list tells that for which type of url pattern which controller needs to be invoked. Spring again comes up with a handful of mapper adn you can have more than one mapper also existing. Differemnt handler mapping that come with Spring are:BeanNameUrlHandlerMapping - The bean name is used as a URL pattern.SimpleUrlHandlerMapping - As we have used in the example above. Maps the pattern to the controller. It is the preferred approach.ControllerClassNameHandlerMapping Maps controller to URLs by using the controllers class name as the basis for the URL. So our Controller will be mapped to /*.htm

SPRING TUTORIAL:-18/04/11 10:39 AM

USE OF JAR FILES:-1. ant/ant.jar, ant/ant-launcher.jar, ant-trax.jar, ant-junit.jar--->used to build the framework and the sample apps

2.antlr/antlr-2.7.6.jar--->required for running application by hibernate

3.cglib/cglib-nodep-2.1_3.jar--> required for building the framework- required at runtime when proxying full target classes via Spring AOP

4.commonj/commonj-twm.jar-->required for building the framework- required at runtime when using Spring's CommonJ support

5.dom4j/dom4j-1.6.1, dom4j/jaxen-1.1-beta-7.jar-->required for running application (by Hibernate)

6.hibernate/hibernate3.jar-->required for building the framework- required at runtime when using Spring's Hibernate support

7.hibernate/hibernate-annotation.jar-->required for building the "tiger" part of the framework- required at runtime when using Spring's Hibernate Annotations support

8.j2ee/jstl.jar-->required for building the framework- required at runtime when using Spring's JstlView

9.j2ee/jta.jar-->required for building the framework- required at runtime when using Spring's JtaTransactionManager

10.j2ee/persistence.jar-->required for building the framework- required at runtime when using Spring's JPA support

11.j2ee/servlet-api.jar-->- required for building the framework- required at runtime when using Spring's web support

12.jakarta-commons/commons-beanutils.jar-->required for running JPetStore's Struts web tier

13.jakarta-commons/commons-collections.jar-->required for building the framework- required for running PetClinic, JPetStore (by Commons DBCP, Hibernate)

14.jakarta-commons/commons-dbcp.jar-->required for building the framework- required at runtime when using Spring's CommonsDbcpNativeJdbcExtractor- required for running JPetStore

15. jakarta-commons/commons-logging.jar-->required for building the framework- required at runtime, as Spring uses it for all logging

16.jakarta-commons/commons-pool.jar-->required for running Database (by Commons DBCP)

17.jakarta-commons/commons-validator.jar-->required for running JPetStore's Struts web tier on servers that eagerly load tag libraries .

18.junit/junit-3.8.2.jar, junit/junit-4.4.jar-->required for building and running the framework's test suite

19.tiles/tiles-api-2.0.5.jar, tiles/tiles-core-2.0.5.jar, tiles/tiles-jsp-2.0.5.jar--required for building the framework- required at runtime when using the Tiles2 TilesView

20.log4j/log4j-1.2.14.jar-->required for building the framework- required at runtime when using Spring's Log4jConfigurer

21. hibernate-3.1rc3.jar The list of classes contained in hibernate-3.1rc3.jar to be sure this is the correct jar file to retrieve to resolve your java.lang.ClassNotFoundException or java.lang.NoClassDefFoundError.

22.Odbc14.jar ojdbc14.jar is meant to be used with JDK 1.4 and JDK 1.5.ojdbc14.jar provides classes for use with JDK 1.4

Anandmathur

Spring 3.0:- Aim:- To WAP(Java perspective) with using Dependency injection/IOC .

Required Jars files:-1. org.springframework.core-3.0.0.RELEASE.jar------for core spring features2. org.springframework.beans-3.0.0.RELEASE.jar----for bean class to set/get the properties3. org.springframework.context-3.0.0.RELEASE.jar------Spring container4. org.springframework.context.support-3.0.0.RELEASE.jar-----Spring container5. org.springframework.asm-3.0.0.RELEASE.jarTo create Dynamic Objects6. org.springframework.aop-3.0.0.RELEASE.jar----it is just like filter as user in servlet7. commons-logging.jar----For logger massage instead of std I/O8. org.springframework.orm-3.0.0.RELEASE.jar----for expression library,and exception handling9. org.springframework.orm-3.0.4.RELEASE.jar----to import hibernate capability

All these jar files are required for making a simple standalone application.we will use other jar files as per our requirement.

IOC:-Inversion of control pattern is also known as Dependency Injection,it is nothing but one of the spring framework feature for intialization of objects of classes without using the (New() ) operator. It can be two type of injections like- ----- Property injection ------ Constructor injection

will see the use of these Injection in the example.

Lets see the demo example,

Structure :-

Create one Person.java class,which contains some data members and corresponding setter/getter method.

package com.training.exilant;

import java.util.List;

public class Person {

// fieldsprivate String name;private String city;private int age;private String emailAddress;

private Address homeAddress;

private List friends;

public Person() {System.out.println("Person object created!");}

public Person(String name, String city, int age) {super();this.name = name;this.city = city;this.age = age;}

// the combination of a setter/getter is called a property// for example, getName and setName adds to a property called// name (starting with a lowercase)public String getName() {return name;}

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

public String getCity() {return city;}

public void setCity(String city) {this.city = city;}

public int getAge() {return age;}

public void setAge(int age) {this.age = age;}

// emailAddress --> property

public String getEmailAddress() {return emailAddress;}

public void setEmailAddress(String emailAddress) {this.emailAddress = emailAddress;}

public Address getHomeAddress() {return homeAddress;}

public void setHomeAddress(Address homeAddress) {this.homeAddress = homeAddress;}

public void setFriends(List friends) {this.friends = friends;}

public List getFriends() {return friends;}

public void print() {System.out.printf("Name : %s\n", name);System.out.printf("Age : %d\n", age);System.out.printf("City : %s\n", city);System.out.printf("Email: %s\n", emailAddress);

if (homeAddress != null)homeAddress.print();if(friends!=null){System.out.println("Friends are...");for(Person p: friends){System.out.printf("\t%s (%s)\n", p.getName(), p.getCity());}}}

}

Address.java class:-

package com.training.exilant;

public class Address {private String street, area, city, state;public Address() {}

public String getStreet() {return street;}

public void setStreet(String street) {this.street = street;}

public String getArea() {return area;}

public void setArea(String area) {this.area = area;}

public String getCity() {return city;}

public void setCity(String city) {this.city = city;}

public String getState() {return state;}

public void setState(String state) {this.state = state;}

public void print(){System.out.printf("Street : %s\n", street);System.out.printf("Area : %s\n", area);System.out.printf("City : %s\n", city);System.out.printf("State : %s\n", state);}}

beans.xml:-

john

//it sets the value of friend list in the person class by setFriend method// there is lot of way to add in the list like either using of ref tag or directly put the bean inside the list tag.-----its Injection

Main class:-

package com.training.exilant;

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Training_example01 {public static void main(String[] args) {ApplicationContext ctx =new ClassPathXmlApplicationContext("beans.xml");Person p1 = (Person) ctx.getBean("p1");// here is no need to new create objects , beans.xml will take care of it,p1.print();}18/04/11 10:39 AM}

Required Jars files for the jdbc connection is:-

1.org.springframework.jdbc-3.0.4.RELEASE.jar2.org.springframework.transaction-3.0.4.RELEASE.jar3. hsqldb.jar

org.springframework.spring-library-3.0.4.RELEASE.libd---it is a binary file

The HSQLDB RDBMS and JDBC Driver provide the core functionality.

Running tools can be run in the standard way for archived Java classes. If hsqldb.jar is in the current directory, the command is

java -cp hsqldb.jar org.hsqldb.util.DatabaseManager

Hsqldb Server

This is the preferred way of running a database server and the fastest one. A proprietary communications protocol is used for this mode. A command similar to those used for running tools and described above is used for running the server. The following command is for starting the server starts the server with one (default) database with files named "nwind".

java -cp hsqldb.jar org.hsqldb.Server -dbname.0 nwind -database.0 file:nwind

We have nwind.script ,the script file which contains full of data.

Create one Category.java class,which contains some data members and corresponding setter/getter method.

package com.anyName.daoService;

public class Category {private int id;private String name;private String description;public int getId() {return id;}

public void setId(int id) {this.id = id;}

public String getName() {return name;}

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

public String getDescription() {return description;}

public void setDescription(String description) {this.description = description;}

public Category() {// TODO Auto-generated constructor stub}}

Create one NorthwindDAO.java interface,which contains some methods.

package com.anyName.daoService;import java.util.List;

public interface NorthwindDAO {public void addNewCategory(int id, String name, String desc);public void addNewCategory(Category c);public Category getCategory(int id);public List getAllCategories();

}

Create one class that implements the interface and all the methods of that interface are overridden here.

package com.anyName.daoService;

import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;

public class SprinhJdbcTemplateNorthWindDaoImpl implements NorthwindDAO {private JdbcTemplate template;public void setTemplate(JdbcTemplate template) {this.template = template;}

@Overridepublic void addNewCategory(int id, String name, String desc) {String sql="insert into categories(category_id,category_name,description) values (?,?,?)";template.update(sql,id,name,desc);// TODO Auto-generated method stub

}

@Overridepublic void addNewCategory(Category c) {addNewCategory(c.getId(), c.getName(), c.getDescription());// TODO Auto-generated method stub

}

@Overridepublic Category getCategory(int id) {// TODO Auto-generated method stubreturn null;}

@Overridepublic List getAllCategories() {// TODO Auto-generated method stubreturn null;}

}

Main class:-

package com.anyName.daoService;

import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Example01 {

/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");NorthwindDAO dao = (NorthwindDAO) ctx.getBean("dao1");try{dao.addNewCategory(99, "test123", "test123 desc");}catch (Exception e) {// TODO: handle exceptionSystem.out.println("Error");}System.out.println("Test New category added");

}

}

beans.xml:-

Anandmathur

Additional Jars files :-

1.org.springframework.web-3.0.4.RELEASE.jar2.org.springframework.expression-3.0.4.RELEASE.jar3.org.springframework.web.servlet-3.0.4.RELEASE.jar4. servlet-api.jar--for the servlet class

we have to create one views folder under the WEB-INF folder:-In this folder we have Hello.jsp file

Hello.jsp:-

MVC DEMO

MVC DEMO${msg} //here we have used the expression language

In the WebContent we are having index.jsp file:-

Index.jsp:-

Insert title here

click here

HelloController.java:-

package com.vinod.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

public class HelloController extends HttpServlet {private static final long serialVersionUID = 1L;//useful when object will go to sleep then it will show the error due to desrilazation will change.so it is req

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString model ="Hello from RAJ";//store the model in a scoperequest.setAttribute("msg", model);// forward to the view (JSP)String url="/WEB-INF/views/Hello.jsp";RequestDispatcher rd=request.getRequestDispatcher(url);rd.forward(request,response);}

}

HelloSpringController.java:-

package com.vinod.controller;

import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;

@Controllerpublic class HelloSpringController {@RequestMapping("/Hello") public ModelAndView Hello() {String modelData="Hell0 from Spring MVC";//View (name and location of JSP)String viewName ="/WEB-INF/views/Hello.jsp";ModelAndView mav=new ModelAndView(viewName,"msg",modelData);return mav; }}

web.xml:- The web.xml file provides configuration and deployment information for the web components that comprise a web application.

03_Spring_MVC_Basics index.html index.htm index.jsp default.html default.htm default.jsp HelloController HelloController com.vinod.controller.HelloController HelloController /HelloController DispatcherServlet DispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/beans.xml DispatcherServlet /spring/*

beans.xml:-

18/04/11 10:39 AM

Additional Jars files :-

1.jstl.jar2.standard.jar

CategoryController.java:-Here we have used annotation

package com.exilant.controllers;

import java.util.List;

import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;

@Controllerpublic class CategoryController {private NorthwindDAO dao;

public void setDao(NorthwindDAO dao) {this.dao = dao;}

@RequestMapping("/getCategory") public ModelAndView getCategoryIfo(@RequestParam("cat_id") int categoryId) {//model for the outputCategory cat=dao.getCategory(categoryId); //3 to be replacedString viewName="/WEB-INF/views/DisplayCategoryInfo.jsp";ModelAndView mav=new ModelAndView(viewName,"c",cat);return mav;}@RequestMapping("/listAllCategories")public ModelAndView getAllCategory(){ModelAndView mav= new ModelAndView();List categories = dao.getAllCategories();String viewName="/WEB-INF/views/DisplayAllCategories.jsp";mav.setViewName(viewName);mav.addObject("cats", categories);return mav;}@RequestMapping("/getProductCategory")public ModelAndView getProducts(int catId){ModelAndView mav =new ModelAndView();List products = dao.getProductCategory(catId);String viewName="/WEB-INF/views/DisplayProducts.jsp";mav.setViewName(viewName);mav.addObject("cat", products);return mav;}

}

Products.java:-

package com.exilant.controllers;

public class Products {

}

Before modifying the class we should know about the following:-

1.RowMappers -RowMappers are used to map the contents of a row in a ResultSet to the return type of an annotated method.

2.JdbcTemplate- The JdbcTemplate class is the central class in the JDBC core package.This class executes SQL queries, update statements or stored procedure calls, imitating iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package.JdbcTemplate class are threadsafe once configured. This is important because it means that you can configure a single instance of a JdbcTemplate and then safely inject this shared reference into multiple DAOs .JdbcTemplate is stateful, in that it maintains a reference to a DataSource, but this state is not conversational stateJdbcTemplate is created in the setter for the DataSource.

we have modified the SprinhJdbcTemplateNorthWindDaoImpl class and here it is:-

package com.exilant.controllers;

import java.sql.ResultSet;import java.sql.SQLException;import java.util.Collection;import java.util.List;import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;

public class SprinhJdbcTemplateNorthWindDaoImpl implements NorthwindDAO {public class CategoryRowMapper implements RowMapper {

@Overridepublic Category mapRow(ResultSet rs, int num) throws SQLException {// TODO Auto-generated method stubCategory c= new Category();c.setId(rs.getInt(1));c.setName(rs.getString(2));c.setDescription(rs.getString(3));return c;}

}public class ProductRowMapper implements RowMapper {

@Overridepublic Products mapRow(ResultSet rs, int num) throws SQLException {// TODO Auto-generated method stubProducts p= new Products();p.setProduct_id(rs.getInt(1));p.setProduct_name(rs.getString(2));//c.setId(rs.getInt(1));//c.setName(rs.getString(2));//c.setDescription(rs.getString(3));return p;}

}

private JdbcTemplate template;public void setTemplate(JdbcTemplate template) {this.template = template;}

//@Overridepublic void addNewCategory(int id, String name, String desc) {String sql="insert into categories(category_id,category_name,description) values (?,?,?)";template.update(sql,id,name,desc);// TODO Auto-generated method stub

}

@Overridepublic void addNewCategory(Category c) {addNewCategory(c.getId(), c.getName(), c.getDescription());// TODO Auto-generated method stub

}

@Overridepublic Category getCategory(int id) {// TODO Auto-generated method stubString sql="select * from categories where category_id="+id;return template.queryForObject(sql, new CategoryRowMapper());}

@Overridepublic List getAllCategories() {// TODO Auto-generated method stub//return template.queryForList("select * from categories");return template.query("select * from categories",new CategoryRowMapper());}

@Overridepublic List getProductCategory(int catId) {String sql="select * from products where category_id="+catId;return template.query(sql, new ProductRowMapper());// TODO Auto-generated method stub}

}

Now two html forms we are having in the Webcontent:-

GetCategoryForm.html:-

Get a category information

Get a category information

Enter the category id:

index.html:-

GHJKL

category

  • Get Category

  • all category

We need to create two jsp pages in a folder called views under WEB-INF

DisplayAllCategories.jsp:-

Insert title here

List of All categories Id Name Description ${cat.id} ${cat.name} ${cat.description}

DisplayCategoryInfo.jsp:-

Insert title here

hello

ID: ${c.id}
name: ${c.name}
description :${c.description}

Under WEB-INF we need to create the web.xml,s1-servlet.xml files.

web.xml:-

NorthwindApp_04 GetCategoryForm.html s1 s1 org.springframework.web.servlet.DispatcherServlet 1 s1 *.spring

s1-servlet.xml:-This xml file is named with the servlet name in the web.xml

5/20/2011 11:15:00 AM

Three more jsp pages we need to add in the views folder.

DisplayProducts.jsp:-

Insert title here

List of All Products Id Name

//expression language ${cat.product_id} ${cat.product_name}

Error.jsp:-

Insert title here

ERROR

NewCategoryForm.jsp:-

Insert title here

add new category

IDNameDescription:

10/05/11 6:46 PM

Additional Jars files :-

1.antlr-2.7.6.jar2.cglib-nodep-2.1_3.jar3.commons-fileupload.jar4.commons-io.jar5.dom4j-1.6.1.jar6.hibernate3.jar7.jta.jar

those jars are required for hibernate capabilities.

Now we need to create one mappings folder:-

In that folder we have employees.hbm.xml

Now we have added something in the index.html and the modified file is:-

GHJKL

category

  • Get Category

  • all category

  • create new category

  • All employee details

Enter the Employee id:

The modified jsp files under views are:-

DisplayAllCategories.jsp

Insert title here

List of All categories

ID: ${cat.id}

Name: ${cat.name}
Description: ${cat.description}

Id Name Supplier CategoryId quantity_per_unit unit_price unit_in_stock unit_on_order reorder_level discontinued

${cat.product_id} ${cat.product_name} ${cat.supplier_id} ${cat.id} ${cat.quantity_per_unit} ${cat.unit_price} ${cat.unit_in_stock} ${cat.unit_on_order} ${cat.reorder_level} ${cat.discontinued}

The new created jsp file is:-

DisplayAllEmployee.jsp

Insert title here

Employee list

Id lastName firstName title titleOfCourtesy birthDate hireDate address city region

${cat.id} ${cat.lastName} ${cat.firstName} ${cat.title} ${cat.titleOfCourtesy} ${cat.birthDate} ${cat.hireDate} ${cat.address} ${cat.city} ${cat.region}

DisplayEmployeeInfo.jsp

Employee Info

Employee Info Name ${emp.lastName},${emp.firstName} Date of Birth ${emp.birthDate} Date of join ${emp.hireDate}

DisplayProducts.jsp

Insert title here

List of All Products Id Name

${cat.product_id} ${cat.product_name}

only one property we have in the NewCategoryForm,jsp file

Insert title here

add new category

IDNameDescription:

Select the Picture:

Accordingly s1-servlet.xml we need to change:-we have to add extra bean id.

employees.hbm.xml

10/05/11 6:46 PM

Architectural benefits of Spring:-Before we get down to specifics, let's look at some of the benefits Spring can bring to a project:

1.> Spring can effectively organize your middle tier objects, whether or not you choose to use EJB. Spring takes care of plumbing that would be left up to you if you use only Struts or other frameworks geared to particular J2EE APIs. And while it is perhaps most valuable in the middle tier, Spring's configuration management services can be used in any architectural layer, in whatever runtime environment.

2.> Spring can eliminate the proliferation of Singletons seen on many projects. In my experience, this is a major problem, reducing testability and object orientation.

3.> Spring can eliminate the need to use a variety of custom properties file formats, by handling configuration in a consistent way throughout applications and projects. Ever wondered what magic property keys or system properties a particular class looks for, and had to read the Javadoc or even source code? With Spring you simply look at the class's JavaBean properties or constructor arguments. The use of Inversion of Control and Dependency Injection (discussed below) helps achieve this simplification.

4.> Spring can facilitate good programming practice by reducing the cost of programming to interfaces, rather than classes, almost to zero.

5.> Spring is designed so that applications built with it depend on as few of its APIs as possible. Most business objects in Spring applications have no dependency on Spring.

6.> Applications built using Spring are very easy to unit test.

7.> Spring can make the use of EJB an implementation choice, rather than the determinant of application architecture. You can choose to implement business interfaces as POJOs or local EJBs without affecting calling code.

8.> Spring helps you solve many problems without using EJB. Spring can provide an alternative to EJB that's appropriate for many applications. For example, Spring can use AOP to deliver declarative transaction management without using an EJB container; even without a JTA implementation, if you only need to work with a single database.

9.> Spring provides a consistent framework for data access, whether using JDBC or an O/R mapping product such as TopLink, Hibernate or a JDO implementation.

10.> Spring provides a consistent, simple programming model in many areas, making it an ideal architectural "glue." You can see this consistency in the Spring approach to JDBC, JMS, JavaMail, JNDI and many other important APIs.10/05/11 6:46 PM

MVC web framework:-

Spring includes a powerful and highly configurable MVC web framework.Spring's MVC model is most similar to that of Struts, although it is not derived from Struts. A Spring Controller is similar to a Struts Action in that it is a multithreaded service object, with a single instance executing on behalf of all clients. However, we believe that Spring MVC has some significant advantages over Struts. For example:

1.> Spring provides a very clean division between controllers, JavaBean models, and views.

2.> Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course we also provide convenience classes as an implementation option.Spring, like WebWork, provides interceptors as well as controllers, making it easy to factor out behavior common to the handling of many requests.

3.> Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it.

4.> Spring Controllers are configured via IoC like any other objects. This makes them easy to test, and beautifully integrated with other objects managed by Spring.

5.> Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the dispatcher servlet.

6.> The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all tiers of your application.

10/05/11 6:46 PM

10/05/11 6:46 PM

19/05/11 6:39 PM