Develop Spring MVC applications with jbuilder2005
Gaoke Hua
About the author: Gao Jinghua, Nanjing Aviation College computing a master's degree in mathematics, more than ten years of corporate informationization work experience. Current research interest, J2EE enterprise application, ERP software research and development, data warehouse system research and development.
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"?>
servlet>
servlet-maping>
Index.jsp
welcome-file>
welcome-file-list>
web-app>
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/jsp/jstl/core"%> <% @ taglib prefix = "fmt" URI = "http://java.sun.com/jsp/jstl/fmt"%> Using JSTL, Springapp / War / INDEX.JSP <% @ include file = "/ web-inf / jsp / incrude.jsp"%> <% - Redirected Because We can't set the welcome page to a Virtual URL. -%> With JSTL SpringApp / War / Web-INF / JSP / HELLO.JSP <% @ include file = "/ web-inf / jsp / incrude.jsp"%>
Greetings, IT is now
p>
body>
html>
Increase string containing the current date and time in SpringAppController.java as Model
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 ModlandView 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.
->
bean>
beans>
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 ModlandView 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 product;
Public ModlandView 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. Modify View to display business data, add support to Message Bundle
SpringApp / War / Web-INF / JSP / HELLO.JSP
<% @ include file = "/ web-inf / jsp / incrude.jsp"%>
p>
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"?>
- Application Context Definition for "SpringApp" DispatcherServlet.
->
Property>
bean>
list>
Property>
bean>
bean>
bean>
bean>
bean>
bean>
beans>
19. Add Message Bundle
SpringApp / War / Web-INF / CLASS / MESSAGES.PROPERTIES
Title = SpringApp
Heading = hello :: SpringApp
Greeting = 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 NTEGER 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" "%"); SQLUPDATE SU = New SQLUPDATE (DS, "Update Products Set Price = Price * (100 ) / 100 WHERE ID =? "); Su.DeclareParameter (" Increase ", Types.integer); Su.DeclareParameter (" ID ", Types.integer); Su.compile (); Object [ ] OA = New Object [2]; OA [0] = New Integer (PCT); OA [1] = new integer (pROUNT = 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.getin)); prod.setdescription (Rs.getstring ("description")); prod .Setprice (NEW DOUBLE ("Price"))); Return Prod;
}
}
Springapp / src / bus / product.java package bus;
Import java.io.serializable;
Public Class Product Implements Serializable {
Private int id; private string description; private video design; 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 pmda;
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 testgetProductList () {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); ask 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 the database persistence layer
Springapp / src / bus / productmanager.javaPackage 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 increasepric (int PCT) {listiterator Li = products.listiterator (); while (li.hasnext ()) {Product P = () li.next (); / * double newprice = p.getPrice (). DoubleValue () * (100 PCT) / 100; P.SETPRICE (New Double (new price)); * / pmd.increaseprice (p, pct);}}
}
SpringApp / War / Web-INF / SPRINGAPP-Servlet.xml XML Version = "1.0" Encoding = "UTF-8"?>
Springapp / src / tests / mockproductmanagerdaoImpl.javaPackage tests;
Import bus.product; import java.util.list; import db.productmanagerdao; import bus.product;
Public Class MockProductManagerDaoImpl Implements ProductManagerdao {
PRIVATE LIST PRODUCTS;
Public void setProducts (list p) {product = p;}
Public List getProductList () {Return Products;
Public Void Increaseprice (Product Prod, INT PCT) {Double NewPrice = Product.getPrice (). DoubleValue () * (100 PCT) / 100; prod.setprice (new Double (new price));}
}
Springapp / src / tests / web-inf / springapp-servlet.xml xml version = "1.0" encoding = "UTF-8"?> " ~ - - Application Context definition for "SpringApp" dispatcherservlet. ->
beans>
Springapp / src / tests / testproductmanager .java package tests;
Import java.util.list; import junit.framework.testcase; import db.productManagerDao; import bus.productmanager; import bus.product;
Public Class TestProductManager Extends Testcase {
Private productManager PM;
Public void setup () {pm = new productManager (); product p = new product (); p.setdescription ("chair"); P.SETPRICE (New Double ("20.50"); arraylist al = new arraylist () Al.Add (p); p = new product (); p.setdescription ("Table"); P.SETPRICE (New Double ("150.10"); al.add (p); / * pm.setProducts al); * / MockProductManagerDaoImpl pmdao = new MockProductManagerDaoImpl (); pmdao.setProducts (al); pm.setProductManagerDao (pmdao); pm.getProducts ();} public void testGetProducs () {List l = pm.getProducts (); Product P1 = (product) L.GET (0); Assertequals ("chair", p1.getdescription ()); Product P2 = (Product) L.GET (1); Assertequals ("Table", p2.getdescription ()) }
Public void testincreaseprice () {pm.increaseprice (10); list l = pm.getProducts (); product p = (product) L.GET (0); Assertequals (New Double ("22.55"), p.GetPrice () ); P = (product) L.GET (1); Assertequals (New Double ("165.11"), p.Getprice ());}
}
Reference resources:
http://www.springframework.org/docs/mvc-step-cy-step/spring-mvc-step-s-step.html