ï»??xml version="1.0" encoding="utf-8" standalone="yes"?>h动漫在线视频,精品日韩一区,久久综合九色综合欧美就去吻http://www.aygfsteel.com/topquan/category/23897.html分äínä»·å€?---成就你我----我的博客----ä½ çš„å®?/description>zh-cnSat, 07 Jul 2007 14:45:52 GMTSat, 07 Jul 2007 14:45:52 GMT60Developing a Spring Framework MVC applicationåQˆå››åQ?/title><link>http://www.aygfsteel.com/topquan/articles/62677.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:25:00 GMT</pubDate><guid>http://www.aygfsteel.com/topquan/articles/62677.html</guid><wfw:comment>http://www.aygfsteel.com/topquan/comments/62677.html</wfw:comment><comments>http://www.aygfsteel.com/topquan/articles/62677.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/topquan/comments/commentRss/62677.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/topquan/services/trackbacks/62677.html</trackback:ping><description><![CDATA[     摘要: This is Part 4 of a step-by-step account of how to develop a web application from scratch using the Spring Framework. In Part 1 (Steps 1 – 12) we configured the environment and set up a basic ap...  <a href='http://www.aygfsteel.com/topquan/articles/62677.html'>阅读全文</a><img src ="http://www.aygfsteel.com/topquan/aggbug/62677.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:25 <a href="http://www.aygfsteel.com/topquan/articles/62677.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Developing a Spring Framework MVC application åQˆä¸‰åQ?http://www.aygfsteel.com/topquan/articles/62676.htmltopquantopquanWed, 09 Aug 2006 15:23:00 GMThttp://www.aygfsteel.com/topquan/articles/62676.htmlhttp://www.aygfsteel.com/topquan/comments/62676.htmlhttp://www.aygfsteel.com/topquan/articles/62676.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/62676.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/62676.htmlThis is Part 3 of a step-by-step account of how to develop a web application from scratch using the Spring Framework. In Part 1 (Steps 1 – 19) we configured the environment and set up a basic application that we will build upon. Part 2 (Steps 13-19) improved the application in several ways. We are now going to add some unit tests to the application.


Step 20 – Add unit test for the SpringappController

Before we create any unit tests, we want to prepare Ant and our build script to be able to handle this. Ant has a built in JUnit target, but we need to add junit.jar to Ant's lib directory. I used the one that came with the Spring distribution spring-framework-1.2/lib/junit/junit.jar. Just copy this file to the lib directory in your Ant installation. I also added the following target to our build script.

												    <target name="junit" depends="build" description="Run JUnit Tests">
                    <junit printsummary="on"
                           fork="false"
                           haltonfailure="false"
                           failureproperty="tests.failed"
                           showoutput="true">
                        <classpath refid="master-classpath"/>
                        <formatter type="brief" usefile="false"/>
                        <batchtest>
                            <fileset dir="${build.dir}">
                                <include name="**/Test*.*"/>
                            </fileset>
                        </batchtest>
                    </junit>
                    <fail if="tests.failed">
tests.failed=${tests.failed}
 *********************************************************** *********************************************************** **** One or more tests failed! Check the output ... **** *********************************************************** *********************************************************** </fail> </target>

Now I add a new sub-directory in the src directory that I name tests. This directory will, as you might have guessed, contain all the unit tests.

After all this, we are ready to start writing the first unit test. The SpringappController depends on both the HttpServletRequest, HttpServletResponse and our application context. Since the controller does not use the request or the response, we can simply pass in null for these objects. If that was not the case, we could create some mock objects using EasyMock that we would pass in during our test. The application context can be loaded outside of a web server environment using a class that will load an application context. There are several available, and for the current task the FileSystemXmlApplicationContext works fine.

springapp/src/tests/TestSpringappController.java

package tests;

import java.util.Map;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import web.SpringappController;
import bus.ProductManager;
import bus.Product;

public class TestSpringappController extends TestCase {

private ApplicationContext ac;

public void setUp() throws IOException {
ac = new FileSystemXmlApplicationContext("src/tests/WEB-INF/springapp-servlet.xml");
}

public void testHandleRequest() throws ServletException, IOException {
SpringappController sc = (SpringappController) ac.getBean("springappController");
ModelAndView mav = sc.handleRequest((HttpServletRequest) null, (HttpServletResponse) null);
Map m = mav.getModel();
List pl = (List) ((Map) m.get("model")).get("products");
Product p1 = (Product) pl.get(0);
assertEquals("Lamp", p1.getDescription());
Product p2 = (Product) pl.get(1);
assertEquals("Table", p2.getDescription());
Product p3 = (Product) pl.get(2);
assertEquals("Chair", p3.getDescription());
}

}

The only test is a call to handleRequest, and we check the products that are returned in the model. In the setUp method, we load the application context that I have copied into a WEB-INF directory in the src/tests directory. I create a copy just so this file will work during tests with a small set of beans necessary for running the tests. So, copy springapp/war/WEB-INF/springapp-servlet.xml to springapp/src/tests/WEB-INF directory. You can then remove the “messageSource”, "urlMapping" and "viewResolver" bean entries since they are not needed for this test.

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.
-->


<beans>
<bean id="springappController" class="web.SpringappController"><property name="productManager"> <ref bean="prodMan"/> </property> </bean> <bean id="prodMan" class="bus.ProductManager"> <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></property> </bean> <bean id="product3" class="bus.Product"> <property name="description"><value>Chair</value></property> <property name="price"><value>22.79</value></property> </bean> </beans>

When you run this test, you should see a lot of log messages from the loading of the application context.


Step 21 – Add unit test and new functionality for ProductManager

Next I add a test case for the ProductManager, and I also add a test for a new method to increase the prices that I am planning on adding to the ProductManager.

springapp/src/tests/TestProductManager .java

package tests;

import java.util.List;
import java.util.ArrayList;
import junit.framework.TestCase;
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);
}

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());
}

}

For this test, there is no need to create an application context. I just create a couple of products in the setUp method and add them to the product manager. I add tests for both getProducts and increasePrice. The increasePrice method is a cross the board increase based on the percentage passed in to the method. I modify the ProductManager class to implement this new method.

springapp/src/bus/ProductManager.java

package bus;

import java.io.Serializable;
import java.util.ListIterator; import java.util.List; public class ProductManager implements Serializable { private List products; public void setProducts(List p) { products = p; } public List getProducts() { return products; } public void increasePrice(int pct) { ListIterator li = products.listIterator(); while (li.hasNext()) { Product p = (Product) li.next(); double newPrice = p.getPrice().doubleValue() * (100 + pct)/100; p.setPrice(new Double(newPrice)); } } }

Next I build and run the tests. As you can see, this test is just like any regular test – the business classes don't depend on any of the servlet classes so these classes are very easy to test.


Step 22 – Adding a form

To provide an interface in the web application, I add a form that will allow the user to enter a percentage value. This form uses a tag library named “spring” that is provided with the Spring Framework. We have to copy this file from the Spring distribution spring-framework-1.2/dist/spring.tld to the springapp/war/WEB-INF directory. Now we must also add a <taglib> entry to web.xml.

springapp/war/WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'>

<web-app>

<servlet> <servlet-name>springapp</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springapp</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> <taglib> <taglib-uri>/spring</taglib-uri> <taglib-location>/WEB-INF/spring.tld</taglib-location> </taglib> </web-app>

We also have to declare this taglib in a page directive in the jsp file. We declare a form the normal way with a <form> tag and an <input> text field and a submit button.

springapp/war/WEB-INF/jsp/priceincrease.jsp

<%@ include file="/WEB-INF/jsp/include.jsp" %>
<%@ taglib prefix="spring" uri="/spring" %>

<html>
<head><title><fmt:message key="title"/></title></head>
<body>
<h1><fmt:message key="priceincrease.heading"/></h1>
<form method="post">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td alignment="right" width="20%">Increase (%):</td>
<spring:bind path="priceIncrease.percentage">
<td width="20%">
<input type="text" name="percentage" value="<c:out value="${status.value}"/>">
</td>
<td width="60%">
<font color="red"><c:out value="${status.errorMessage}"/></font>
</td>
</spring:bind>
</tr>
</table>
<br>
<spring:hasBindErrors name="priceIncrease">
<b>Please fix all errors!</b>
</spring:hasBindErrors>
<br><br>
<input type="submit" alignment="center" value="Execute">
</form>
<a href="<c:url value="hello.htm"/>">Home</a>
</body>
</html>

The <spring:bind> tag is used to bind an <input> form element to a command object PriceIncrease.java, that is used together with the form. This command object is later passed in to the validator and if it passes validation it is passed on to the controller. The ${status.errorMessage} and ${status.value} are special variables declared by the framework that can be used to display error messages and the current value of the field.

springapp/src/bus/PriceIncrease.java

package bus;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PriceIncrease {

/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());

private int percentage;

public void setPercentage(int i) {
percentage = i;
logger.info("Percentage set to " + i);
}

public int getPercentage() {
return percentage;
}

}

This is a very simple JavaBean class, and in our case there is a single property with a getter and setter. The validator class gets control after the user presses submit. The values entered in the form will be set on the command object by the framework. The method validate is called and the command object and an object to hold any errors are passed in.

springapp/src/bus/PriceIncreaseValidator.java

package bus;

import java.io.Serializable;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PriceIncreaseValidator implements Validator {
private int DEFAULT_MIN_PERCENTAGE = 0;
private int DEFAULT_MAX_PERCENTAGE = 50;
private int minPercentage = DEFAULT_MIN_PERCENTAGE;
private int maxPercentage = DEFAULT_MAX_PERCENTAGE;

/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());

public boolean supports(Class clazz) {
return clazz.equals(PriceIncrease.class);
}

public void validate(Object obj, Errors errors) {
PriceIncrease pi = (PriceIncrease) obj;
if (pi == null) {
errors.rejectValue("percentage", "error.not-specified", null, "Value required.");
}
else {
logger.info("Validating with " + pi + ": " + pi.getPercentage());
if (pi.getPercentage() > maxPercentage) {
errors.rejectValue("percentage", "error.too-high",
new Object[] {new Integer(maxPercentage)}, "Value too high.");
}
if (pi.getPercentage() <= minPercentage) {
errors.rejectValue("percentage", "error.too-low",
new Object[] {new Integer(minPercentage)}, "Value too low.");
}
}
}

public void setMinPercentage(int i) {
minPercentage = i;
}

public int getMinPercentage() {
return minPercentage;
}

public void setMaxPercentage(int i) {
maxPercentage = i;
}

public int getMaxPercentage() {
return maxPercentage;
}

}

Now we need to add an entry in the springapp-servlet.xml file to define the new form and controller. We define properties for command object and validator. We also specify two views, one that is used for the form and one that we will go to after successful form processing. The latter which is called the success view can be of two types. It can be a regular view reference that is forwarded to one of our JSP pages. One disadvantage with this approach is, that if the user refreshes the page, the form data is submitted again, and you would end up with a double priceincrease. An alternative way is to use a redirect, where a response is sent back to the users browser instructing it to redirect to a new url. The url we use in this case can't be one of our JSP pages, since they are hidden from direct access. It has to be a url that is externally reachable. I have choosen to use 'hello.htm' as my redirect url. This url maps to the 'hello.jsp' page, so this should work nicely.

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

<!--
- Application context definition for "springapp" DispatcherServlet.
-->

<beans>

<!-- Controller for the initial "Hello" page --> <bean id="springappController" class="web.SpringappController"> <property name="productManager"> <ref bean="prodMan"/> </property> </bean> <!-- Validator and Form Controller for the "Price Increase" page --> <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></property> <property name="validator"><ref bean="priceIncreaseValidator"/></property> <property name="formView"><value>priceincrease</value></property> <property name="successView"><value>hello.htm</value></property> <property name="productManager"> <ref bean="prodMan"/> </property> </bean> <bean id="prodMan" class="bus.ProductManager"> <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></property> </bean> <bean id="product3" class="bus.Product"> <property name="description"><value>Chair</value></property> <property name="price"><value>22.79</value></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"><value>messages</value></property> </bean> <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></property> <property name="suffix"><value>.jsp</value></property> </bean> </beans>

Next, let's take a look at the controller for this form. The onSubmit method gets control and does some logging before it calls the increasePrice method on the ProductManager object. It then returns a ModelAndView passing in a new instance of a RedirectView created using the url for the successView.

springapp/src/web/PriceIncreaseFormController.java

package web;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

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;
import bus.PriceIncrease;

public class PriceIncreaseFormController extends SimpleFormController {

/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());

private ProductManager prodMan;

