1. Download the Spring package, the website is as follows
http://www.springframework.org/download.html
Decompressed directory contains DIST, LIB, etc.
2. Increase the Spring library in JBuilder 2005, select Menu Tools-Configure-Libraries, click the New button in the pop-up dialog box, enter the name of the Spring library: Spring, click the Add button to add all JAR files in the dist directory to Spring Library
3. New project files, select the menu file-new project, name to myProject to the project file
Set the properties of the project file, select the menu Project-Project Properties, select Tomcat as the server, join the Spring library to Path / Required Libraries. Because the log4j is used in the example, the library containing the log4j will be added to Path / Required Libraries, notice that there are two subdirectories LOG4J and JAKARTA-COMMONs in the lib directory, and their usage is different, as shown in the following code segment:
Log4j import org.apache.log4j.level;
Import org.apache.log4j.logger;
Public Class SpringAppController Implements Controller {
/ ** Logger for this class and subclasses * /
Static logger logger = logger.getlogger (SpringAppController.class);
Jakarta-commons import org.apache.commons.logging.log;
Import org.apache.commons.logging.logfactory;
Public Class SpringAppController Implements Controller {
/ ** Logger for this class and subclasses * /
Protected final log logger = logfactory.getlog (getclass ());
4. Create a new web module, select the menu file-new, named SpringApp to the web module
5. New Hello.jsp files are as follows:
<% @ Page ContentType = "Text / HTML; Charset = BIG5"%>
greetings. p>
body>
html>
6. New class files SpringAppController.java is as follows:
Package Spring;
Import Org.SpringFramework.Web.Servlet.mvc.controller;
Import org.springframework.Web.Servlet.ModelandView;
Import javax.servlet.servletException;
Import javax.servlet.http.httpservletRequest; import javax.servlet.http.httpservletResponse;
Import java.io.ioException;
// Import org.apache.commons.logging.log;
// Import org.apache.commons.logging.logfactory;
Import org.apache.log4j.level;
Import org.apache.log4j.logger;
Public Class SpringAppController Implements Controller {
/ ** Logger for this class and subclasses * /
// protected final log logger = logfactory.getlog (getClass ());
Static logger logger = logger.getlogger (SpringAppController.class);
Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)
Throws servletexception, ioException {
Logger.info ("SpringAppController - Returning Hello View");
Return New ModelandView ("Hello.jsp");
}
}
7. Modify the web.xml file
XML Version = "1.0" encoding = "UTF-8"?>
8. New springapp-servlet.xml files in the web-inflicity
XML Version = "1.0" encoding = "UTF-8"?>
"
- Application Context Definition for "SpringApp" DispatcherServlet.
->
SpringApp / War / Web-INF / JSP / include.jsp <% @ page session = "false"%> <% @ taglib prefix = "c" uri = "http://java.sun.com/jstl/core" %> <% @ taglib prefix = "fmt" URI = "http://java.sun.com/jstl/fmt"%> Using JSTL, Springapp / war / index.jsp <% @ include file = "/ web-inf / jsp / incrude.jsp"%> <% - redirected Because we can set the welcome page to a Virtual URL. -%> With JSTL SpringApp / War / Web-INF / JSP / HELLO.JSP <% @ include file = "/ web-inf / jsp / include.jsp"%> greetings, it is now springapp / src / SpringappController.java import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax. servlet.http.HttpServletResponse; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SpringappController implements Controller {/ ** Logger for this class and subclasses * / protected final Log logger = LogFactory.getLog (getClass ()); public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String now = (new java.util.Date ()) toString ();. logger .info ("Returning Hello View with" Now); Return New ModelandView ("Web-INF / JSP / HELLO.JSP", "now", now);}} 15. Browse the improved results http: // localhost: 8080 / SpringApp, first access index.jsp, then redirect to Hello.htm, then hand it over to Controller, Controller transfer the date and time to View. Can only test it in the browser. Setting Run Configuration in JBuilder2005 You cannot access http: // localhost: 8080 / springApp, but you can access http: // localhost: 8080 / SpringApp / index.jsp In the above example, Controller specifies the full path to the View so that there is unnecessary dependencies between Controller and View. To remove this dependency, we can define this dependence in the properties file in the property file, and we can use the InternalResourceViewResolver to set the prefix and suffix using the InternalResourceViewResolver to set the prefix and suffix. Modify file springapp-servlet.xml Include ViewResolver settings, we also choose to use JSTLVIEW, which allows us to combine JSTL and Message Resource Bundles, so you can support internationalization. SpringApp / War / Web-INF / SPRINGAPP-Servlet.xml XML Version = "1.0" Encoding = "UTF-8"?> <- - Application context definition for" springapp ". DispatcherServlet -> Now, we can remove the prefix and suffix of the View name in Controller. springapp / src / SpringappController.java import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax. servlet.http.HttpServletResponse; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SpringappController implements Controller {/ ** Logger for this class and subclasses * / protected final Log logger = LogFactory.getLog (getClass ()); public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String now = (new java.util.Date ()) toString ();. logger .info ("Returning Hello View with" Now); Return New ModelandView ("Hello", "Now", NOW);}} This modified example should still run. 16. Add commercial logic In order to separate web logic and business logic, we build two different packages, web and bus springapp / src / bus / Product.java package bus; import java.io.Serializable; public class Product implements Serializable {private String description; private Double price; public void setDescription (String s) {description = s;} public String getDescription ( ) {Return Description; PUBLIC VOID SETPRICE (Double D) {Price = D;} PUBLIC DOUBLE GETPRICE () {Return Price;}} springapp / src / bus / ProductManager.java package bus; import java.io.Serializable; import java.util.List; public class ProductManager implements Serializable {private List products; public void setProducts (List p) {products = p;} public List getProducts () {return products;} Modify SpringAppController.java springapp / src / web / SpringappController.java package web; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http. HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; import java.util.HashMap; import org.apache.commons.logging.Log; import org.apache.commons. logging.LogFactory; import bus.Product; import bus.ProductManager; public class SpringappController implements Controller {/ ** Logger for this class and subclasses * / protected final Log logger = LogFactory.getLog (getClass ()); private ProductManager prodMan; public ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String now = (new java.util.Date ()) toString ();. logger.info ( "returning hello view with" now); Map myModel = new Hashmap (); myModel.put ( "now", now); myModel.put ( "products", getProductManager () getProducts ().); return new ModelAndView ( "hello", "model", myModel);} public void setProductManager (ProductManager pm ) {Prodman = pm;} public productManager getProductManager () {return.com 17. Modify View to display business data, add support to Message Bundle SpringApp / War / Web-INF / JSP / HELLO.JSP <% @ include file = "/ web-inf / jsp / include.jsp"%> Hello - Spring Application h1>
Products h3>
c: forEach> body> html> 18. Add some test data
We are still not intended to increase the code, load the business object from the database. We only add BEAN and Messagesource settings in SpringApp-Servlet.xml to provide some test data and support for Messages Resource Bundle.
SpringApp / War / Web-INF / SPRINGAPP-Servlet.xml XML Version = "1.0" Encoding = "UTF-8"?>
/ Property>
SpringApp / War / Web-INF / CLASS / MESSAGES.PROPERTIES TITLE = SpringAppHeading = Hello :: SpringAppGreeting = Greetings, IT IS NOW
20. Browse improvements Http: // localhost: 8080 / SpringApp
Realize database persistence layer
21. Set the HSQL database, add the HSQL library in JBuilder2005, select Menu Tools-Configure-Libraries, click the New button in the pop-up dialog box, enter the name of the HSQL library: HSQL, click the Add button, will use the lib / hsqldb directory The file hsqldb.jar is added to the HSQL library.
Select Menu Enterprise-Enterprise Setup, select Database Drivers in the pop-up dialog box, press the Add button to increase the HSQL library. Select Menu Tools-Database Pilot, then select Menu Files-New Enter DRIVER: Org.hsqldb.jdbcdriver, URL: JDBC: HSQLDB: DB / TEST, Double-click HSQLDB: DB / Test, Enter username: SA, do not have to enter Passsword. Enter the following SQL statement and execute
CREATE TABLE PRODUCTS
ID Integer Not Null Primary Key,
Description varchar (255),
Price Decimal (15, 2)
);
CREATE INDEX Products_Description on Products (Description);
Insert Into Products (ID, Description, Price) VALUES (1, 'Lamp', 5.78);
INSERT INTO Products (ID, Description, Price) Values (2, 'Table', 75.29);
INSERT INTO Products (ID, Description, Price) Values (3, 'Chair', 22.81);
This will create a directory DB in the jbuilder_home / bin directory, and the data of the database TEST is stored.
22. Creating a JDBC DAO (Data Access Object) implementation
springapp / src / db / ProductManagerDao.java package db; import bus.Product; import java.util.List; public interface ProductManagerDao {public List getProductList (); public void increasePrice (Product prod, int pct);}
springapp / src / db / ProductManagerDaoJdbc.java package db; import bus.Product; import java.util.List; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import javax.sql. DataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.jdbc.object.MappingSqlQuery; import org.springframework.jdbc.object.SqlUpdate; import org.springframework .jdbc.core.SqlParameter; public class ProductManagerDaoJdbc implements ProductManagerDao {/ ** Logger for this class and subclasses * / protected final Log logger = LogFactory.getLog (getClass ()); private DataSource ds; public List getProductList () {logger. info ( "Getting products!"); ProductQuery pq = new ProductQuery (ds); return pq.execute ();} public void increasePrice (Product prod, int pct) {logger.info ( "Increasing price by" pct " % "); SQLUPDATE Su = New SQLUPDATE (DS," Update Products Set Price = Price * (100 ?) / 100 Where ID =? "); Su.DeclareParameter (" Increase "," INCREASE "," INCRESE "); Su.DeclareParameter (" ID ", Types.integer); Compile (); object [] OA = new object [2]; OA [0] = new integer (PCT); OA [1] = new integer (PROD); int count = su.update (OA) ; logger.info ( "Rows affected:" count);} public void setDataSource (DataSource ds) {this.ds = ds;} class ProductQuery extends MappingSqlQuery {ProductQuery (DataSource ds) {super (ds, "SELECT id, description Price from products ");
compile ();} protected Object mapRow (ResultSet rs, int rowNum) throws SQLException {Product prod = new Product (); prod.setId (rs.getInt ( "id")); prod.setDescription (rs.getString ( "description ")); Prod.setprice (NEW DOUBLE (" price "))))))); returnif;}}} springapp / src / bus / product.java package bus; import java.io.serializable; public class products implements Serializable {private int id; private String description; private Double price; public void setId (int i) {id = i;} public int getId () {return id;} public void setDescription (String s) {description = s; PUBLIC STRING GETDESCRIPTION () {Return Description; PUBLIC VOID SETPRICE (Double D) {Price = D;} PUBLIC DOUBLE GETPRICE ()}}}}
springapp / src / test / TestProductManagerDaoJdbc.java package tests; import java.util.List; import java.util.ArrayList; import junit.framework.TestCase; import org.springframework.jdbc.datasource.DriverManagerDataSource; import db.ProductManagerDaoJdbc; import bus.Product; public class TestProductManagerDaoJdbc extends TestCase {private ProductManagerDaoJdbc pmdao; public void setUp () {pmdao = new ProductManagerDaoJdbc (); DriverManagerDataSource ds = new DriverManagerDataSource (); ds.setDriverClassName ( "org.hsqldb.jdbcDriver"); ds. Seturl ("JDBC: HSQLDB: DB / TEST"); DS.SETUSERNAME ("sa"); ds.setpassword (""); pMDAO.SetDataSource (DS);} public void testProductList () {list l = pmdao.getProductList (); Product P1 = (Product) L.GET (0); Assertequals ("LAMP", P1.GetDescription ()); Product P2 = (Product) L.GET (1); Assertequals ("Table", P2. GetDescription ());} public void testincreaseprice () { List l1 = pmdao.getProductList (); Product P1 = (product) l1.get (0); Assertequals (New Double ("5.78"), P1.GetPrice ()); PMDAO.IncReaseprice (P1, 10); List L2 = PMDAO.GETPRODUCTLIST (); Product P2 = (Product) L2.GET (0); Assertequals (New Double ("6.36"), P2.GetPrice ());}} 23. Modify the web application to use database persistence
springapp / src / bus / ProductManager.java package bus; import java.io.Serializable; import java.util.ListIterator; import java.util.List; import db.ProductManagerDao; public class ProductManager implements Serializable {private ProductManagerDao pmd; private List products; public void setProductManagerDao (ProductManagerDao pmd) {this.pmd = pmd;} / * public void setProducts (List p) {products = p;} * / public List getProducts () {products = pmd.getProductList (); return products PUBLIC VOID INCRESEPRICE (INT PCT) {Listiterator Li = Products.Listiterator (); while (li.hasnext ()) {product (); / * double newprice = p.Getprice () .doublevalue () * (100 PCT) / 100; P.SETPRICE (New Double (NewPrice)); * / PMD.IncReaseprice (p, pct);}}}
SpringApp / War / Web-INF / SPRINGAPP-Servlet.xml XML Version = "1.0" Encoding = "UTF-8"?>
/ Property> bean>
Bean id = "product2" class = "bus.product">
Springapp / src / tests / web-inf / springapp-servlet.xml xml version = "1.0" encoding = "UTF-8"?>