1. Download the Spring package, the URL 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 ModelAndView handleRequest (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException. {logger.info ( "SpringappController - returning hello view"); return new ( "hello.jsp") ModelAndView;}} 7 modify the web.xml file
XML Version = "1.0" encoding = "UTF-8"?>
XML Version = "1.0" encoding = "UTF-8"?>
log4j.rootCategory = INFO, stdout, logfilelog4j.appender.stdout = org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout = org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern =% d% p [% c] - <% m>% nlog4j.appender.logfile org.apache.log4j.RollingFileAppenderlog4j.appender.logfile.File springapp.loglog4j.appender.logfile.MaxFileSize = 512KB # Keep three backup fileslog4j.appender.logfile.MaxBackupIndex = = = 3log4j.appender.logfile.layout = org.apache.log4j.PatternLayout # Pattern to output: date priority [category] -
10. Set the web module SpringApp's property Content, add file log4j.properties, because the classes directory is automatically generated, this step is to add file log4j.properties to the classes directory. 11. Set the Run Configuration, select the menu Run-Configurations, create a new Run Configuration, Type selection server, launch URI set to: /springapp/hello.htm, name Hello 12. Run, you will look at the Messages window To the following information: News: Server Startup in 9253 MS2004-11-05 15: 05: 00, 585 info [Spring.SpringAppController] -
<% @ Include file = "/ web-inf / jsp / include.jsp"%> <% - redirected Because We can't set the welcome page to a virtual url. -%> greetings, it is now 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);" Web-INF / JSP / HELLO.JSP "," NOW ", NOW);}} 15. Browse improvements Http: // localhost: 8080 / springApp, first access Index.jsp, then redirect to Hello.htm, then handle the control to the controller, Controller transfer the date and time to View. Can only test it in the browser. Setting Run Configuration in JBuilder2005 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, making Controller There is unnecessary dependence between the 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"?> springapp / src / SpringappController.javaimport 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 business logic to separate web logic and business logic, we build two different packages, web and bus springapp / src / bus / products, import java.io.serializable; public class product imports serializable {productive 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 prodMan;}} 17. View to display the modified business data, increased message Bundle's support 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. we now add further test data 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 name = "description">
Title = SpringAppHeading = Greetings, IT IS NOW 20. Browse improvements HTTP: // localhost: 8080 / springApp Implement database persistence 21. Set HSQL database, add HSQL libraries 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 to add filesqldb.jar in the lib / hsqldb directory 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. Input and execute the following SQL statements 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, 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, store Database Test data 22. Create JDBC DAO (Data Access Object) to implement 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", Types.integer); Su.Declare Parameter ("ID", Types.integer); Su.compile (); Object [] OA = New Object [2]; OA [0] = New Integer (PCT); OA [1] = New Integer ()); 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 "))))); returnified,}}} springapp / src / bus / product.javaPackage bus; import java.io.serializable; Public Class Product 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 () {return price;}} 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 TestinCreasepricePrice () {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 P 2 = (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 increasePrice (int pct) {Listiterator Li = Products.Listiterator (); while (li.hasnext ()) {Product P = () li.next (); / * double newprice = p.getPrice (). DoubleValue () * (100 PCT ) /100q; new double (new price)); * / pmd.increaseprice (p, pct);}}} springapp / war / web-inf / springapp-servlet.xml
XML Version = "1.0" encoding = "UTF-8"?>
/ Property>
Property name = "description">
XML Version = "1.0" encoding = "UTF-8"?>
Value> 5.75 value> property> bean>