public ModelAndView onSubmit(Object command)
throws ServletException {

int increase = ((PriceIncrease) command).getPercentage();
logger.info("Increasing prices by " + increase + "%.");

prodMan.increasePrice(increase);

String now = (new java.util.Date()).toString();
logger.info("returning from PriceIncreaseForm view to " + getSuccessView();

return new ModelAndView(new RedirectView(getSuccessView()));
}

protected Object formBackingObject(HttpServletRequest request) throws ServletException {

PriceIncrease priceIncrease = new PriceIncrease();
priceIncrease.setPercentage(20);

return priceIncrease;

}

public void setProductManager(ProductManager pm) {
prodMan = pm;
}

public ProductManager getProductManager() {
return prodMan;
}

}

We are also adding some messages to the messages.properties resource file.

springapp/war/WEB-INF/classes/messages.properties

title=SpringApp
heading=Hello :: SpringApp
greeting=Greetings, it is now
priceincrease.heading=Price Increase :: SpringApperror.not-specified=Percentage not specified!!!error.too-low=You have to specify a percentage higher than {0}!error.too-high=Don't be greedy - you can't raise prices by more than {0}%!required=Entry required.typeMismatch=Invalid data.typeMismatch.percentage=That is not a number!!!

Finally, we have to provide a link to the priceincrease page from the hello.jsp.

springapp/war/WEB-INF/jsp/hello.jsp

<%@ include file="/WEB-INF/jsp/include.jsp" %>

<html>
<head><title><fmt:message key="title"/></title></head>
<body>
<h1><fmt:message key="heading"/></h1>
<p><fmt:message key="greeting"/> <c:out value="${model.now}"/>
</p>
<h3>Products</h3>
<c:forEach items="${model.products}" var="prod">
<c:out value="${prod.description}"/> <i>$<c:out value="${prod.price}"/></i><br><br>
</c:forEach>
<br><a href="<c:url value="priceincrease.htm"/>">Increase Prices</a><br> </body> </html>

