Develop Spring MVC applications with jbuilder2005

xiaoxiao2021-03-06  77

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"%>

eXample :: spring application </ title> </ head></p> <p><body></p> <p><H1> Hello - Spring Application </ h1></p> <p><p> greetings. </ p></p> <p></ body></p> <p></ html></p> <p>6. New class files SpringAppController.java is as follows:</p> <p>Package Spring;</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller; import org.springframework.web.servlet.modelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>// Import org.apache.commons.logging.log;</p> <p>// Import org.apache.commons.logging.logfactory;</p> <p>Import org.apache.log4j.level;</p> <p>Import org.apache.log4j.logger;</p> <p>Public Class SpringAppController Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>// protected final log logger = logfactory.getlog (getClass ());</p> <p>Static logger logger = logger.getlogger (SpringAppController.class);</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>Logger.info ("SpringAppController - Returning Hello View");</p> <p>Return New ModelandView ("Hello.jsp");</p> <p>}</p> <p>}</p> <p>7. Modify the web.xml file</p> <p><? XML Version = "1.0" encoding = "UTF-8"?></p> <p><! Doctype web-app public '- // sun microsystems, Inc.//dtd Web Application 2.3 // en' 'http://java.sun.com/dtd/web-app_2_3.dtd'></p> <p><web-app></p> <p><servlet></p> <p><servlet-name> SpringApp </ servlet-name></p> <p><servlet-class> Org.springframework.web.servlet.dispatcherServlet </ servlet-class></p> <p><load-on-startup> 1 </ load-on-startup></p> <p></ servlet></p> <p><servlet-mapping></p> <p><servlet-name> SpringApp </ servlet-name></p> <p><url-pattern> *. htm </ url-pattern></p> <p></ servlet-maping></p> <p><Welcome-file-list></p> <p><Welcome-File></p> <p>Index.jsp</p> <p></ welcome-file></p> <p></ welcome-file-list></p> <p></ web-app></p> <p>8. New springapp-servlet.xml files in the web-inflicity</p> <p><? XML Version = "1.0" encoding = "UTF-8"?> <! doctype beans public "- // Spring // DTD bean //" http://www.springframework.org/dtd/spring- Beans.dtd "></p> <p><! -</p> <p>- Application Context Definition for "SpringApp" DispatcherServlet.</p> <p>-></p> <p><beans></p> <p><bean id = "SpringAppController" class = "Spring.springAppController" /></p> <p><bean id = "urlmapping" class = "org.springframework.web.servlet.Handler.SIMPLEURLHANDLERMAPPING"></p> <p><Property Name = "MAppings"></p> <p><PrOPS></p> <p><prop key = "/ hello.htm> SpringAppController </ prop></p> <p></ prOPS></p> <p></ Property></p> <p></ bean></p> <p></ beans></p> <p>9. New log4j.properties file in the web-inflicity is as follows:</p> <p>Log4j.rootcategory = info, stdout, logfile</p> <p>Log4j.appender.stdout = org.apache.log4j.consoleAppender</p> <p>Log4j.Appender.stdout.Layout = Org.apache.log4j.patternlayout</p> <p>Log4j.Appender.stdout.Layout.conversionPattern =% D% p [% C] - <% m>% N</p> <p>Log4j.Appender.logfile = org.apache.log4j.rollingfileappender</p> <p>Log4j.Appender.logfile.file = Springapp.log</p> <p>Log4j.Appender.logfile.maxfilesize = 512KB</p> <p># Keep Three Backup Files</p> <p>Log4j.Appender.logfile.maxbackupindex = 3</p> <p>Log4j.Appender.logfile.Layout = org.apache.log4j.patternlayout</p> <p>#Pattern to output: Date Priority [category] - <message> line_separator</p> <p>Log4j.Appender.logfile.Layout.conversionPattern =% D% p [% C] - <% m>% N</p> <p>10. Set the web module SpringApp's property content, join the file log4j.properties, because the classes directory is automatically generated, this step is to add file log4j.properties to the web-inf / class directory. Note Check the path to the file.</p> <p>11. Set the Run Configuration, select the menu Run-Configurations, create a new Run Configuration, Type selection server, the launch URI is set to: /springapp/hello.htm, give it name Hello12. Run, you will see in the Messages window The following information:</p> <p>Information: Server Startup in 9253 MS</p> <p>2004-11-05 15: 05: 00, 585 Info [Spring.SpringAppController] - <SpringAppController - Returning Hello View></p> <p>2004/11/5 03:05:00 Org.springframework.web.servlet.view.abstractCachingViewResolver ResolveviewName</p> <p>Information: Cached View 'Hello.jsp'</p> <p>In the MyProject / Tomcat / SpringApp.log file, the line is as follows:</p> <p>2004-11-05 15: 11: 32,348 info [Spring.SpringAppController] - <SpringAppController - Returning Hello View></p> <p>This shows that you have successfully established basic Spring applications.</p> <p>13. Increase the support of JSTL, set the properties of the project file, select the menu Project-Project Properties, join the JSTL library to Path / Required Libraries.</p> <p>14. Improve the previous example, the improved documents are as follows:</p> <p>Increase the "Header" file include.jsp, which is a common part of some JSP files, which makes it easier for development and maintenance. All JSP files are placed in a web-INF / JSP directory, which is only Controller to access View.</p> <p>SpringApp / War / Web-INF / JSP / INCLUDE.JSP</p> <p><% @ Page session = "false"%></p> <p><% @ taglib prefix = "c" URI = "http://java.sun.com/jsp/jstl/core"%></p> <p><% @ taglib prefix = "fmt" URI = "http://java.sun.com/jsp/jstl/fmt"%></p> <p>Using JSTL, <C: Redirect> Redirects the page to Controller, which has established connection between Index.jsp and application architecture.</p> <p>Springapp / War / INDEX.JSP</p> <p><% @ include file = "/ web-inf / jsp / incrude.jsp"%></p> <p><% - Redirected Because We can't set the welcome page to a Virtual URL. -%></p> <p><c: redirect url = "/ hello.htm" /></p> <p>With JSTL <C: OUT> tag, the current date and time passed from Model delivery to the current date and time of the VIEW.</p> <p>SpringApp / War / Web-INF / JSP / HELLO.JSP</p> <p><% @ include file = "/ web-inf / jsp / incrude.jsp"%></p> <p><html></p> <p><head> <title> Hello :: Spring Application </ Title> </ hEAD></p> <p><body></p> <p><H1> Hello - Spring Application </ h1></p> <p><p> Greetings, IT is now <c: out value = "$ {now}" /></p> <p></ p></p> <p></ body></p> <p></ html></p> <p>Increase string containing the current date and time in SpringAppController.java as Model</p> <p>Springapp / src / SpringAppController.java</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller;</p> <p>Import org.springframework.Web.Servlet.ModelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>Import org.apache.commons.logging.log;</p> <p>Import org.apache.commons.logging.logfactory;</p> <p>Public Class SpringAppController Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>Protected final log logger = logfactory.getlog (getclass ());</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>String now = (New java.util.date ()). TOSTRING ();</p> <p>Logger.info ("Returning Hello View with" Now);</p> <p>Return New ModelandView ("Web-INF / JSP / HELLO.JSP", "now", now)</p> <p>}</p> <p>}</p> <p>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.</p> <p>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</p> <p>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</p> <p><? XML Version = "1.0" encoding = "UTF-8"?></p> <p><! Doctype beans public "- // Spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd"></p> <p><! -</p> <p>- Application Context Definition for "SpringApp" DispatcherServlet.</p> <p>-></p> <p><beans></p> <p><bean id = "SpringAppController" class = "springappcontroller" /></p> <p><bean id = "urlmapping" class = "org.springframework.web.servlet.Handler.SIMPLEURLHANDLERMAPPING"></p> <p><Property Name = "MAppings"></p> <p><PrOPS></p> <p><prop key = "/ hello.htm> SpringAppController </ prop></p> <p></ prOPS></p> <p></ Property></p> <p></ bean></p> <p><bean id = "ViewResolver" class = "org.springframework.web.servlet.view.internalResourceViewResolver"></p> <p><property name = "viewclass"> <value> org.springframework.web.servlet.view.jstlview </ value> </ property></p> <p><Property Name = "prefix"> <value> / web-inf / jsp / </ value> </ property></p> <p><Property Name = "SUFFIX"> <value> .jsp </ value> </ property></p> <p></ bean></p> <p></ beans></p> <p>Now, we can remove the prefix and suffix of the View name in Controller.</p> <p>Springapp / src / SpringAppController.java</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller; import org.springframework.web.servlet.modelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>Import org.apache.commons.logging.log;</p> <p>Import org.apache.commons.logging.logfactory;</p> <p>Public Class SpringAppController Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>Protected final log logger = logfactory.getlog (getclass ());</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>String now = (New java.util.date ()). TOSTRING ();</p> <p>Logger.info ("Returning Hello View with" Now);</p> <p>Return New ModelandView ("Hello", "NOW", NOW;</p> <p>}</p> <p>}</p> <p>This modified example should still run.</p> <p>16. Add commercial logic</p> <p>In order to separate web logic and business logic, we build two different packages, web and bus</p> <p>SpringApp / src / bus / product.java</p> <p>Package bus;</p> <p>Import java.io.serializable;</p> <p>Public Class Product Implements Serializable {</p> <p>Private string description;</p> <p>PRIVATE DOUBLE PRICE;</p> <p>Public void setdescription (String s) {</p> <p>Description = S;</p> <p>}</p> <p>Public string getdescription () {</p> <p>Return description;</p> <p>}</p> <p>Public void setprice (double d) {</p> <p>Price = d;</p> <p>}</p> <p>Public double getprice () {</p> <p>Return Price;</p> <p>}</p> <p>}</p> <p>Springapp / src / bus / productmanager.java</p> <p>Package bus;</p> <p>Import java.io.serializable;</p> <p>Import java.util.list;</p> <p>Public Class ProductManager IMPLEments Serializable {</p> <p>PRIVATE LIST PRODUCTS;</p> <p>Public void setProducts (List P) {</p> <p>Products = P;</p> <p>}</p> <p>Public List getProducts () {</p> <p>Return Products;</p> <p>}</p> <p>}</p> <p>Modify SpringAppController.java</p> <p>SpringApp / src / Web / SpringAppController.java</p> <p>Package web;</p> <p>Import Org.SpringFramework.Web.Servlet.mvc.controller; import org.springframework.web.servlet.modelandView;</p> <p>Import javax.servlet.servletException;</p> <p>Import javax.servlet.http.httpservletRequest;</p> <p>Import javax.servlet.http.httpservletResponse;</p> <p>Import java.io.ioException;</p> <p>Import java.util.map;</p> <p>Import java.util.hashmap;</p> <p>Import org.apache.commons.logging.log;</p> <p>Import org.apache.commons.logging.logfactory;</p> <p>Import bus.product;</p> <p>Import Bus.ProductManager;</p> <p>Public Class SpringAppController Implements Controller {</p> <p>/ ** Logger for this class and subclasses * /</p> <p>Protected final log logger = logfactory.getlog (getclass ());</p> <p>Private productManager product;</p> <p>Public ModlandView HandleRequest (httpservletRequest Request, HttpservletResponse Response)</p> <p>Throws servletexception, ioException {</p> <p>String now = (New java.util.date ()). TOSTRING ();</p> <p>Logger.info ("Returning Hello View with" Now);</p> <p>Map mymodel = new hashmap ();</p> <p>MyModel.Put ("now", now);</p> <p>MyModel.put ("Products", getProductManager (). getProducts ());</p> <p>Return New ModelandView ("Hello", "Model", MyModel;</p> <p>}</p> <p>Public Void SetProductManager (ProductManager PM) {</p> <p>PRODMAN = PM;</p> <p>}</p> <p>Public productManager getProductManager () {</p> <p>Return Prodman</p> <p>}</p> <p>}</p> <p>17. Modify View to display business data, add support to Message Bundle</p> <p>SpringApp / War / Web-INF / JSP / HELLO.JSP</p> <p><% @ include file = "/ web-inf / jsp / incrude.jsp"%></p> <p><html></p> <p><head> <title> <fmt: message key = "title" /> </ title> </ head></p> <p><body></p> <p><h1> <fmt: message key = "Heading" /> </ h1></p> <p><p> <fmt: message key = "greeting" /> <c: out value = "$ {model.now}" /></p> <p></ p></p> <p><h3> Products </ h3> <c: foreach items = "$ {model.products}" var = "prod"></p> <p><C: out value = "$ {prod.description}" /> <i> $ <c: out value = "$ {prod.price}" /> </ i> <br> <br></p> <p></ c: foreach></p> <p></ body></p> <p></ html></p> <p>18. Add some test data</p> <p>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.</p> <p>SpringApp / War / Web-Inf / SpringApp-Servlet.xml</p> <p><? XML Version = "1.0" encoding = "UTF-8"?></p> <p><! Doctype beans public "- // Spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd"></p> <p><! -</p> <p>- Application Context Definition for "SpringApp" DispatcherServlet.</p> <p>-></p> <p><beans></p> <p><bean id = "SpringAppController" class = "Web.SpringAppController"></p> <p><property name = "productManager"></p> <p><ref bean = "prodman" /></p> <p></ Property></p> <p></ bean></p> <p><bean id = "prodman" class = "bus.productmanager"></p> <p><Property Name = "Products"></p> <p><List></p> <p><ref bean = "product1" /></p> <p><ref bean = "product2" /></p> <p><ref bean = "product3" /></p> <p></ list></p> <p></ Property></p> <p></ bean></p> <p><bean id = "product1" class = "bus.product"></p> <p><Property Name = "Description"> <value> Lamp </ value> </ property></p> <p><proty name = "price"> <value> 5.75 </ value> </ property></p> <p></ bean></p> <p><bean id = "product2" class = "bus.product"></p> <p><Property Name = "Description"> <value> Table </ value> </ property> <property name = "price"> <value> 75.25 </ value> </ printtle></p> <p></ bean></p> <p><bean id = "product3" class = "bus.product"></p> <p><Property Name = "Description"> <value> chair </ value> </ property></p> <p><Property Name = "Price"> <value> 22.79 </ value> </ property></p> <p></ bean></p> <p><bean id = "messagesource" class = "org.springframework.context.support.resourceBundleMessages"></p> <p><Property Name = "BaseName"> <value> message </ value> </ property></p> <p></ bean></p> <p><bean id = "urlmapping" class = "org.springframework.web.servlet.Handler.SIMPLEURLHANDLERMAPPING"></p> <p><Property Name = "MAppings"></p> <p><PrOPS></p> <p><prop key = "/ hello.htm> SpringAppController </ prop></p> <p></ prOPS></p> <p></ Property></p> <p></ bean></p> <p><bean id = "ViewResolver" class = "org.springframework.web.servlet.view.internalResourceViewResolver"></p> <p><property name = "viewclass"> <value> org.springframework.web.servlet.view.jstlview </ value> </ property></p> <p><Property Name = "prefix"> <value> / web-inf / jsp / </ value> </ property></p> <p><Property Name = "SUFFIX"> <value> .jsp </ value> </ property></p> <p></ bean></p> <p></ beans></p> <p>19. Add Message Bundle</p> <p>SpringApp / War / Web-INF / CLASS / MESSAGES.PROPERTIES</p> <p>Title = SpringApp</p> <p>Heading = hello :: SpringApp</p> <p>Greeting = Greetings, IT IS NOW</p> <p>20. Browse improvements Http: // localhost: 8080 / SpringApp</p> <p>Realize database persistence layer</p> <p>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.</p> <p>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</p> <p>CREATE TABLE PRODUCTS</p> <p>ID Integer NTEGER NULL PRIMARY Key,</p> <p>Description varchar (255),</p> <p>Price Decimal (15, 2)</p> <p>);</p> <p>CREATE INDEX Products_Description on Products (Description);</p> <p>INSERT INTO Products (ID, Description, Price) Values ​​(1, 'Lamp', 5.78); Insert Into Products (ID, Description, Price) VALUES (2, 'Table', 75.29);</p> <p>INSERT INTO Products (ID, Description, Price) Values ​​(3, 'Chair', 22.81);</p> <p>This will create a directory DB in the jbuilder_home / bin directory, and the data of the database TEST is stored.</p> <p>22. Creating a JDBC DAO (Data Access Object) implementation</p> <p>Springapp / src / db / productmanagerdao.java package db;</p> <p>Import bus.product; import java.util.list;</p> <p>Public interface productManagerdao {</p> <p>Public List getProductList ();</p> <p>Public Void Increaseprice (Product Prod, INT PCT);</p> <p>}</p> <p>SpringApp / SRC / DB / ProductManagerDaojdbc.java package db;</p> <p>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;</p> <p>Public Class ProductManagerdaojdbc Implements ProductManagerdao {</p> <p>/ ** Logger for this class and subclasses * / protected final log logger = logfactory.getlog (getclass ()); private DataSource DS;</p> <p>Public List getProductList () {Logger.info ("getting products!"); ProductQuery PQ = New ProductQuery (DS); Return Pq.execute ();</p> <p>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);</p> <p>Public void setDataSource (DataSource DS) {this.ds = ds;}</p> <p>Class ProductQuery Extends MappingsqlQuery {</p> <p>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;</p> <p>}</p> <p>}</p> <p>Springapp / src / bus / product.java package bus;</p> <p>Import java.io.serializable;</p> <p>Public Class Product Implements Serializable {</p> <p>Private int id; private string description; private video design; public void setid (int i) {id = i;}</p> <p>Public int getId () {return id;}</p> <p>Public void setdescription (string s) {description = s;}</p> <p>Public string getDescription;} {Return Description;</p> <p>Public void setprice (double d) {price = d;</p> <p>Public Double getprice () {return price;}</p> <p>}</p> <p>Springapp / src / test / testproductmanagerdaojdbc.java package tests;</p> <p>import java.util.List; import java.util.ArrayList; import junit.framework.TestCase; import org.springframework.jdbc.datasource.DriverManagerDataSource; import db.ProductManagerDaoJdbc; import bus.Product;</p> <p>Public class testproductmanagerdaojdbc extends testcase {</p> <p>Private productmanagerdaojdbc pmda;</p> <p>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);</p> <p>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 ());</p> <p>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 ());}}</p> <p>23. Modify the web application to use the database persistence layer</p> <p>Springapp / src / bus / productmanager.javaPackage bus;</p> <p>Import java.io.serializable; import java.util.listiterator; import java.util.list; import db.productmanagerdao;</p> <p>Public Class ProductManager IMPLEments Serializable {</p> <p>Private ProductManagerDao PMD; Private List Products;</p> <p>Public void setProductManagerDao (ProductManagerDao PMD) {this.pmd = pmd;}</p> <p>/ * Public void setProducts (list p) {products = p;} * /</p> <p>Public List GetProducts () {products = pmd.getProductList (); Return Products;</p> <p>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);}}</p> <p>}</p> <p>SpringApp / War / Web-INF / SPRINGAPP-Servlet.xml <? XML Version = "1.0" Encoding = "UTF-8"?> <! doctype beans public "- // Spring // DTD bean // en" "http : //www.springframework.org/dtd/spring-beans.dtd "></p> <p><! - Application Context Definition for "SpringApp" dispatcherServlet. -></p> <p><beans></p> <p><! - Controller for the initial "hello" page -> <bean id = "springappcontroller" class = "Web.SpringAppController"> <property name = "productManager> <ref bean =" prodman "/> </ printy > </ Bean> <! - Validator and form -> <bean id = "priceincreasevalidator" class = "bus.priceincreasevalidator" /> <bean id = "priceIncreaseform" class = "Web .PriceIncreaseFormController "> <property name =" sessionForm "> <value> true </ value> </ property> <property name =" commandName "> <value> priceIncrease </ value> </ property> <property name =" commandClass "> <value> bus.priceincrease </ value> </ proty> <property name =" validator "> <ref bean =" priceincreasevaliDator "/> </"> <property name = "formview> <value> priceIncrease < / value> </ proty> <property name = "surcessView"> <value> hello.htm </ value> </ proty> <property name = "productManager> <ref bean =" prodman "/> </ property> </ bean></p> <p><Bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name = "driverClassName"> <value> org.hsqldb.jdbcDriver </ value> </ property> <property name = " URL> <value> jdbc: hsqldb: / home / trisberg / workspace / springapp / db / test </ value> </ proty> <property name = "username"> <value> sa </ value> </ printty> <Property Name = "Password"> <value> </ value> </ property> </ bean> <bean id = "prodmandao" class = "db.productmanagerdaojdbc"> <property name = "datasource> <ref bean = "DataSource" /> </ property> </ bean></p> <p><bean id = "prodman" class = "bus.productmanager"> <property name = "productManagerdao"> <ref bean = "prodmandao" /> <property name = "products"> <list > <Ref bean = "product1" /> <ref bean = "product2" /> <ref bean = "product3" /> </ list> </ property> -> </ bean> <! - <bean id = "Product1" class = "bus.product"> <property name = "description"> <value> lamp </ value> </ property> <property name = "price"> <value> 5.75 </ value> </ Property> </ bean> <bean id = "product2" class = "bus.product"> <property name = "description"> <value> table </ value> </ property> <property name = "price"> < Value> 75.25 </ value> </ proty> </ bean> <bean id = "product3" class = "bus.product"> <property name = "description"> <value> chair </ value> </ property> <Property Name = "Price"> <value> 22.79 </ value> </ property> </ bean> -></p> <p><bean id = "messagesource" class = "org.springframework.context.support.resourcebundleMessages"> <property name = "basename"> <value> message </ value> </ property> </ bean>></p> <p><Bean id = "urlMapping" class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name = "mappings"> <props> <prop key = "/ hello.htm"> springappController </ prop> <prop key = "/ priceincrease.htm"> priceIncreaseForm </ prop> </ props> </ property> </ bean> <bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" > <Property Name = "ViewClass"> <value> org.springframework.web.servlet.view.jstlview </ value> </ property> <property name = "prefix"> <value> / web-inf / jsp / < / value> </ proty> <property name = "suffix"> <value> .jsp </ value> </ property> </ bean> </ beans></p> <p>Springapp / src / tests / mockproductmanagerdaoImpl.javaPackage tests;</p> <p>Import bus.product; import java.util.list; import db.productmanagerdao; import bus.product;</p> <p>Public Class MockProductManagerDaoImpl Implements ProductManagerdao {</p> <p>PRIVATE LIST PRODUCTS;</p> <p>Public void setProducts (list p) {product = p;}</p> <p>Public List getProductList () {Return Products;</p> <p>Public Void Increaseprice (Product Prod, INT PCT) {Double NewPrice = Product.getPrice (). DoubleValue () * (100 PCT) / 100; prod.setprice (new Double (new price));}</p> <p>}</p> <p>Springapp / src / tests / web-inf / springapp-servlet.xml <? xml version = "1.0" encoding = "UTF-8"?> <! doctype beans public "- // Spring // DTD bean // en" "http://www.springframework.org/dtd/spring-beans.dtd">" ~ - - Application Context definition for "SpringApp" dispatcherservlet. -></p> <p><beans> <bean id = "SpringAppController" class = "Web.SpringAppController> <property name =" productManager> <ref bean = "prodman" /> </ property> </ bean></p> <p><bean id = "prodmandao" class = "tests.mockproductmanagerdaoImpl> <property name =" products "> <list> <ref bean =" product1 "/> <ref bean =" product2 "/> <ref bean =" Product3 "/> </ List> </ property> </ bean></p> <p><bean id = "prodman" class = "bus.productmanager"> <property name = "productManagerdao"> <ref bean = "prodmandao" /> <property name = "products"> <list > <Ref bean = "product1" /> <ref bean = "product2" /> <ref bean = "product3" /> </ list> </ property> -> </ bean></p> <p><bean id = "product1" class = "bus.product"> <property name = "description"> <value> Lamp </ value> </ printy> <property name = "price"> <value> 5.75 </ value > </ profy> </ bean> <bean id = "product2" class = "bus.product"> <property name = "description"> <value> Table </ value> </ property> <property name = "Price "> <value> 75.25 </ value> </ proty> </ bean> <bean id =" product3 "class =" bus.product "> <property name =" description> <value> chair </ value> < / Property> <property name = "price"> <value> 22.79 </ value> </ property> </ bean></p> <p></ beans></p> <p>Springapp / src / tests / testproductmanager .java package tests;</p> <p>Import java.util.list; import junit.framework.testcase; import db.productManagerDao; import bus.productmanager; import bus.product;</p> <p>Public Class TestProductManager Extends Testcase {</p> <p>Private productManager PM;</p> <p>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 ()) }</p> <p>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 ());}</p> <p>}</p> <p>Reference resources:</p> <p>http://www.springframework.org/docs/mvc-step-cy-step/spring-mvc-step-s-step.html</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-93738.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="93738" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.040</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'T5i3wUPGrUo0GZ2hskUB21ZcNpLQoWEnte2uWxfca_2BgPJuSzL2DxDfbcGMizlnenAKG1fHRfYMhmBgd_2Fc4DqgQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>