Compile and deploy all this and after reloading the application we can test it. This is what the form looks like with errors displayed.




]]>
Developing a Spring Framework MVC applicationåQˆäºŒåQ?/title><link>http://www.aygfsteel.com/topquan/articles/62675.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:22:00 GMT</pubDate><guid>http://www.aygfsteel.com/topquan/articles/62675.html</guid><wfw:comment>http://www.aygfsteel.com/topquan/comments/62675.html</wfw:comment><comments>http://www.aygfsteel.com/topquan/articles/62675.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/topquan/comments/commentRss/62675.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/topquan/services/trackbacks/62675.html</trackback:ping><description><![CDATA[<p style="MARGIN-BOTTOM: 0in">This is Part 2 of a step-by-step account of how to develop a web application from scratch using the Spring Framework. In Part 1 (Steps 1 – 12) we configured the environment and set up a basic application that we will build upon.</p> <p style="MARGIN-BOTTOM: 0in">This is what we have to start with.</p> <ol> <li> <p style="MARGIN-BOTTOM: 0in">An introduction page <strong>index.jsp</strong>.</p> <li> <p style="MARGIN-BOTTOM: 0in">A DispatcherServlet with a corresponding <strong>springapp-servlet.xml</strong> configuration file.</p> <li> <p style="MARGIN-BOTTOM: 0in">A controller <strong>springappController.java</strong>.</p> <li> <p style="MARGIN-BOTTOM: 0in">A view <strong>hello.jsp</strong>.</p> </li> </ol> <p style="MARGIN-BOTTOM: 0in">We will now improve on these parts to build a more useful application.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 13 – Improve index.jsp</strong> </p> <p style="MARGIN-BOTTOM: 0in">We will make use of JSP Standard Tag Library (JSTL) so I will start by copying the JSTL files we need to our WEB-INF/lib directory. Copy jstl.jar from the 'spring-framework-1.2/lib/j2ee' directory and standard.jar from the 'spring-framework-1.2/lib/jakarta-taglibs' directory to the springapp/war/WEB-INF/lib directory. I am also creating a “header” file that will be included in every JSP page that I'm going to write. This will make development easier and I will be sure that I have the same definitions in all JSPs. I am going to put all JSPs in a directory named jsp under the WEB-INF directory. This will ensure that only the controller has access to the views - it is not possible to get to these pages by entering them directly as a URL in the browser. This strategy might not work in all application servers and if this is the case with the one you are using, just move the jsp directory up a level. You would then use springapp/war/jsp as the directory instead of springapp/war/WEB-INF/jsp in all the code examples that will follow.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/jsp/include.jsp</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><%@ page session="false"%><br><br><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %><br><%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Now we can change index.jsp to use this include and since we are using JSTL we can use the <c:redirect> tag for redirecting to our Controller. This ties the index.jsp into our application framework.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/index.jsp</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><%@ include file="/WEB-INF/jsp/include.jsp" %><br><br><%-- Redirected because we can't set the welcome page to a virtual URL. --%><br><c:redirect url="/hello.htm"/></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 14 – Improve the view and the controller</strong> </p> <p>I am going to move the view hello.jsp to the WEB-INF/jsp directory. The same include that was added to index.jsp gets added to hello.jsp. I also add the current date and time as output that I will retrieve from the model, passed to the view, using the JSTL <c:out> tag. </p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/jsp/hello.jsp</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><%@ include file="/WEB-INF/jsp/include.jsp" %><br><br><html><br><head><title>Hello :: Spring Application</title></head><br><body><br><h1>Hello - Spring Application</h1><br><p>Greetings, it is now <c:out value="${now}"/><br></p><br></body><br></html></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">For SpringappController.java there are a few changes we need to make. Change the view to WEB-INF/jsp/hello.jsp since we moved the file to this new location. Also add a string containing the current data and time as the model. </p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/SpringappController.java</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre>import org.springframework.web.servlet.mvc.Controller;<br>import org.springframework.web.servlet.ModelAndView;<br><br>import javax.servlet.ServletException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>import java.io.IOException;<br><br>import org.apache.commons.logging.Log;<br>import org.apache.commons.logging.LogFactory;<br><br>public class SpringappController implements Controller {<br><br> /** Logger for this class and subclasses */<br> protected final Log logger = LogFactory.getLog(getClass());<br><br> public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)<br> throws ServletException, IOException {<br><br><font color=#800000> String now = (new java.util.Date()).toString(); </font><font color=#800000> logger.info("returning hello view with " + now);</font><font color=#800000> return new ModelAndView("WEB-INF/jsp/hello.jsp", "now", now);</font> } }</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Now we are ready to try this after we build and deploy this new code. We enter <a href="http://localhost:8080/springapp">http://localhost:8080/springapp</a> in a browser and that should pull up index.jsp, which should redirect to hello.htm, which in turn gets us to the controller that sends the data and time to the view.</p> <p style="MARGIN-BOTTOM: 0in"><img height=540 src="file:///G:/Guest%20Documents/topquan/develop/spring-framework-1.2.8/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-2_html_1969edd8.png" width=780 align=left border=0 name=Graphic1> <br clear=left><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 15 – Decouple the view and the controller</strong> </p> <p style="MARGIN-BOTTOM: 0in">Right now the controller specifies the full path of the view, which creates an unnecessary dependency between the controller and the view. Ideally we would like to map to the view using a logical name, allowing us to switch the view without having to change the controller. You can set this mapping in a properties file if you like using a ResourceBundleViewResolver and a SimpleUrlHandlerMapping class. If your mapping needs are simple it is easier to just set a prefix and a suffix on the InternalResourceViewResolver. The latter approach is the one that I will implement now, so I modify the springapp-servlet.xml and include this viewResolver entry. I have elected to use a JstlView which will enable us to use JSTL in combination with message resource bundles and it will also support internationalization.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/springapp-servlet.xml</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><?xml version="1.0" encoding="UTF-8"?><br><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><br><br><!--<br> - Application context definition for "springapp" DispatcherServlet.<br> --><br><br><beans><br> <bean id="springappController" class="SpringappController"/><br><br> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><br> <property name="mappings"><br> <props><br> <prop key="/hello.htm">springappController</prop><br> </props><br> </property><br> </bean><br><br><font color=#800000> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"></font><font color=#800000> <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property></font><font color=#800000> <property name="prefix"><value>/WEB-INF/jsp/</value></property></font><font color=#800000> <property name="suffix"><value>.jsp</value></property></font><font color=#800000> </bean></font> </beans> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">So now I can remove the prefix and suffix from the view name in the controller. </p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/SpringappController.java</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre>import org.springframework.web.servlet.mvc.Controller;<br>import org.springframework.web.servlet.ModelAndView;<br><br>import javax.servlet.ServletException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>import java.io.IOException;<br><br>import org.apache.commons.logging.Log;<br>import org.apache.commons.logging.LogFactory;<br><br>public class SpringappController implements Controller {<br><br> /** Logger for this class and subclasses */<br> protected final Log logger = LogFactory.getLog(getClass());<br><br> public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)<br> throws ServletException, IOException {<br><br> String now = (new java.util.Date()).toString();<br> logger.info("returning hello view with " + now);<br><br><font color=#800000>return new ModelAndView("hello", "now", now);</font> } }</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Compile and deploy and the application should still work.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 16 – Add some classes for business logic</strong> </p> <p style="MARGIN-BOTTOM: 0in">So far our application is not very useful. I would like to add a little bit of business logic in form of a Product class and a class that will manage all the products. I name this management class ProductManager. In order to separate the web dependent logic from the business logic I will create two separate packages for the Java source – web and bus. If this was an application for a real company I would name the packages something like com.mycompany.web and com.mycompany.bus, but since this is just a demo application I will keep the package names real short. The Product class is implemented as a JavaBean – it has the default constructor (automatically provided if we don't specify any constructors) and getters and setters for the two instance variables description and price. I also make it Serializable, not necessary for our application, but could come in handy later on if we have to pass this class between different application layers.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=876 border=1> <colgroup> <col width=866></colgroup> <tbody> <tr> <td vAlign=top width=866 bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/bus/Product.java</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width=866 bgColor=#ffffcc> <pre>package bus;<br><br>import java.io.Serializable;<br><br>public class Product implements Serializable {<br><br> private String description;<br> private Double price;<br><br> public void setDescription(String s) {<br> description = s;<br> }<br><br> public String getDescription() {<br> return description;<br> }<br><br> public void setPrice(Double d) {<br> price = d;<br> }<br><br> public Double getPrice() {<br> return price;<br> }<br><br>}</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">The ProductManager holds a List of Products, and again this this class is implemented as a JavaBean.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=876 border=1> <colgroup> <col width=866></colgroup> <tbody> <tr> <td vAlign=top width=866 bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/bus/ProductManager.java</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width=866 bgColor=#ffffcc> <pre>package bus;<br><br>import java.io.Serializable;<br>import java.util.List;<br><br>public class ProductManager implements Serializable {<br><br> private List products;<br><br> public void setProducts(List p) {<br> products = p;<br> }<br><br> public List getProducts() {<br> return products;<br> }<br><br>}</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Next, I modify the SpringappController to hold a reference to this ProductManager class. As you can see, it is now in a separate package called web – remember to move the source to this new location. I also add code to have the controller pass some product information to the view. The getModelAndView now returns a Map with both the date and time and the product manager reference.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=876 border=1> <colgroup> <col width=866></colgroup> <tbody> <tr> <td vAlign=top width=866 bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/web/SpringappController.java</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width=866 bgColor=#ffffcc> <pre>package web;<br><br>import org.springframework.web.servlet.mvc.Controller;<br>import org.springframework.web.servlet.ModelAndView;<br><br>import javax.servlet.ServletException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>import java.io.IOException;<br><font color=#800000>import java.util.Map;</font><font color=#800000>import java.util.HashMap;</font> import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; <font color=#800000>import bus.Product;</font><font color=#800000>import bus.ProductManager;</font> public class SpringappController implements Controller { /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog(getClass()); <font color=#800000> private ProductManager prodMan;</font> public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String now = (new java.util.Date()).toString(); logger.info("returning hello view with " + now); <font color=#800000> Map myModel = new HashMap();</font><font color=#800000> myModel.put("now", now);</font><font color=#800000> myModel.put("products", getProductManager().getProducts());</font><font color=#800000> return new ModelAndView("hello", "model", myModel);</font> } <font color=#800000> public void setProductManager(ProductManager pm) {</font><font color=#800000> prodMan = pm;</font><font color=#800000> }</font><font color=#800000> public ProductManager getProductManager() {</font><font color=#800000> return prodMan;</font><font color=#800000> }</font> }</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 17 – Modify the view to display business data and add support for message bundle</strong> </p> <p style="MARGIN-BOTTOM: 0in">Using the JSTL <c:forEach> tag, I add a section that displays product information. I have also replaced the title, heading and greeting text with a JSTL <fmt:message> tag that pulls the text to display from a provided 'message' source – I will show this source in a later step. </p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/jsp/hello.jsp</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><%@ include file="/WEB-INF/jsp/include.jsp" %><br><br><html><br><head><font color=#800000><title><fmt:message key="title"/></title></font></head><br><body><br><font color=#800000><h1><fmt:message key="heading"/></h1></font> <p><font color=#800000><fmt:message key="greeting"/></font> <c:out value="${model.now}"/><br></p><br><font color=#800000><h3>Products</h3></font><font color=#800000><c:forEach items="${model.products}" var="prod"></font><font color=#800000> <c:out value="${prod.description}"/> <i>$<c:out value="${prod.price}"/></i><br><br></font><font color=#800000></c:forEach></font> </body> </html></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 18 – Add some test data to automatically populate some business objects</strong> </p> <p style="MARGIN-BOTTOM: 0in">I am not going to add any code to load the business objects from a database just yet. Instead, we can “wire up” a couple of instances using Spring's bean and application context support. I will simply put the data I need as a couple of bean entries in springapp-servlet.xml. I will also add the messageSource entry that will pull in the messages resource bundle ('messages.properties') that I will create in the next step.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=939 border=1> <colgroup> <col width=929></colgroup> <tbody> <tr> <td vAlign=top width=929 bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/springapp-servlet.xml</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width=929 bgColor=#ffffcc> <pre><?xml version="1.0" encoding="UTF-8"?><br><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><br><br><!--<br> - Application context definition for "springapp" DispatcherServlet.<br> --><br><br><br><beans><br> <bean id="springappController" class="web.SpringappController"<font color=#800000>></font><font color=#800000> <property name="productManager"></font><font color=#800000> <ref bean="prodMan"/></font><font color=#800000> </property></font><font color=#800000> </bean></font><font color=#800000> <bean id="prodMan" class="bus.ProductManager"></font><font color=#800000> <property name="products"></font><font color=#800000> <list></font><font color=#800000> <ref bean="product1"/></font><font color=#800000> <ref bean="product2"/></font><font color=#800000> <ref bean="product3"/></font><font color=#800000> </list></font><font color=#800000> </property></font><font color=#800000> </bean></font><font color=#800000> <bean id="product1" class="bus.Product"></font><font color=#800000> <property name="description"><value>Lamp</value></property></font><font color=#800000> <property name="price"><value>5.75</value></property></font><font color=#800000> </bean></font><font color=#800000></font><font color=#800000> <bean id="product2" class="bus.Product"></font><font color=#800000> <property name="description"><value>Table</value></property></font><font color=#800000> <property name="price"><value>75.25</value></property></font><font color=#800000> </bean></font><font color=#800000> <bean id="product3" class="bus.Product"></font><font color=#800000> <property name="description"><value>Chair</value></property></font><font color=#800000> <property name="price"><value>22.79</value></property></font><font color=#800000> </bean></font><font color=#800000> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"></font><font color=#800000> <property name="basename"><value>messages</value></property></font><font color=#800000> </bean></font> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello.htm">springappController</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></property> <property name="suffix"><value>.jsp</value></property> </bean> </beans> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 19 – Add the message bundle and a 'clean' target to build.xml</strong> </p> <p style="MARGIN-BOTTOM: 0in">I create a 'messages.properties' file in the war/WEB-INF/classes directory. This properties bundle so far has three entries matching the keys specified in the <fmt:message> tags that we added to the hello.jsp.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/classes/messages.properties</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre>title=SpringApp<br>heading=Hello :: SpringApp<br>greeting=Greetings, it is now</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Since we moved some source files around, it makes sense to add a 'clean' and an 'undeploy' target to the build scripts. I add the following entries to the build.xml file.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=807 border=1> <colgroup> <col width=797></colgroup> <tbody> <tr> <td vAlign=top width=797 bgColor=#ffffff> <pre> <font color=#800000> <target name="clean" description="Clean output directories"></font> <font color=#800000> <delete></font> <font color=#800000> <fileset dir="${build.dir}"></font> <font color=#800000> <include name="**/*.class"/></font> <font color=#800000> </fileset></font> <font color=#800000> </delete></font> <font color=#800000> </target></font> <font color=#800000> <target name="undeploy" description="Un-Deploy application"></font> <font color=#800000> <delete></font> <font color=#800000> <fileset dir="${deploy.path}/${name}"></font> <font color=#800000> <include name="**/*.*"/></font> <font color=#800000> </fileset></font> <font color=#800000> </delete></font> <font color=#800000> </target></font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Now stop the Tomcat server, run the clean, undeploy and deploy targets. This should remove all old class files, re-build the application and deploy it. Start up Tomcat again and you should see the following:</p> <p style="MARGIN-BOTTOM: 0in"><img height=536 src="file:///G:/Guest%20Documents/topquan/develop/spring-framework-1.2.8/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-2_html_m3eb7013.png" width=742 align=left border=0 name=Graphic2> <br clear=left></p> <img src ="http://www.aygfsteel.com/topquan/aggbug/62675.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:22 <a href="http://www.aygfsteel.com/topquan/articles/62675.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Developing a Spring Framework MVC applicationåQˆä¸€åQ?/title><link>http://www.aygfsteel.com/topquan/articles/62673.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:21:00 GMT</pubDate><guid>http://www.aygfsteel.com/topquan/articles/62673.html</guid><wfw:comment>http://www.aygfsteel.com/topquan/comments/62673.html</wfw:comment><comments>http://www.aygfsteel.com/topquan/articles/62673.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/topquan/comments/commentRss/62673.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/topquan/services/trackbacks/62673.html</trackback:ping><description><![CDATA[<p style="MARGIN-BOTTOM: 0in" align=center>This is a step-by-step account of how to develop a web application from scratch using the Spring Framework.</p> <p style="MARGIN-BOTTOM: 0in">Prerequisites:</p> <ul> <ul> <li> <p style="MARGIN-BOTTOM: 0in">Java SDK (<em>I am currently using version 1.4.2</em>)</p> <li> <p style="MARGIN-BOTTOM: 0in">Ant (<em>using version 1.6.2</em>)</p> <li> <p style="MARGIN-BOTTOM: 0in">Apache Tomcat (<em>using version 5.0.28</em>)</p> </li> </ul> </ul> <p style="MARGIN-BOTTOM: 0in">You should also be reasonably comfortable using the above software.</p> <p style="MARGIN-BOTTOM: 0in">I am not going to cover a lot of background information or theory in this document -- there are plenty of books available that covers this in depth. Instead we will dive right into developing the application.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 1 – development directory</strong> </p> <p style="MARGIN-BOTTOM: 0in">We are going to need a place to keep all the source and other files we will be creating, so I create a directory that I name 'springapp'. You can place this directory in your home folder or in some other location. I created mine in a 'projects' directory that I already had in my home directory so the full path to my directory is '/Users/trisberg/projects/springapp'. Inside this directory I create a 'src' directory to hold all Java source files. Then I create another directory that I name 'war'. This directory will hold everything that should go into the WAR file, that we would use to deploy our application. All source files other than Java source, like JSPs and configuration files, belongs in this directory.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 2 – index.jsp</strong> </p> <p style="MARGIN-BOTTOM: 0in">I will start by creating a JSP page named 'index.jsp' in the war directory. This is the entry point for our application.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/index.jsp</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><html><br><head><title>Example :: Spring Application</title></head><br><body><br><h1>Example - Spring Application</h1><br><p>This is my test.</p><br></body><br></html></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Just to have a complete web application, I create a web.xml in a WEB-INF directory that I create under the war directory.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=1004 border=1> <colgroup> <col width=994></colgroup> <tbody> <tr> <td vAlign=top width=994 bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/web.xml</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width=994 bgColor=#ffffcc> <pre><?xml version="1.0" encoding="UTF-8"?><br><!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'><br><br><web-app><br><br></web-app></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 3 – deploying the application to Tomcat</strong> </p> <p style="MARGIN-BOTTOM: 0in">Next, I write an Ant build script that we are going to use throughout this document. There are tasks for building and deploying the application. A separate build script contains the app server specific tasks There are also tasks for controlling the application under Tomcat.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/build.xml</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><?xml version="1.0"?><br><br><project name="springapp" basedir="." default="usage"><br> <property file="build.properties"/><br><br> <property name="src.dir" value="src"/><br> <property name="web.dir" value="war"/><br> <property name="build.dir" value="${web.dir}/WEB-INF/classes"/><br> <property name="name" value="springapp"/><br><br> <path id="master-classpath"><br> <fileset dir="${web.dir}/WEB-INF/lib"><br> <include name="*.jar"/><br> </fileset><br> <!-- We need the servlet API classes: --><br> <!-- for Tomcat 4.1 use servlet.jar --><br> <!-- for Tomcat 5.0 use servlet-api.jar --><br> <!-- for Other app server - check the docs --><br> <fileset dir="${appserver.home}/common/lib"><br> <include name="servlet*.jar"/><br> </fileset><br> <pathelement path="${build.dir}"/><br> </path><br><br> <target name="usage"><br> <echo message=""/><br> <echo message="${name} build file"/><br> <echo message="-----------------------------------"/><br> <echo message=""/><br> <echo message="Available targets are:"/><br> <echo message=""/><br> <echo message="build --> Build the application"/><br> <echo message="deploy --> Deploy application as directory"/><br> <echo message="deploywar --> Deploy application as a WAR file"/><br> <echo message="install --> Install application in Tomcat"/><br> <echo message="reload --> Reload application in Tomcat"/><br> <echo message="start --> Start Tomcat application"/><br> <echo message="stop --> Stop Tomcat application"/><br> <echo message="list --> List Tomcat applications"/><br> <echo message=""/><br> </target><br><br> <target name="build" description="Compile main source tree java files"><br> <mkdir dir="${build.dir}"/><br> <javac destdir="${build.dir}" target="1.3" debug="true"<br> deprecation="false" optimize="false" failonerror="true"><br> <src path="${src.dir}"/><br> <classpath refid="master-classpath"/><br> </javac><br> </target><br><br> <target name="deploy" depends="build" description="Deploy application"><br> <copy todir="${deploy.path}/${name}" preservelastmodified="true"><br> <fileset dir="${web.dir}"><br> <include name="**/*.*"/><br> </fileset><br> </copy><br> </target><br><br> <target name="deploywar" depends="build" description="Deploy application as a WAR file"><br> <war destfile="${name}.war"<br> webxml="${web.dir}/WEB-INF/web.xml"><br> <fileset dir="${web.dir}"><br> <include name="**/*.*"/><br> </fileset><br> </war><br> <copy todir="${deploy.path}" preservelastmodified="true"><br> <fileset dir="."><br> <include name="*.war"/><br> </fileset><br> </copy><br> </target><br><br><!-- ============================================================== --><br><!-- Tomcat tasks - remove these if you don't have Tomcat installed --><br><!-- ============================================================== --><br><br> <taskdef name="install" classname="org.apache.catalina.ant.InstallTask"><br> <classpath><br> <path location="${appserver.home}/server/lib/catalina-ant.jar"/><br> </classpath><br> </taskdef><br> <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"><br> <classpath><br> <path location="${appserver.home}/server/lib/catalina-ant.jar"/><br> </classpath><br> </taskdef><br> <taskdef name="list" classname="org.apache.catalina.ant.ListTask"><br> <classpath><br> <path location="${appserver.home}/server/lib/catalina-ant.jar"/><br> </classpath><br> </taskdef><br> <taskdef name="start" classname="org.apache.catalina.ant.StartTask"><br> <classpath><br> <path location="${appserver.home}/server/lib/catalina-ant.jar"/><br> </classpath><br> </taskdef><br> <taskdef name="stop" classname="org.apache.catalina.ant.StopTask"><br> <classpath><br> <path location="${appserver.home}/server/lib/catalina-ant.jar"/><br> </classpath><br> </taskdef><br><br> <target name="install" description="Install application in Tomcat"><br> <install url="${tomcat.manager.url}"<br> username="${tomcat.manager.username}"<br> password="${tomcat.manager.password}"<br> path="/${name}"<br> war="${name}"/><br> </target><br><br> <target name="reload" description="Reload application in Tomcat"><br> <reload url="${tomcat.manager.url}"<br> username="${tomcat.manager.username}"<br> password="${tomcat.manager.password}"<br> path="/${name}"/><br> </target><br><br> <target name="start" description="Start Tomcat application"><br> <start url="${tomcat.manager.url}"<br> username="${tomcat.manager.username}"<br> password="${tomcat.manager.password}"<br> path="/${name}"/><br> </target><br><br> <target name="stop" description="Stop Tomcat application"><br> <stop url="${tomcat.manager.url}"<br> username="${tomcat.manager.username}"<br> password="${tomcat.manager.password}"<br> path="/${name}"/><br> </target><br><br> <target name="list" description="List Tomcat applications"><br> <list url="${tomcat.manager.url}"<br> username="${tomcat.manager.username}"<br> password="${tomcat.manager.password}"/><br> </target><br><br><!-- End Tomcat tasks --><br><br></project></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">This script now contains all the targets that we are going to need to make our development efforts easier. I am not going to cover this script in detail since most if not all of it is pretty much standard Ant and Tomcat stuff. You can just copy the above build file and put it at the root of your development directory tree. We also need a build.properties file that you should customize to match your server installation. This file belongs in the same directory as the build.xml file.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/build.properties</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre># Ant properties for building the springapp<br><br>appserver.home=${user.home}/jakarta-tomcat-5.0.28<br>deploy.path=${appserver.home}/webapps<br><br>tomcat.manager.url=http://localhost:8080/manager<br>tomcat.manager.username=admin<br>tomcat.manager.password=tomcat</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><em>If you are on a system where you are not the owner of the Tomcat install, then the Tomcat owner must either grant you full access to the webapps directory or the owner must create a new directory named 'springapp' in the 'webapps' directory of the Tomcat installation, and also give you full rights to deploy to this newly created directory. On Linux I run the command <strong><font size=2><font face="Fixed, monospace">chmod a+rwx springapp</font></font></strong> to give everybody full rights to this directory.</em> </p> <p style="MARGIN-BOTTOM: 0in"><em>If you are using a different web application server, then you can remove the Tomcat specific tasks at the end of the build script. You will have to rely on your server's hot deploy feature, or you will have to stop and start your application manually.</em> </p> <p style="MARGIN-BOTTOM: 0in">Now I run Ant to make sure that everything is working OK. You should have your current directory set to the 'springapp' directory.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="85%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#e6e6ff> <pre> <font color=#280099>[trisberg@localhost springapp]$ ant</font> <font color=#280099>Buildfile: build.xml</font> <font color=#280099> </font> <font color=#280099>usage:</font> <font color=#280099> </font> <font color=#280099> [echo] springapp build file</font> <font color=#280099> [echo] -----------------------------------</font> <font color=#280099> </font> <font color=#280099> [echo] Available targets are:</font> <font color=#280099> </font> <font color=#280099> [echo] build --> Build the application</font> <font color=#280099> [echo] deploy --> Deploy application as directory</font> <font color=#280099> [echo] deploywar --> Deploy application as a WAR file</font> <font color=#280099> [echo] install --> Install application in Tomcat</font> <font color=#280099> [echo] reload --> Reload application in Tomcat</font> <font color=#280099> [echo] start --> Start Tomcat application</font> <font color=#280099> [echo] stop --> Stop Tomcat application</font> <font color=#280099> [echo] list --> List Tomcat applications</font> <font color=#280099> </font> <font color=#280099> </font> <font color=#280099>BUILD SUCCESSFUL</font> <font color=#280099>Total time: 2 seconds</font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Last action here is to do the actual deployment. Just run Ant and specify 'deploy' or 'deploywar' as the target.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="85%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#e6e6ff> <pre> <font color=#280099>[trisberg@localhost springapp]$ ant deploy</font> <font color=#280099>Buildfile: build.xml</font> <font color=#280099> </font> <font color=#280099>build:<br> [mkdir] Created dir: /Users/trisberg/projects/springapp/war/WEB-INF/classes<br><br>deploy:<br> [copy] Copying 2 files to /Users/trisberg/jakarta-tomcat-5.0.28/webapps/springapp<br><br></font> <font color=#280099>BUILD SUCCESSFUL</font> <font color=#280099>Total time: 2 seconds</font> </pre> </td> </tr> </tbody> </table> <p><br><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 4 – Test the application</strong> </p> <p style="MARGIN-BOTTOM: 0in">Let's just quickly start Tomcat and make sure that we can access the application. Use the 'list' task from our build file to see if Tomcat has picked up the new application.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="85%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#e6e6ff> <pre> <font color=#280099>[trisberg@localhost springapp]$ ant list</font> <font color=#280099>Buildfile: build.xml</font> <font color=#280099> </font> <font color=#280099>list:<br> [list] OK - Listed applications for virtual host localhost<br><br> [list] /admin:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/server/webapps/admin<br><br> [list] /webdav:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/webapps/webdav<br><br> [list] /servlets-examples:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/webapps/servlets-examples<br><br><span style="FONT-WEIGHT: bold"> [list] /springapp:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/webapps/springapp</span><br style="FONT-WEIGHT: bold"><br> [list] /jsp-examples:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/webapps/jsp-examples<br><br> [list] /balancer:running:0:balancer<br><br> [list] /tomcat-docs:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/webapps/tomcat-docs<br><br> [list] /:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/webapps/ROOT<br><br> [list] /manager:running:0:/Users/trisberg/jakarta-tomcat-5.0.28/server/webapps/manager<br></font> <font color=#280099> </font> <font color=#280099> </font> <font color=#280099>BUILD SUCCESSFUL</font> <font color=#280099>Total time: 1 second</font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">If it is not listed, use the 'install' task to get the application installed in Tomcat.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="85%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#e6e6ff> <pre> <font color=#280099>[trisberg@localhost springapp]$ ant install</font> <font color=#280099>Buildfile: build.xml</font> <font color=#280099> </font> <font color=#280099>install:</font> <font color=#280099> [install] OK - Installed application at context path /springapp</font> <font color=#280099> </font> <font color=#280099> </font> <font color=#280099>BUILD SUCCESSFUL</font> <font color=#280099>Total time: 2 seconds</font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in">Now open a browser and browse to <a href="http://localhost:8080/springapp/index.jsp">http://localhost:8080/springapp/index.jsp</a>. </p> <p style="MARGIN-BOTTOM: 0in"><img height=528 src="file:///G:/Guest%20Documents/topquan/develop/spring-framework-1.2.8/docs/MVC-step-by-step/Spring-MVC-step-by-step_html_m5b7553b2.png" width=840 align=left border=0 name=Graphic1> <br clear=left><br></p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 5 – Download Spring distribution</strong> </p> <p style="MARGIN-BOTTOM: 0in">If you have not already downloaded the Spring Framework Release file, now is the time to do so. I am currently using 'spring-framework-1.2-with-dependencies.zip' that can be downloaded from <a >www.springframework.org/download.html</a>. I unzipped this file in my home directory. We are going to use several files from this download later on.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><font size=4><u><strong>This completes the setup of the environment that is necessary, and now we can start actually developing our Spring Framework MVC application.</strong> </u></font></p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 6 – Modify web.xml in WEB-INF directory</strong> </p> <p style="MARGIN-BOTTOM: 0in">Go to the 'springapp/war/ WEB-INF' directory. Modify the minimal 'web.xml' file that we created earlier. Now we will modify it to suit our needs. We define a DispatcherServlet that is going to control where all our request are routed based on information we will enter at a later point. It also has a standard servlet-mapping entry that maps to the url patterns that we will be using. I have decided to let any url with an '.htm' extension be routed to the 'springapp' dispatcher.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/web.xml</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><?xml version="1.0" encoding="UTF-8"?><br><!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'><br><br><web-app><br><br><font color=#800000> <servlet></font><font color=#800000> <servlet-name>springapp</servlet-name></font><font color=#800000> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class></font><font color=#800000> <load-on-startup>1</load-on-startup></font><font color=#800000> </servlet></font><font color=#800000> <servlet-mapping></font><font color=#800000> <servlet-name>springapp</servlet-name></font><font color=#800000> <url-pattern>*.htm</url-pattern></font><font color=#800000> </servlet-mapping></font><font color=#800000> <welcome-file-list></font><font color=#800000> <welcome-file></font><font color=#800000> index.jsp</font><font color=#800000> </welcome-file></font><font color=#800000> </welcome-file-list></font> </web-app></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Next, create a file called 'springapp-servlet.xml' in the springapp/war/WEB-INF directory (you can copy an example of this file from the Spring distributions sample/skeletons/webapp-minimal directory). This is the file where definitions used by the DispatcherServlet should be entered. It is named based on the servlet-name from web.xml with '-servlet' appended. This is a standard naming convention used in the Spring Framework. Now, add a bean entry named springappController and make the class SpringappController. This defines the controller that our application will be using. We also need to add a url mapping so the DispatcherServlet knows which controller should be invoked for different url:s.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/war/WEB-INF/springapp-servlet.xml</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><?xml version="1.0" encoding="UTF-8"?><br><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><br><br><!--<br> - Application context definition for "springapp" DispatcherServlet.<br> --><br><br><beans><br> <bean id="springappController" class="SpringappController"/><br><br> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"><br> <property name="mappings"><br> <props><br> <prop key="/hello.htm">springappController</prop><br> </props><br> </property><br> </bean><br></beans></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 7 – Copy jars to WEB-INF/lib</strong> </p> <p style="MARGIN-BOTTOM: 0in">First create a 'lib' directory in the 'war/WEB-INF' directory.  Then, from the Spring distribution, copy spring.jar (spring-framework-1.2/dist/spring.jar) to the new war/WEB-INF/lib directory. Also copy commons-logging jars to the war/WEB-INF/lib directory (spring-framework-1.2/lib/jakarta-commons/commons-logging.jar). We are also going to need a log4j jar. Copy log4j-1.2.9.jar to the war/WEB-INF/lib directory (spring-framework-1.2/lib/log4j/log4j-1.2.9.jar). These jars will be deployed to the server and they are also used during the build process.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 8 – Create your Controller</strong> </p> <p style="MARGIN-BOTTOM: 0in">Create your Controller – I named mine SpringappController.java and placed it in the springapp/src directory.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/src/SpringappController.java</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre>import org.springframework.web.servlet.mvc.Controller;<br>import org.springframework.web.servlet.ModelAndView;<br><br>import javax.servlet.ServletException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>import java.io.IOException;<br><br>public class SpringappController implements Controller {<br><br> public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)<br> throws ServletException, IOException {<br> return new ModelAndView("");<br> }<br>}</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">This is as basic a Controller as you can use. We will be expanding this later on, and we will also later on extend some provided abstract base implementations. The Controller “handles” the request and returns a ModelAndView. We have not yet defined any Views, so right now there is nothing to do.</p> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 9 – Build the Application</strong> </p> <p style="MARGIN-BOTTOM: 0in">Run the 'build' task of the build.xml. Hopefully the code compiles OK.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="85%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#e6e6ff> <pre> <font color=#280099>[trisberg@localhost springapp]$ ant build</font> <font color=#280099>Buildfile: build.xml</font> <font color=#280099> </font> <font color=#280099>build:</font> <font color=#280099> [javac] Compiling 1 source file to /Users/trisberg/projects/springapp/war/WEB-INF/classes</font> <font color=#280099> </font> <font color=#280099>BUILD SUCCESSFUL</font> <font color=#280099>Total time: 2 seconds</font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 10 – Copy and modify log4j.properties</strong> </p> <p style="MARGIN-BOTTOM: 0in">The Spring Framework uses log4j for logging so we have to create a configuration file for log4j. Copy the log4j.properties from the sample Petclinic application (spring-framework-1.2/samples/petclinic/war/WEB-INF/log4j.properties) to the war/WEB-INF/classes directory (this directory should have been created in the previous step). Now uncomment or modify the log4j.rootCategory property and change the name and location of the logfile that will be written. I decided to have it written to the same directory as all other Tomcat logs.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/war/WEB-INF/classes/log4j.properties</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre># For JBoss: Avoid to setup Log4J outside $JBOSS_HOME/server/default/deploy/log4j.xml!<br># For all other servers: Comment out the Log4J listener in web.xml to activate Log4J.<br>log4j.rootLogger=INFO, stdout, logfile<br><br>log4j.appender.stdout=org.apache.log4j.ConsoleAppender<br>log4j.appender.stdout.layout=org.apache.log4j.PatternLayout<br>log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n<br><br>log4j.appender.logfile=org.apache.log4j.RollingFileAppender<br><span style="FONT-WEIGHT: bold">log4j.appender.logfile.File=/Users/trisberg/jakarta-tomcat-5.0.28/logs/springapp.log</span><br style="FONT-WEIGHT: bold">log4j.appender.logfile.MaxFileSize=512KB<br># Keep three backup files.<br>log4j.appender.logfile.MaxBackupIndex=3<br># Pattern to output: date priority [category] - message<br>log4j.appender.logfile.layout=org.apache.log4j.PatternLayout<br>log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Step 11 – Deploy Application</strong> </p> <p style="MARGIN-BOTTOM: 0in">Run the 'deploy' task and then the 'stop' and 'start' tasks of the build.xml. This will force a reload of the application. We have to check the Tomcat logs for any deployment errors – there could be typos in the above xml files or there could be missing classes or jar files. This is an example of what it should look like. (/Users/trisberg/jakarta-tomcat-5.0.28/logs/springapp.log)</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="85%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#e6e6ff> <pre> <font color=#280099>2005-04-24 14:58:18,112 INFO [org.springframework.web.servlet.DispatcherServlet] - Initializing servlet 'springapp'<br>2005-04-24 14:58:18,261 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'springapp': initialization started<br>2005-04-24 14:58:18,373 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] - Loading XML bean definitions from ServletContext resource [/WEB-INF/springapp-servlet.xml]<br>2005-04-24 14:58:18,498 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Bean factory for application context [WebApplicationContext for namespace 'springapp-servlet']: org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [springappController,urlMapping]; root of BeanFactory hierarchy<br>2005-04-24 14:58:18,505 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - 2 beans defined in application context [WebApplicationContext for namespace 'springapp-servlet']<br>2005-04-24 14:58:18,523 INFO [org.springframework.core.CollectionFactory] - JDK 1.4+ collections available<br>2005-04-24 14:58:18,524 INFO [org.springframework.core.CollectionFactory] - Commons Collections 3.x available<br>2005-04-24 14:58:18,537 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@8dacb]<br>2005-04-24 14:58:18,539 INFO [org.springframework.web.context.support.XmlWebApplicationContext] - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@5674a4]<br>2005-04-24 14:58:18,549 INFO [org.springframework.ui.context.support.UiApplicationContextUtils] - No ThemeSource found for [WebApplicationContext for namespace 'springapp-servlet']: using ResourceBundleThemeSource<br>2005-04-24 14:58:18,556 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Pre-instantiating singletons in factory [org.springframework.beans.factory.support.DefaultListableBeanFactory defining beans [springappController,urlMapping]; root of BeanFactory hierarchy]<br>2005-04-24 14:58:18,557 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'springappController'<br>2005-04-24 14:58:18,603 INFO [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Creating shared instance of singleton bean 'urlMapping'<br>2005-04-24 14:58:18,667 INFO [org.springframework.web.servlet.DispatcherServlet] - Using context class [org.springframework.web.context.support.XmlWebApplicationContext] for servlet 'springapp'<br>2005-04-24 14:58:18,668 INFO [org.springframework.web.servlet.DispatcherServlet] - Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided<br>2005-04-24 14:58:18,670 INFO [org.springframework.web.servlet.DispatcherServlet] - Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@318309]<br>2005-04-24 14:58:18,675 INFO [org.springframework.web.servlet.DispatcherServlet] - Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver@c11e94]<br>2005-04-24 14:58:18,681 INFO [org.springframework.web.servlet.DispatcherServlet] - No HandlerAdapters found in servlet 'springapp': using default<br>2005-04-24 14:58:18,700 INFO [org.springframework.web.servlet.DispatcherServlet] - No ViewResolvers found in servlet 'springapp': using default<br>2005-04-24 14:58:18,700 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'springapp': initialization completed in 439 ms<br>2005-04-24 14:58:18,704 INFO [org.springframework.web.servlet.DispatcherServlet] - Servlet 'springapp' configured successfully</font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><strong>Step 12 – Create a View</strong> </p> <p style="MARGIN-BOTTOM: 0in">Now it is time to create our first view. I will use a JSP page that I decided to name hello.jsp. I'll put it in the war directory to begin with.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width="90%" border=1> <colgroup> <col width=256></colgroup> <tbody> <tr> <td vAlign=top width="100%" bgColor=#ffcc99> <p><font face="Nimbus Mono L"><font size=2><strong>springapp/war/hello.jsp</strong> </font></font></p> </td> </tr> <tr> <td vAlign=top width="100%" bgColor=#ffffcc> <pre><html><br><head><title>Example :: Spring Application</title></head><br><body><br><h1>Hello - Spring Application</h1><br><p>Greetings.</p><br></body><br></html></pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">Nothing fancy here, but it will do for now. Next we have to modify the SpringappController to forward to this view.</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=876 border=1> <colgroup> <col width=866></colgroup> <tbody> <tr> <td vAlign=top width=866 bgColor=#ffcc99> <p><strong><font size=2><font face="Nimbus Mono L">springapp/src/SpringappController.java</font> </font></strong></p> </td> </tr> <tr> <td vAlign=top width=866 bgColor=#ffffcc> <pre>import org.springframework.web.servlet.mvc.Controller;<br>import org.springframework.web.servlet.ModelAndView;<br><br>import javax.servlet.ServletException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br><br>import java.io.IOException;<br><br><font color=#800000>import org.apache.commons.logging.Log;</font><font color=#800000>import org.apache.commons.logging.LogFactory;</font> public class SpringappController implements Controller { <font color=#800000> /** Logger for this class and subclasses */</font><font color=#800000> protected final Log logger = LogFactory.getLog(getClass());</font> public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { <font color=#800000>logger.info("SpringappController - returning hello view");</font> return new ModelAndView("<font color=#800000>hello.jsp</font>");<br> }<br>}</pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in">While I was modifying this class, I also added a logger so we can verify that we actually got here. Changes are highlighted in <font color=#800000>red</font>. The model that this class returns is actually resolved via a ViewResolver. Since we have not specified a specific one, we are going to get a default one that just forwards to a url matching the name of the view specified. We will modify this later on.</p> <p style="MARGIN-BOTTOM: 0in">Now compile and deploy the application. After instructing Tomcat to stop and then start the application, everything should get reloaded.</p> <p style="MARGIN-BOTTOM: 0in">Let's try it in a browser – enter the url <a href="http://localhost:8080/springapp/hello.htm">http://localhost:8080/springapp/hello.htm</a> and we should see the following:</p> <p style="MARGIN-BOTTOM: 0in"><img height=572 src="file:///G:/Guest%20Documents/topquan/develop/spring-framework-1.2.8/docs/MVC-step-by-step/Spring-MVC-step-by-step_html_m3871950e.png" width=742 align=left border=0 name=Graphic2> <br clear=left><br></p> <p style="MARGIN-BOTTOM: 0in">We can also check the log – I'm only showing the last entries, but we can see that the controller did get invoked and that it forwarded to the hello view. (/Users/trisberg/jakarta-tomcat-5.0.28/logs/springapp.log)</p> <table borderColor=#000000 cellSpacing=0 cellPadding=4 width=1226 border=1> <colgroup> <col width=1216></colgroup> <tbody> <tr> <td vAlign=top width=1216 bgColor=#e6e6ff> <pre> <font color=#280099>2005-04-24 15:01:56,217 INFO [org.springframework.web.servlet.DispatcherServlet] - FrameworkServlet 'springapp': initialization completed in 372 ms<br>2005-04-24 15:01:56,217 INFO [org.springframework.web.servlet.DispatcherServlet] - Servlet 'springapp' configured successfully<br>2005-04-24 15:03:57,908 INFO [SpringappController] - SpringappController - returning hello view</font> <font color=#280099> </font> </pre> </td> </tr> </tbody> </table> <p style="MARGIN-BOTTOM: 0in"><br></p> <p style="MARGIN-BOTTOM: 0in"><strong>Summary</strong> </p> <p style="MARGIN-BOTTOM: 0in">Let's take quick look at the parts of our application that we have created so far.</p> <ol> <li> <p style="MARGIN-BOTTOM: 0in">An introduction page <strong>index.jsp</strong> that does not do anything useful. It was just used to test our setup. We will later change this to actually provide a link into our application.</p> <li> <p style="MARGIN-BOTTOM: 0in">A DispatcherServlet with a corresponding <strong>springapp-servlet.xml</strong> configuration file.</p> <li> <p style="MARGIN-BOTTOM: 0in">A controller <strong>springappController.java</strong> with limited functionality – it just forwards a ModelAndView to the ViewResolver. Actually, we only have an empty model so far, but we will fix this later.</p> <li> <p style="MARGIN-BOTTOM: 0in">A view <strong>hello.jsp</strong> that again is extremely basic. But the whole setup works and we are now ready to add more functionality.</p> </li> </ol> <p style="MARGIN-BOTTOM: 0in"><br></p> <img src ="http://www.aygfsteel.com/topquan/aggbug/62673.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:21 <a href="http://www.aygfsteel.com/topquan/articles/62673.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>eclipse下struts+spring+hibernate快速入门(二)http://www.aygfsteel.com/topquan/articles/62672.htmltopquantopquanWed, 09 Aug 2006 15:15:00 GMThttp://www.aygfsteel.com/topquan/articles/62672.htmlhttp://www.aygfsteel.com/topquan/comments/62672.htmlhttp://www.aygfsteel.com/topquan/articles/62672.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/62672.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/62672.htmlWeb层.
创徏Struts ActionåQŒäؓ了在一个action中实现CRUD操作åQŒAction¾l§æ‰¿äº†DispatchActionæ ÒŽ®å‚数军_®šè°ƒç”¨æ–ÒŽ³•。在src/com.jandar.web.struts.action下创建UserAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import com.jandar.model.User;
import com.jandar.service.spring.UserManager;
public class UserAction extends DispatchAction {
private static Log log = LogFactory.getLog(UserAction.class);
private UserManager mgr = null;
public void setUserManager(UserManager userManager) {
this.mgr = userManager;
}
public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering ''delete'' method...");
}
mgr.removeUser(request.getParameter("user.id"));
ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.deleted"));
saveMessages(request, messages);
return list(mapping, form, request, response);
}
public ActionForward edit(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering ''edit'' method...");
}
DynaActionForm userForm = (DynaActionForm) form;
String userId = request.getParameter("id");
// null userId indicates an add
if (userId != null) {
User user = mgr.getUser(userId);
if (user == null) {
ActionErrors errors = new ActionMessages();
errors.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.missing"));
saveErrors(request, errors);
return mapping.findForward("list");
}
userForm.set("user", user);
}
return mapping.findForward("edit");
}
public ActionForward list(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering ''list'' method...");
}
request.setAttribute("users", mgr.getUsers());
return mapping.findForward("list");
}
public ActionForward save(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
if (log.isDebugEnabled()) {
log.debug("entering ''save'' method...");
}
// run validation rules on this form
ActionErrors errors = form.validate(mapping, request);
if (!errors.isEmpty()) {
saveErrors(request, errors);
return mapping.findForward("edit");
}
DynaActionForm userForm = (DynaActionForm) form;
mgr.saveUser((User)userForm.get("user"));
ActionMessages messages = new ActionMessages();
messages.add(ActionMessages.GLOBAL_MESSAGE,
new ActionMessage("user.saved"));
saveMessages(request, messages);
return list(mapping, form, request, response);
}
public ActionForward unspecified(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
return list(mapping, form, request, response);
}
}
UserAction.java通过UserManger讉K—®ä¸šåŠ¡å±‚ï¼ŒUserManager通过依赖注入
2åQ?创徏struts ActionFrom
可以在src/com.jandar.web.struts.form下创å»ÞZ¸€ä¸ªUserForm.javaçš„struts ActionFormåQŒæˆ‘们也可以采用已徏好的模型来配¾|®form bean即采用动态form
org.apache.struts.validator.DynaValidatorForm 同时指定property ä¸?br>com.jandar.model.User详见struts-config.xml配置文äšg.

配置struts-config.xml
1åQ?配置struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"<struts-config>
<!-- ======================================== Form Bean Definitions -->
<form-beans>
<form-bean
name="userForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="user" type="com.jandar.model.User"/>
</form-bean>
</form-beans>
<!-- =================================== Global Forward Definitions -->
<global-forwards>
</global-forwards>
<!-- =================================== Action Mapping Definitions -->
<action-mappings>
<action path="/user" type="com.jandar.web.struts.action.UserAction "
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
</action-mappings>
<!-- ================================ Message Resources Definitions -->
<message-resources parameter="messages"/>
</struts-config>
2åQ?通过struts-config.xml把strutså’Œspring¾l“合èµäh¥
UserAction.java中的UserManager需要通过依赖注入åQŒé€šè¿‡plug-in技术将spring加到struts中,在struts-config.xml中增加一下代ç ?br><plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml,
/WEB-INF/action-servlet.xml"/>
</plug-in>
让struts启动同时初始化springåQŒè¯»å–spring的配¾|®æ–‡ä»¶applicationContext.xml,òq¶ä¸”把strutsçš„action也交¾l™spring½Ž¡ç†åQŒæŠŠaction配置到action-servlet.xmlä¸?br>新徏action-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"
<beans>
<bean name="/user" class="com.jandar.web.struts.action.UserAction" singleton="false">
<property name="userManager"><ref bean="userManager"/></property>
</bean>
</beans>
同时ž®†action映射到org.springframework.web.struts.DelegatingActionProxy即修æ”?br><action path="/user" type="org.springframework.web.struts.DelegatingActionProxy"
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
3åQ?新徏web.xml配置文äšg
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="

xmlns:xsi="

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>3</param-value>

</init-param>

<init-param>

<param-name>detail</param-name>

<param-value>3</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>


<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>


<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>


</web-app>

4åQ?新徏index.jsp,userList.jsp,userForm.jsp
index.jsp
<%@ page language="java"%>

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="<html:html locale="true">

<head>

<html:base />


<title>index.jsp</title>

</head>


<body>

<html:link href="user.do?method=list">List all user</html:link>

</body>

</html:html>

userForm.jsp
<%@ page language="java"%>
<%@ taglib uri="
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html locale="true">
<head>
<html:base />
<title>userform.jsp</title>
</head>
<body>
<html:form action="user.do?method=save" method="post" focus="id">
<html:hidden property="user.id"/>
<table border="0">
<tr>
<td>id:</td>
<td><html:text property="user.firstname"/></td>
</tr>
<tr>
<td>lastname:</td>
<td><html:text property="user.lastname" /></td>
</tr>
<tr>
<td colspan="2" align="center"><html:submit property="tijiao"/></td>
</tr>
</table>
</html:form>
</body>
</html:html>
userList.jsp
<%@ page language="java"%>
<%@ taglib uri="
<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<%@ taglib uri="<html:html locale="true">
<head>
<html:base />
<title>userList.jsp</title>
</head>
<body>
This a struts page. <br>
<table class="list">
<thead>
<tr>
<th>id</th>
<th>firstName</th>
<th>lastName</th>
</tr>
</thead>
<tbody>
<logic:iterate id="user" name="users">
<tr>
<td>
<a href="user.do?method=edit&amp;id=<bean:write name="user" property="id"/>"><bean:write name="user" property="id"/></a>
</td>
<td><bean:write name="user" property="firstName"/></td>

<td><bean:write name="user" property="lastName"/></td></tr>
</logic:iterate>
</tbody>
</table>
</body>
</html:html>



]]>
eclipse下struts+spring+hibernate快速入门(一åQ?/title><link>http://www.aygfsteel.com/topquan/articles/62670.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:14:00 GMT</pubDate><guid>http://www.aygfsteel.com/topquan/articles/62670.html</guid><wfw:comment>http://www.aygfsteel.com/topquan/comments/62670.html</wfw:comment><comments>http://www.aygfsteel.com/topquan/articles/62670.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/topquan/comments/commentRss/62670.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/topquan/services/trackbacks/62670.html</trackback:ping><description><![CDATA[<p>本文是开发基于springçš„web应用的入门文章,前端采用Struts MVC框架åQŒä¸­é—´å±‚采用springåQŒåŽå°é‡‡ç”¨Hibernateã€?<br>概览<br>本文包含以下内容åQ?<br>•配置Hibernate和事åŠ?•装蝲Springçš„applicationContext.xmlæ–‡äšg <br>•建立业务层和DAO之间的依赖关¾p?•ž®†Spring应用到Strutsä¸?<br>˜q™ä¸ªä¾‹å­æ˜¯å¾ç«‹ä¸€ä¸ªç®€å•çš„web应用åQŒå«MyUsers,完成用户½Ž¡ç†æ“ä½œåQŒåŒ…含简单的数据库增åQŒåˆ åQŒæŸ¥åQŒè¯¥å³CRUDåQˆæ–°å»ºï¼Œè®‰K—®åQŒæ›´æ–ŽÍ¼Œåˆ é™¤åQ‰æ“ä½œã€‚这是一个三层的web应用åQŒé€šè¿‡ActionåQˆStrutsåQ‰è®¿é—®ä¸šåС层åQŒä¸šåŠ¡å±‚è®‰K—®DAO。应用的æ€ÖM½“¾l“æž„åQä»ŽwebåQˆUserActionåQ‰åˆ°ä¸­é—´å±‚(UserManageråQ‰ï¼Œå†åˆ°æ•°æ®è®‰K—®å±‚(UserDAOåQ‰ï¼Œç„¶åŽž®†ç»“果返回ã€?<br>Spring层的真正强大在于它的声明型事务处理,帮定和对持久层支持(例如Hiberateå’ŒiBATISåQ?<br>以下是完成这个例子的步骤åQ?<br> 1åQ‰å®‰è£…Eclipse插äšg 2åQ‰æ•°æ®åº“廸™¡¨ 3åQ‰é…¾|®Hibernateå’ŒSpring <br>4åQ‰å¾ç«‹Hibernate DAO接口的实现类 5åQ‰è¿è¡Œæµ‹è¯•ç±»åQŒæµ‹è¯•DAOçš„CRUD操作 <br>6åQ‰åˆ›å»ÞZ¸€ä¸ªå¤„理类åQŒå£°æ˜Žäº‹åŠ?nbsp; 7åQ‰åˆ›å»ºStruts Action的测试类 <br>8åQ‰åˆ›å»ºweb层的Actionå’Œmodel 9åQ‰è¿è¡ŒAction的测试类‹¹‹è¯•CRUD操作 <br>10åQ‰åˆ›å»ºjspæ–‡äšg通过‹¹è§ˆå™¨è¿›è¡ŒCRUD操作 11åQ‰é€šè¿‡‹¹è§ˆå™¨æ ¡éªŒjsp <br>开发环å¢?br>Eclipse3.0.1 , MyEclispe 3.8.4, MySQL4.1.8, spring-framework-1.2.6-with-dependencies,Tomcat5.0<br>   数据库徏è¡?nbsp;  use appfuse;<br>CREATE TABLE app_user (<br>  id int(11) NOT NULL auto_increment,<br>  firstname varchar(20) NOT NULL,<br>  lastname varchar(20) ,<br>  PRIMARY KEY  (id)<br>);<br>    新徏™å¹ç›®<br>新徏一个web projectåQŒåˆ†åˆ«add struts,hibernate capabilities.ž®†spring 包中的dist<a></a><a></a>æ–‡äšg夹中的jaræ–‡äšg拯‚´åˆ°WEB-INF/lib中ã€?br>创徏持久层O/R mapping <br>1åQ?在src/com.jandar.model下用hibernate插äšg从数据库导出app_userçš?hbm.xmlæ–‡äšg改名为User.hbm.xml <br><?xml version="1.0"?><br><!DOCTYPE hibernate-mapping PUBLIC<br>                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"<br>                            "<a ></p> <p><!-- DO NOT EDIT: This is a generated file that is synchronized --><br><!-- by MyEclipse Hibernate tool integration.                   --><br><!-- Created Mon Jul 24 11:48:15 CST 2006                         --><br><hibernate-mapping package=""></p> <p>    <class name="AppUser" table="app_user"><br>        <id name="id" column="id" type="integer"><br>            <generator class="identity"/><br>        </id><br> <br>        <property name="firstName" column="firstname" type="string"  not-null="true" /><br>        <property name="lastName" column="lastname" type="string" /><br>    </class><br>    <br></hibernate-mapping><br>2åQŽåœ¨com.jandar.model下分别徏 BaseObject.java å’ŒUser.java<br>package com.jandar.model;<br>import java.io.Serializable; <br>import org.apache.commons.lang.builder.EqualsBuilder; <br>import org.apache.commons.lang.builder.HashCodeBuilder; <br>import org.apache.commons.lang.builder.ToStringBuilder; <br>import org.apache.commons.lang.builder.ToStringStyle; <br>public class BaseObject implements Serializable { <br>public String toString() { <br>return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); <br>} <br>public boolean equals(Object o) { <br>return EqualsBuilder.reflectionEquals(this, o); <br>}<br> public int hashCode() { <br>return HashCodeBuilder.reflectionHashCode(this); <br>} <br>} <br>package com.jandar.model;<br>public class User extends BaseObject { <br>private Long id; <br>private String firstName; <br>private String lastName; <br>/** <br>* @return Returns the id. <br>*/ <br>public Long getId() { <br>return id; <br> } <br>/** <br> * @param id The id to set. <br>*/ <br>public void setId(Long id) { <br>this.id = id; <br>}<br>public void getFirstName() { <br>return firstName; <br>}</p> <p>public void setFirstName(String firstName) { <br>this.firstName = firstName; <br>} <br> public String getLastName() { <br> return lastName; <br>} <br>public void setLastName(String lastName) { <br>this.lastName = lastName; <br>} <br>}<br>创徏DAOåQŒè®¿é—®å¯¹è±?<br>1åQ?在src/com.jandar.service.dao新徏IDAO.java接口åQŒæ‰€æœ‰çš„DAO都ç‘ô承该接口 <br>package com.jandar.service.dao; <br>public interface IDAO { <br>} <br>2åQ?在src/com.jandar.service.dao下新建IUserDAO.java接口 <br>package com.jandar.service.dao;<br>import java.util.List;<br>public interface IUserDAO extends IDAO { <br>List getUsers(); <br>User getUser(Integer userid); <br>void saveUser(User user); <br>void removeUser(Integer id); <br>} <br>该接口提供了讉K—®å¯¹è±¡çš„æ–¹æ³•, <br>3åQ?在src/com.jandar.service.dao.hibernate下新建UserDAOHiberante.java <br>package com.jandar.service.dao.hibernate;<br>import java.util.List; <br>import org.apache.commons.logging.Log; <br>import org.apache.commons.logging.LogFactory; <br>import org.springframework.orm.hibernate.support.HibernateDaoSupport; <br>import com.jandar.model.User; <br>import com.jandar.service.dao.IUserDAO; <br>public class UserDaoHibernate extends HibernateDaoSupport implements IUserDAO { <br>private Log log=LogFactory.getLog(UserDaoHibernate.class); <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.dao.IUserDAO#getUsers() <br>*/ <br>public List getUsers() { <br>return getHibernateTemplate().find("from User"); <br>} <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.dao.IUserDAO#getUser(java.lang.Long) <br>*/ <br>public User getUser(Integer id) { <br>// TODO 自动生成æ–ÒŽ³•存根 <br>return (User) getHibernateTemplate().get(User.class,id); <br>} <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.dao.IUserDAO#saveUser(com.jandar.model.User) <br>*/ <br>public void saveUser(User user) { <br>log.debug("xxxxxxx"); <br>System.out.println("yyyy"); <br>getHibernateTemplate().saveOrUpdate(user); <br>if(log.isDebugEnabled()) <br>{ <br>log.debug("userId set to "+user.getId()); <br>} <br>} <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.dao.IUserDAO#removeUser(java.lang.Long) <br>*/ <br>public void removeUser(Integer id) { <br>Object user=getHibernateTemplate().load(User.class,id); <br>getHibernateTemplate().delete(user); <br>if(log.isDebugEnabled()){ <br>log.debug("del user "+id); <br>} <br>} <br>} <br>在这个类中实çŽîCº†IUserDAO接口的方法,òq¶ä¸”¾l§æ‰¿äº†HibernateDAOSupport¾c…R€‚这个类的作用是通过hibernate讉K—®ã€æ“ä½œå¯¹è±¡ï¼Œ˜q›è€Œå®žçŽ°å¯¹æ•°æ®åº“çš„æ“ä½œã€?<br>创徏业务层,声明事务 <br>业务层主要处理业务逻辑åQŒæä¾›ç»™web层友好的讉K—®æŽ¥å£å’Œå®žçŽ°è®¿é—®DAO层。用业务层的另一个好处是åQŒå¯ä»¥é€‚应数据讉K—®å±‚从Hibernate技术è{¿UÕdˆ°å…¶ä»–数据讉K—®æŠ€æœ¯ã€?<br>1åQ?在src/com.jandar.service下新å»ÞZ¸€ä¸ªIUserManager接口åQŒè¯¥æŽ¥å£æœ‰å‡ ä¹ŽäºŽIUserDAO同样的方法,不同的是处理参数åQŒåº”为IUserManager是供web层访问的ã€?<br>package com.jandar.service;<br>import java.util.List;<br>import com.jandar.model.User;<br>public interface IUserManager { <br>User getUser(String userid); <br>List getUsers(); <br>User saveUser(User user); <br>void removeUser(String userid); <br>} <br>2åQ?在src/com.jandar.service.spring下新建IUserManager实现¾c»ï¼ŒUserManager.java <br>package com.jandar.service.spring; <br>import java.util.List; <br>import org.apache.commons.logging.Log; <br>import org.apache.commons.logging.LogFactory; <br>import com.jandar.model.User; <br>import com.jandar.service.IUserManager; <br>import com.jandar.service.dao.IUserDAO;  <br>public class UserManager implements IUserManager { <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.service.IUserManager#getUser(java.lang.String) <br>*/ <br>private static Log log=LogFactory.getLog(UserManager.class); <br>public IUserDAO userDao; <br>/** <br>* @return ˜q”回 userDaoã€?<br>*/ <br>public IUserDAO getUserDao() { <br>return userDao; <br>} <br>/** <br>* @param userDao 要设¾|®çš„ userDaoã€?<br>*/ <br>public void setUserDao(IUserDAO userDao) { <br>this.userDao = userDao; <br>} <br>public User getUser(String userid) { <br>User user=userDao.getUser(Integer.valueOf(userid)); <br>if(user==null){ <br>log.warn(" user id "+userid+" not found in database"); <br>} <br>if(log.isDebugEnabled()){ <br>log.debug("get a user with id "+userid); <br>} <br>return user; <br>} <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.service.IUserManager#getUsers() <br>*/ <br>public List getUsers() { <br>// TODO 自动生成æ–ÒŽ³•存根 <br>return userDao.getUsers(); <br>} <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.service.IUserManager#saveUser(com.jandar.model.User) <br>*/ <br>public User saveUser(User user) { <br>// TODO 自动生成æ–ÒŽ³•存根 <br>userDao.saveUser(user); <br>return user; <br>} <br>/* åQˆéž JavadocåQ?<br>* @see com.jandar.service.IUserManager#removeUser(java.lang.String) <br>*/ <br>public void removeUser(String userid) { <br>// TODO 自动生成æ–ÒŽ³•存根 <br>userDao.removeUser(Integer.valueOf(userid)); <br>} <br>} <br>UserManager.java通过讉K—®dao接口实现业务逻辑和数据库操作。同时该¾cÖM¸­æä¾›äº†setæ–ÒŽ³•åQŒè¿ç”¨äº†Spring的依赖注入机制。但ž®šæœªä½¿ç”¨springçš„AOP和声明事务ã€?<br>配置applicationContext.xml <br>在WEB-INF 下新建applicationContext.xml<br><?xml version="1.0" encoding="UTF-8"?></p> <p><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"</p> <p>"<a ></p> <p><br><beans></p> <p><br><bean id="dataSource" </p> <p>class="org.springframework.jdbc.datasource.DriverManagerDataSource"></p> <p><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property></p> <p><property name="url"><value>jdbc:mysql://localhost:3306/appfuse</value></property></p> <p><property name="username"><value>root</value></property></p> <p><!-- Make sure <value> tags are on same line - if they''re not, </p> <p>authentication will fail --></p> <p><property name="password"><value>root</value></property></p> <p></bean></p> <p><br><!-- Hibernate SessionFactory --></p> <p><bean id="sessionFactory" </p> <p>class="org.springframework.orm.hibernate.LocalSessionFactoryBean"></p> <p><property name="dataSource"><ref local="dataSource"/></property></p> <p><property name="mappingResources"></p> <p><list></p> <p><value>com/jandar/model/User.hbm.xml</value></p> <p></list></p> <p></property></p> <p><property name="hibernateProperties"></p> <p><props></p> <p><prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop></p> <p><prop key="hibernate.hbm2ddl.auto">create</prop></p> <p></props></p> <p></property></p> <p></bean></p> <p><br><!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --></p> <p><bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"></p> <p><property name="sessionFactory"><ref local="sessionFactory"/></property></p> <p></bean></p> <p><br><bean id="userDAO" class="com.jandar.service.dao.hibernate.UserDAOHibernate"></p> <p><property name="sessionFactory"><ref local="sessionFactory"/></property></p> <p></bean> </p> <p><br><bean id="userManagerTarget" class="com.jandar.service.spring.UserManager"></p> <p><property name="userDAO"><ref local="userDAO"/></property></p> <p></bean></p> <p><br><bean id="userManager" </p> <p>class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"></p> <p><property name="transactionManager"><ref local="transactionManager"/></property></p> <p><property name="target"><ref local="userManagerTarget"/></property></p> <p><property name="transactionAttributes"></p> <p><props></p> <p><prop key="save*">PROPAGATION_REQUIRED</prop></p> <p><prop key="remove*">PROPAGATION_REQUIRED</prop></p> <p><prop key="*">PROPAGATION_REQUIRED,readOnly</prop></p> <p></props></p> <p></property><br></bean></p> <p><bean name="/user" class="com.jandar.web.struts.action.UserAction"<br>singleton="false"><br><property name="mgr"><br><ref bean="userManager" /><br></property><br></bean></p> <p><br></beans><br></p> <p> </p> <p class=diaryFoot></p> <img src ="http://www.aygfsteel.com/topquan/aggbug/62670.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:14 <a href="http://www.aygfsteel.com/topquan/articles/62670.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>˜q›å…¥ Spring MVChttp://www.aygfsteel.com/topquan/articles/62658.htmltopquantopquanWed, 09 Aug 2006 14:26:00 GMThttp://www.aygfsteel.com/topquan/articles/62658.htmlhttp://www.aygfsteel.com/topquan/comments/62658.htmlhttp://www.aygfsteel.com/topquan/articles/62658.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/62658.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/62658.htmlSpring MVC 框架

  Spring 框架提供了构å»?Web 应用½E‹åºçš„全功能 MVC 模块。ä‹Éç”?Spring 可插入的 MVC æž¶æž„åQŒå¯ä»¥é€‰æ‹©æ˜¯ä‹É用内¾|®çš„ Spring Web 框架˜q˜æ˜¯ Struts ˜q™æ ·çš?Web 框架。通过½{–略接口åQŒSpring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer PagesåQˆJSPåQ‰æŠ€æœ¯ã€Velocity、Tiles、iText å’?POI。Spring MVC 框架òq¶ä¸çŸ¥é“使用的视图,所以不会强˜q«æ‚¨åªä‹Éç”?JSP 技术。Spring MVC 分离了控制器、模型对象、分‹z‘Ö™¨ä»¥åŠå¤„理½E‹åºå¯¹è±¡çš„è§’è‰ÔŒ¼Œ˜q™ç§åˆ†ç¦»è®©å®ƒä»¬æ›´å®ÒŽ˜“˜q›è¡Œå®šåˆ¶ã€?/p>

  Spring çš?Web MVC 框架是围¾l?DispatcherServlet 设计的,它把è¯äh±‚分派¾l™å¤„理程序,同时带有可配¾|®çš„处理½E‹åºæ˜ å°„、视图解析、本地语­a€ã€ä¸»é¢˜è§£æžä»¥åŠä¸Šè½½æ–‡ä»¶æ”¯æŒã€‚默认的处理½E‹åºæ˜¯éžå¸¸ç®€å•çš„ Controller 接口åQŒåªæœ‰ä¸€ä¸ªæ–¹æ³?ModelAndView handleRequest(request, response)。Spring 提供了一个控制器层次¾l“æž„åQŒå¯ä»¥æ´¾ç”Ÿå­¾c…R€‚如果应用程序需要处理用戯‚¾“入表单,那么可以¾l§æ‰¿ AbstractFormController。如果需要把多页输入处理åˆîC¸€ä¸ªè¡¨å•,那么可以¾l§æ‰¿ AbstractWizardFormControllerã€?/p>

  ½CÞZ¾‹åº”用½E‹åºæœ‰åŠ©äºŽç›´è§‚åœ°å­¦ä¹ ˜q™äº›ç‰ÒŽ€§ã€‚银行应用程序允许用æˆäh£€ç´¢ä»–们的帐户信息。在构徏银行应用½E‹åºçš„过½E‹ä¸­åQŒå¯ä»¥å­¦åˆ°å¦‚何配¾|?Spring MVC 框架和实现框架的视图层,视图层包æ‹?JSTL 标记åQˆç”¨äºŽæ˜¾½Cø™¾“出的数据åQ‰å’ŒJavaServer Pages 技术ã€?/p>

  配置 Spring MVC

  要开始构建示例应用程序,请配¾|?Spring MVC çš?DispatcherServlet。请åœ?web.xml æ–‡äšg中注册所有配¾|®ã€‚清å?1 昄¡¤ºäº†å¦‚何配¾|?sampleBankingServletã€?/p>

清单 1. 配置 Spring MVC DispatcherServlet

<servlet>
   <servlet-name>sampleBankingServlet</servlet-name>
   <servlet-class>
      org.springframework.we.servlet.DispatcherServlet
   <servlet-class>
   <load-on-startup>1<load-on-startup>
<servlet>

  DispatcherServlet 从一ä¸?XML æ–‡äšg装入 Spring 应用½E‹åºä¸Šä¸‹æ–‡ï¼ŒXML æ–‡äšg的名¿U°æ˜¯ servlet 的名¿U°åŽé¢åŠ ä¸?-servlet 。在˜q™ä¸ª½CÞZ¾‹ä¸­ï¼ŒDispatcherServlet 会从 sampleBankingServlet-servlet.xml æ–‡äšg装入应用½E‹åºä¸Šä¸‹æ–‡ã€?

  配置应用½E‹åºçš?URL

  下一步是配置惌™®© sampleBankingServlet 处理çš?URLã€‚åŒæ øP¼Œ˜q˜æ˜¯è¦åœ¨ web.xml 中注册所有这些信息ã€?/p>

清单 2. 配置惌™¦å¤„理çš?URL

<servlet-mapping>
<servlet-name> sampleBankingServlet<servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>

  装入配置文äšg

  下面åQŒè£…入配¾|®æ–‡ä»¶ã€‚äØ“äº†åšåˆ°è¿™ç‚¹ï¼Œè¯·äØ“ Servlet 2.3 规范注册 ContextLoaderListener æˆ–äØ“ Servlet 2.2 及以下的容器注册 ContextLoaderServletã€‚äØ“äº†ä¿éšœåŽå‘å…¼å®ÒŽ€§ï¼Œè¯ïL”¨ ContextLoaderServlet。在启动 Web 应用½E‹åºæ—Óž¼ŒContextLoaderServlet 会装å…?Spring 配置文äšg。清å?3 注册äº?ContextLoaderServletã€?/p>

清单 3. 注册 ContextLoaderServlet

<servlet>
  <servlet-name>context>servlet-name>
  <servlet-class>
     org.springframework.web.context.ContextLoaderServlet
  </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

  contextConfigLocation 参数定义了要装入çš?Spring 配置文äšgåQŒå¦‚下面çš?servlet 上下文所½Cºã€?/p>

<context-param>
<param-value>contextConfigLocation</param-value>
<param-value>/WEB-INF/sampleBanking-services.xml</param-value>
</context-param>

  sampleBanking-services.xml æ–‡äšg代表½CÞZ¾‹é“¶è¡Œåº”用½E‹åºæœåŠ¡çš„é…¾|®å’Œ bean 配置。如果想装入多个配置文äšgåQŒå¯ä»¥åœ¨ <param-value> 标记中用逗号作分隔符ã€?/p>

  Spring MVC ½CÞZ¾‹

  ½CÞZ¾‹é“¶è¡Œåº”用½E‹åºå…è®¸ç”¨æˆ·æ ÒŽ®æƒŸä¸€çš?ID 和口令查看帐户信息。虽ç„?Spring MVC 提供了其他选项åQŒä½†æ˜¯æˆ‘ž®†é‡‡ç”?JSP æŠ€æœ¯ä½œä¸ø™§†å›ùN¡µé¢ã€‚这个简单的应用½E‹åºåŒ…含一个视å›ùN¡µç”¨äºŽç”¨æˆ·è¾“å…¥åQˆID 和口令)åQŒå¦ä¸€™å‰|˜¾½Cºç”¨æˆïLš„帐户信息ã€?/p>

  我从 LoginBankController 开始,它扩展了 Spring MVC çš?SimpleFormController。SimpleFormContoller 提供了显½CÞZ»Ž HTTP GET è¯äh±‚接收到的表单的功能,以及处理ä»?HTTP POST 接收到的相同表单数据的功能。LoginBankController ç”?AuthenticationService å’?AccountServices 服务˜q›è¡ŒéªŒè¯åQŒåƈ执行帐户‹zÕdЍã€?#8220; 配置视图属æ€?”一节中的清å?5 描述了如何把 AuthenticationService å’?AccountServices ˜qžæŽ¥åˆ?LoginBankControllerã€?清单 4 昄¡¤ºäº?LoginBankController 的代码ã€?/p>

清单 4. LoginBankController 扩展 SimpleFormController

public class LoginBankController extends SimpleFormController {

   public LoginBankController(){

   }

   protected ModelAndView onSubmit(Object command) throws Exception{

      LoginCommand loginCommand = (LoginCommand) command;
      authenticationService.authenticate(loginCommand);
      AccountDetail accountdetail = accountServices.getAccountSummary(loginCommand.getUserId());
      return new ModelAndView(getSuccessView(),"accountdetail",accountdetail);
   }

   private AuthenticationService authenticationService;

   private AccountServices accountServices;

   public AccountServices getAccountServices() {
      return accountServices;
   }

   public void setAccountServices(AccountServices accountServices) {
      this.accountServices = accountServices;
   }

   public AuthenticationService getAuthenticationService() {
      return authenticationService;
   }

   public void setAuthenticationService(
         AuthenticationService authenticationService) {
      this.authenticationService = authenticationService;
   }
}

  配置视图属�/strong>

  下面åQŒå¿…™åÀL³¨å†Œåœ¨æŽ¥æ”¶åˆ?HTTP GET è¯äh±‚时显½Cºçš„™åµé¢ã€‚在 Spring 配置中用 formView 属性注册这个页面,如清å?5 所½Cºã€‚sucessView 属性代表表单数据提交而且 doSubmitAction() æ–ÒŽ³•中的逻辑成功执行之后昄¡¤ºçš„页面。formView å’?sucessView 属性都代表被定义的视图的逻辑名称åQŒé€»è¾‘名称映射到实际的视图™åµé¢ã€?/p>

清单 5. 注册 LoginBankController

   <bean id="loginBankController"
         class="springexample.controller.LoginBankController">
      <property name="sessionForm"><value>true</value></property>
   <property name="commandName"><value>loginCommand</value></property>
   <property name="commandClass">
      <value>springexample.commands.LoginCommand</value>
   </property>

      <property name="authenticationService">
         <ref bean="authenticationService" />
      </property>
      <property name="accountServices">
         <ref bean="accountServices" />
      </property>
      <property name="formView">
         <value>login</value>
      </property>
      <property name="successView">
         <value>accountdetail</value>
      </property>

   </bean>

  commandClass å’?commandName 标记军_®šž®†åœ¨è§†å›¾™åµé¢ä¸­æ´»åŠ¨çš„ bean。例如,可以通过 login.jsp ™åµé¢è®‰K—® loginCommand beanåQŒè¿™ä¸ªé¡µé¢æ˜¯åº”用½E‹åºçš„登录页面。一旦用æˆähäº¤äº†ç™Õd½•™åµé¢åQŒåº”用程序就可以ä»?LoginBankController çš?onSubmit() æ–ÒŽ³•中的命ä×o对象‹‚€ç´¢å‡ºè¡¨å•数据ã€?/p>

  视图解析�/strong>

  Spring MVC çš?视图解析å™?把每个逻辑名称解析成实际的资源åQŒå³åŒ…含帐户信息çš?JSP æ–‡äšg。我用的æ˜?Spring çš?InternalResourceViewResolveråQŒå¦‚ 清单 6 所½Cºã€?/p>

清单 6. InternalResourceViewResolver

<bean id="view-Resolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="viewClass">
      <value>org.springframework.web.servlet.view.JstlView</value>
   </property>
   <property name="prefix"><value>/jsp/</value></property>
   <property name="suffix"><value>.jsp</value></property>
</bean>

ã€€ã€€å› äØ“æˆ‘åœ¨ JSP ™åµé¢ä¸­ä‹É用了 JSTL 标记åQŒæ‰€ä»¥ç”¨æˆïLš„ç™Õd½•名称解析成资æº?/jsp/login.jspåQŒè€?viewClass æˆäØ“ JstlViewã€?/p>

  验证和帐æˆähœåŠ?/strong>

  ž®±åƒå‰é¢æåˆ°çš„,LoginBankController 内部˜qžæŽ¥äº?Spring çš?AccountServices å’?AuthenticationService。AuthenticationService ¾cÕd¤„理银行应用程序的验证。AccountServices ¾cÕd¤„理典型的银行服务åQŒä¾‹å¦‚查找交易和甉|±‡ã€‚清å?7 昄¡¤ºäº†é“¶è¡Œåº”用程序的验证和帐æˆähœåŠ¡çš„é…ç½®ã€?/p>

清单 7. 配置验证和帐æˆähœåŠ?/p>

<beans>

   <bean id="accountServices"
      class="springexample.services.AccountServices">
   </bean>

   <bean id="authenticationService"
      class="springexample.services.AuthenticationService">
   </bean>

</beans>

  以上服务åœ?sampleBanking-services.xml 中注册,然后装入 web.xml æ–‡äšg中,ž®±åƒ 前面讨论的那栗÷€‚控制器和服务配¾|®å¥½åŽï¼Œ˜q™ä¸ª½Ž€å•的应用½E‹åºž®±å®Œæˆäº†ã€‚现在我们来看看部çÖv和测试它时会发生什ä¹?

  部çÖv应用½E‹åº

  把示例应用程序部¾|²åœ¨ Tomcat servlet 容器中。Tomcat æ˜?Java Servlet å’?Java ServerPagest 技术的官方参考实çŽîC¸­ä½¿ç”¨çš?servlet 容器。如果以前没˜q™ä¹ˆåšè¿‡åQŒè¯· 下蝲 jakarta-tomcat-5.0.28.exe òq¶è¿è¡Œå®ƒæŠ?Tomcat 安装到自己喜‹Æ¢çš„ä»ÖM½•位置åQŒä¾‹å¦?c:\tomcat5.0ã€?/p>

  接下来,下蝲½CÞZ¾‹ä»£ç  òq‰™‡Šæ”‘Öˆ°é©±åŠ¨å™¨ï¼ˆä¾‹å¦‚ c:\ åQ‰ä¸Šã€‚创å»ÞZº† Spring ™å¹ç›®çš„æ–‡ä»¶å¤¹ä¹‹åŽåQŒæ‰“å¼€å®ƒåÆˆæŠ?spring-banking 子文件夹拯‚´åˆ?c:\tomvat5.0\webapps。spring-banking æ–‡äšgå¤ÒŽ˜¯ä¸€ä¸?Web 档案åQŒé‡Œé¢åŒ…å?Spring MVC ½CÞZ¾‹åº”用½E‹åºã€‚lib æ–‡äšg夹包含应用程序需要的 Spring 框架、与Spring 相关çš?MVC 库以å?JSTL 标记库和 jar æ–‡äšgã€?/p>

  要启åŠ?Tomcat 服务器,请ä‹É用以下命令:

  cd bin C:\Tomcat 5.0\bin> catalina.bat start

  Tomcat 应当启动òq‰™ƒ¨¾|?Spring MVC ½CÞZ¾‹åº”用½E‹åºã€?/p>

  ‹¹‹è¯•应用½E‹åº

  要测试应用程序,è¯äh‰“å¼€ Web ‹¹è§ˆå™¨ï¼ŒæŒ‡å‘ http://localhost:tomcatport/springbanking òq¶ç”¨ Tomcat 服务器实际运行的端口替换 tomcatport。应当看到图 1 所½Cºçš„ç™Õd½•屏幕。输入用æˆ?ID “admin”和口ä»?#8220;password”åQŒåƈ按下ç™Õd½•按钮。其他用æˆ?ID 或口令会造成来自验证服务的错误ã€?/p>


å›?1. Spring MVC ½CÞZ¾‹ç™Õd½•屏幕

  ç™Õd½•成功之后åQŒä¼šçœ‹åˆ°å›?2 所½Cºçš„帐户¾l†èŠ‚™åµé¢ã€?/p>


å›?2. Spring MVC ½CÞZ¾‹å¸æˆ·¾l†èŠ‚™åµé¢
Spring MVC框架的高¾U§é…¾|?br>http://dev2dev.bea.com.cn/techdoc/2006068810.html



]]>
一个Spring½E‹åº http://www.aygfsteel.com/topquan/articles/61889.htmltopquantopquanFri, 04 Aug 2006 16:56:00 GMThttp://www.aygfsteel.com/topquan/articles/61889.htmlhttp://www.aygfsteel.com/topquan/comments/61889.htmlhttp://www.aygfsteel.com/topquan/articles/61889.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/61889.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/61889.htmlSpring通过XMLæ–‡äšgåQŒå®Œæˆbean配置和bean间依赖关¾pÈš„æ³¨å…¥ã€?br>
1.需要用到的包:
spring-core.jar
spring-beans.jar
spring-context.jar
commons-logging.jar

2.Beanæ–‡äšg
HelloBean.java
package cn.blogjava.hello;

import java.util.Date;

public class HelloBean {
    
    
private String helloWord;
    
private String name;
    
private Date date;
    
    
public HelloBean() {
        
    }

    
public HelloBean(String helloWord, String name) {
        
this.helloWord = helloWord;
        
this.name = name;
    }    
    
    
public String getHelloWord() {
        
return helloWord;
    }

    
public void setHelloWord(String helloword) {
        
this.helloWord = helloword;
    }

    
public String getName() {
        
return name;
    }

    
public void setName(String name) {
        
this.name = name;
    }
    
    
public Date getDate() {
        
return date;
    }

    
public void setDate(Date date) {
        
this.date = date;
    }
}

配置文äšg
beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
    "http://www.springframework.org/dtd/spring-beans.dtd"
>
<beans>
    
<bean id="dateBean" class="java.util.Date"/>
    
<bean id="helloBean" class="cn.blogjava.hello.HelloBean" >
        
<property name="helloWord">
            
<value>Hello!</value>
        
</property>
        
<property name="name">
            
<value>YYY!</value>
        
</property>    
        
<property name="date">
            
<ref bean="dateBean" />
        
</property>                
    
</bean>
</beans>

3.‹¹‹è¯•½E‹åº
SpringDemo.java
package cn.blogjava.hello;

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

public class SpringDemo {
    
public static void main(String[] args) {
        ApplicationContext context 
= 
            
new FileSystemXmlApplicationContext("beans-config.xml");        
        HelloBean helloBean 
= (HelloBean)context.getBean("helloBean");
        System.out.print(
"Name: ");
        System.out.println(helloBean.getName());
        System.out.print(
"Word: ");
        System.out.println(helloBean.getHelloWord());
        System.out.println(helloBean.getDate());
    }
}


]]>
Spring:Bean基本½Ž¡ç† http://www.aygfsteel.com/topquan/articles/61887.htmltopquantopquanFri, 04 Aug 2006 16:55:00 GMThttp://www.aygfsteel.com/topquan/articles/61887.htmlhttp://www.aygfsteel.com/topquan/comments/61887.htmlhttp://www.aygfsteel.com/topquan/articles/61887.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/61887.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/61887.html阅读全文

]]>
在myeclipse下整合springå’Œhibernate http://www.aygfsteel.com/topquan/articles/61877.htmltopquantopquanFri, 04 Aug 2006 16:28:00 GMThttp://www.aygfsteel.com/topquan/articles/61877.htmlhttp://www.aygfsteel.com/topquan/comments/61877.htmlhttp://www.aygfsteel.com/topquan/articles/61877.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/61877.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/61877.html引用  http://www.aygfsteel.com/dyerac/archive/2006/08/04/61805.html



]]>
Struts+Spring+Hibernate¾l„合使用http://www.aygfsteel.com/topquan/articles/45101.htmltopquantopquanMon, 08 May 2006 14:46:00 GMThttp://www.aygfsteel.com/topquan/articles/45101.htmlhttp://www.aygfsteel.com/topquan/comments/45101.htmlhttp://www.aygfsteel.com/topquan/articles/45101.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/45101.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/45101.html阅读全文

]]>
Ö÷Õ¾Ö©Öë³ØÄ£°å£º ÁêË®| Í©Â®ÏØ| ÈýÃÅÏØ| ÜìÄÏÏØ| ÍûÚÓÏØ| ÑαßÏØ| çÆÔÆÏØ| ÔÆ¸¡ÊÐ| ÌÆº£ÏØ| È«½·ÏØ| °åÇÅÊÐ| ¶«°¢ÏØ| µÂÇìÏØ| ±õº£ÏØ| °²ÇðÊÐ| ÏóÖÝÏØ| ÐÅ·áÏØ| ÒÊÄÏÏØ| ¬ÊÏÏØ| ÐûÎäÇø| Âí°°É½ÊÐ| ÃñÏØ| Ñ®ÑôÏØ| Ì«ÆÍËÂÆì| Á鱦ÊÐ| ѰÎÚÏØ| ºÓÇúÏØ| ÁÚË®| ÎÄ»¯| Õ´ÒæÏØ| °²¹úÊÐ| Äϲ¿ÏØ| ÔæÑôÊÐ| ÆÁÄÏÏØ| ÁúÉ½ÏØ| ¼¯°²ÊÐ| ãòÎ÷ÏØ| èϳÇÏØ| ¹ãÎ÷| Ç­ÄÏ| ÃûÉ½ÏØ|