﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-Topquan's Blog-文章分类-Spring</title><link>http://www.blogjava.net/topquan/category/23897.html</link><description>分享价值----成就你我----我的博客----你的家</description><language>zh-cn</language><lastBuildDate>Sat, 07 Jul 2007 14:45:52 GMT</lastBuildDate><pubDate>Sat, 07 Jul 2007 14:45:52 GMT</pubDate><ttl>60</ttl><item><title>Developing a Spring Framework MVC application（四）</title><link>http://www.blogjava.net/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.blogjava.net/topquan/articles/62677.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62677.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62677.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62677.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/62677.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: 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 &#8211; 12) we configured the environment and set up a basic ap...&nbsp;&nbsp;<a href='http://www.blogjava.net/topquan/articles/62677.html'>阅读全文</a><img src ="http://www.blogjava.net/topquan/aggbug/62677.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 23:25 <a href="http://www.blogjava.net/topquan/articles/62677.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Developing a Spring Framework MVC application （三） </title><link>http://www.blogjava.net/topquan/articles/62676.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:23:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/62676.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62676.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62676.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62676.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/62676.html</trackback:ping><description><![CDATA[<p style="MARGIN-BOTTOM: 0in">This 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 &#8211; 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.</p>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 20 &#8211; <a></a>Add unit test for the SpringappController</strong> </p>
<p style="MARGIN-BOTTOM: 0in">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. </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>    &lt;target name="junit" depends="build" description="Run JUnit Tests"&gt;</font>
            <font color=#800000>        &lt;junit printsummary="on"</font>
            <font color=#800000>               fork="false"</font>
            <font color=#800000>               haltonfailure="false"</font>
            <font color=#800000>               failureproperty="tests.failed"</font>
            <font color=#800000>               showoutput="true"&gt;</font>
            <font color=#800000>            &lt;classpath refid="master-classpath"/&gt;</font>
            <font color=#800000>            &lt;formatter type="brief" usefile="false"/&gt;</font>
            <font color=#800000>            &lt;batchtest&gt;</font>
            <font color=#800000>                &lt;fileset dir="${build.dir}"&gt;</font>
            <font color=#800000>                    &lt;include name="**/Test*.*"/&gt;</font>
            <font color=#800000>                &lt;/fileset&gt;</font>
            <font color=#800000>            &lt;/batchtest&gt;</font>
            <font color=#800000>        &lt;/junit&gt;</font>
            <font color=#800000>        &lt;fail if="tests.failed"&gt;<br>        tests.failed=${tests.failed}<br></font>       &nbsp;<font color=#800000>***********************************************************</font><font color=#800000>        ***********************************************************</font><font color=#800000>        ****  One or more tests failed!  Check the output ...  ****</font><font color=#800000>        ***********************************************************</font><font color=#800000>        ***********************************************************</font><font color=#800000>        &lt;/fail&gt;</font><font color=#800000>    &lt;/target&gt;</font></pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">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. </p>
<p style="MARGIN-BOTTOM: 0in">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.</p>
<table borderColor=#000000 cellSpacing=0 cellPadding=4 width=908 border=1>
    <colgroup>
    <col width=898></colgroup>
    <tbody>
        <tr>
            <td vAlign=top width=898 bgColor=#ffcc99>
            <p><strong><font size=2><font face="Nimbus Mono L">springapp/src/tests/TestSpringappController.java</font> </font></strong></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width=898 bgColor=#ffffcc>
            <pre>package tests;<br><br>import java.util.Map;<br>import java.util.List;<br>import java.io.IOException;<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br>import javax.servlet.ServletException;<br>import junit.framework.TestCase;<br>import org.springframework.context.ApplicationContext;<br>import org.springframework.context.support.FileSystemXmlApplicationContext;<br>import org.springframework.web.servlet.ModelAndView;<br>import web.SpringappController;<br>import bus.ProductManager;<br>import bus.Product;<br><br>public class TestSpringappController extends TestCase {<br><br>    private ApplicationContext ac;<br><br>    public void setUp() throws IOException {<br>        ac = new FileSystemXmlApplicationContext("src/tests/WEB-INF/springapp-servlet.xml");<br>    }<br><br>    public void testHandleRequest() throws ServletException, IOException {<br>        SpringappController sc = (SpringappController) ac.getBean("springappController");<br>        ModelAndView mav = sc.handleRequest((HttpServletRequest) null, (HttpServletResponse) null);<br>        Map m = mav.getModel();<br>        List pl = (List) ((Map) m.get("model")).get("products");<br>        Product p1 = (Product) pl.get(0);<br>        assertEquals("Lamp", p1.getDescription());<br>        Product p2 = (Product) pl.get(1);<br>        assertEquals("Table", p2.getDescription());<br>        Product p3 = (Product) pl.get(2);<br>        assertEquals("Chair", p3.getDescription());<br>    }<br><br>}</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">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 &#8220;messageSource&#8221;, "urlMapping" and "viewResolver" bean entries since they are not needed for this test.</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/src/tests/WEB-INF/springapp-servlet.xml</font> </font></strong></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width=929 bgColor=#ffffcc>
            <pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;<br><br>&lt;!--<br>  - Application context definition for "springapp" DispatcherServlet.<br>  --&gt;<br><br><br>&lt;beans&gt;<br>    &lt;bean id="springappController" class="web.SpringappController"<font color=#800000>&gt;</font><font color=#800000><font color=#000000>&lt;property name="productManager"&gt;</font></font><font color=#000000>            &lt;ref bean="prodMan"/&gt;</font><font color=#000000>        &lt;/property&gt;</font><font color=#000000>    &lt;/bean&gt;</font><font color=#000000>    &lt;bean id="prodMan" class="bus.ProductManager"&gt;</font><font color=#000000>        &lt;property name="products"&gt;</font><font color=#000000>            &lt;list&gt;</font><font color=#000000>                &lt;ref bean="product1"/&gt;</font><font color=#000000>                &lt;ref bean="product2"/&gt;</font><font color=#000000>                &lt;ref bean="product3"/&gt;</font><font color=#000000>            &lt;/list&gt;</font><font color=#000000>        &lt;/property&gt;</font><font color=#000000>    &lt;/bean&gt;</font><font color=#000000>    &lt;bean id="product1" class="bus.Product"&gt;</font><font color=#000000>        &lt;property name="description"&gt;&lt;value&gt;Lamp&lt;/value&gt;&lt;/property&gt;</font><font color=#000000>        &lt;property name="price"&gt;&lt;value&gt;5.75&lt;/value&gt;&lt;/property&gt;</font><font color=#000000>    &lt;/bean&gt;</font><font color=#000000></font><font color=#000000>    &lt;bean id="product2" class="bus.Product"&gt;</font><font color=#000000>        &lt;property name="description"&gt;&lt;value&gt;Table&lt;/value&gt;&lt;/property&gt;</font><font color=#000000>        &lt;property name="price"&gt;&lt;value&gt;75.25&lt;/value&gt;&lt;/property&gt;</font><font color=#000000>    &lt;/bean&gt;</font><font color=#000000>    &lt;bean id="product3" class="bus.Product"&gt;</font><font color=#000000>        &lt;property name="description"&gt;&lt;value&gt;Chair&lt;/value&gt;&lt;/property&gt;</font><font color=#000000>        &lt;property name="price"&gt;&lt;value&gt;22.79&lt;/value&gt;&lt;/property&gt;</font><font color=#000000>    &lt;/bean&gt;</font>
            &lt;/beans&gt;        </pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">When you run this test, you should see a lot of log messages from the loading of the application context.</p>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 21 &#8211; Add unit test and new functionality for ProductManager</strong> </p>
<p style="MARGIN-BOTTOM: 0in">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.</p>
<table borderColor=#000000 cellSpacing=0 cellPadding=4 width=908 border=1>
    <colgroup>
    <col width=898></colgroup>
    <tbody>
        <tr>
            <td vAlign=top width=898 bgColor=#ffcc99>
            <p><strong><font size=2><font face="Nimbus Mono L">springapp/src/tests/TestProductManager .java</font> </font></strong></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width=898 bgColor=#ffffcc>
            <pre>package tests;<br><br>import java.util.List;<br>import java.util.ArrayList;<br>import junit.framework.TestCase;<br>import bus.ProductManager;<br>import bus.Product;<br><br>public class TestProductManager extends TestCase {<br><br>    private ProductManager pm;<br><br>    public void setUp() {<br>        pm = new ProductManager();<br>        Product p = new Product();<br>        p.setDescription("Chair");<br>        p.setPrice(new Double("20.50"));<br>        ArrayList al = new ArrayList();<br>        al.add(p);<br>        p = new Product();<br>        p.setDescription("Table");<br>        p.setPrice(new Double("150.10"));<br>        al.add(p);<br>        pm.setProducts(al);<br>    }<br><br>    public void testGetProducs() {<br>        List l = pm.getProducts();<br>        Product p1 = (Product) l.get(0);<br>        assertEquals("Chair", p1.getDescription());<br>        Product p2 = (Product) l.get(1);<br>        assertEquals("Table", p2.getDescription());<br>    }<br><br>    public void testIncreasePrice() {<br>        pm.increasePrice(10);<br>        List l = pm.getProducts();<br>        Product p = (Product) l.get(0);<br>        assertEquals(new Double("22.55"), p.getPrice());<br>        p = (Product) l.get(1);<br>        assertEquals(new Double("165.11"), p.getPrice());<br>    }<br><br>}</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">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.</p>
<table borderColor=#000000 cellSpacing=0 cellPadding=4 width=907 border=1>
    <colgroup>
    <col width=897></colgroup>
    <tbody>
        <tr>
            <td vAlign=top width=897 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=897 bgColor=#ffffcc>
            <pre>package bus;<br><br>import java.io.Serializable;<br><font color=#800000>import java.util.ListIterator;</font>
            import java.util.List;
            public class ProductManager implements Serializable {
            private List products;
            public void setProducts(List p) {
            products = p;
            }
            public List getProducts() {
            return products;
            }
            <font color=#800000>    public void increasePrice(int pct) {</font><font color=#800000>        ListIterator li = products.listIterator();</font><font color=#800000>        while (li.hasNext()) {</font><font color=#800000>            Product p = (Product) li.next();</font><font color=#800000>            double newPrice = p.getPrice().doubleValue() * (100 + pct)/100;</font><font color=#800000>            p.setPrice(new Double(newPrice));</font><font color=#800000>        }</font><font color=#800000></font><font color=#800000>    }</font>
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">Next I build and run the tests. As you can see, this test is just like any regular test &#8211; the business classes don't depend on any of the servlet classes so these classes are very easy to test. </p>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 22 &#8211; Adding a form</strong> </p>
<p style="MARGIN-BOTTOM: 0in">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 &#8220;spring&#8221; 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 &lt;taglib&gt; entry to web.xml.</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>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'&gt;<br><br>&lt;web-app&gt;<br><br><font color=#000000>  &lt;servlet&gt;</font><font color=#000000>    &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;</font><font color=#000000>    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;</font><font color=#000000>    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;</font><font color=#000000>  &lt;/servlet&gt;</font><font color=#000000>  &lt;servlet-mapping&gt;</font><font color=#000000>    &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;</font><font color=#000000>    &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;</font><font color=#000000>  &lt;/servlet-mapping&gt;</font><font color=#000000>  &lt;welcome-file-list&gt;</font><font color=#000000>    &lt;welcome-file&gt;</font><font color=#000000>      index.jsp</font><font color=#000000>    &lt;/welcome-file&gt;</font><font color=#000000>  &lt;/welcome-file-list&gt;</font><font color=#800000>  &lt;taglib&gt;</font><font color=#800000>    &lt;taglib-uri&gt;/spring&lt;/taglib-uri&gt;</font><font color=#800000>    &lt;taglib-location&gt;/WEB-INF/spring.tld&lt;/taglib-location&gt;</font><font color=#800000>  &lt;/taglib&gt;</font>
            &lt;/web-app&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">We also have to declare this taglib in a page directive in the jsp file. We declare a form the normal way with a &lt;form&gt; tag and an &lt;input&gt; text field and a submit button. </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/priceincrease.jsp</font> </font></strong></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width="100%" bgColor=#ffffcc>
            <pre>&lt;%@ include file="/WEB-INF/jsp/include.jsp" %&gt;<br>&lt;%@ taglib prefix="spring" uri="/spring" %&gt;<br><br>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;&lt;fmt:message key="title"/&gt;&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;&lt;fmt:message key="priceincrease.heading"/&gt;&lt;/h1&gt;<br>&lt;form method="post"&gt;<br>  &lt;table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5"&gt;<br>    &lt;tr&gt;<br>      &lt;td alignment="right" width="20%"&gt;Increase (%):&lt;/td&gt;<br>      &lt;spring:bind path="priceIncrease.percentage"&gt;<br>        &lt;td width="20%"&gt;<br>          &lt;input type="text" name="percentage" value="&lt;c:out value="${status.value}"/&gt;"&gt;<br>        &lt;/td&gt;<br>        &lt;td width="60%"&gt;<br>          &lt;font color="red"&gt;&lt;c:out value="${status.errorMessage}"/&gt;&lt;/font&gt;<br>        &lt;/td&gt;<br>      &lt;/spring:bind&gt;<br>    &lt;/tr&gt;<br>  &lt;/table&gt;<br>  &lt;br&gt;<br>  &lt;spring:hasBindErrors name="priceIncrease"&gt;<br>    &lt;b&gt;Please fix all errors!&lt;/b&gt;<br>  &lt;/spring:hasBindErrors&gt;<br>  &lt;br&gt;&lt;br&gt;<br>  &lt;input type="submit" alignment="center" value="Execute"&gt;<br>&lt;/form&gt;<br>&lt;a href="&lt;c:url value="hello.htm"/&gt;"&gt;Home&lt;/a&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">The &lt;spring:bind&gt; tag is used to bind an &lt;input&gt; 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.</p>
<table borderColor=#000000 cellSpacing=0 cellPadding=4 width=875 border=1>
    <colgroup>
    <col width=865></colgroup>
    <tbody>
        <tr>
            <td vAlign=top width=865 bgColor=#ffcc99>
            <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/bus/PriceIncrease.java</strong> </font></font></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width=865 bgColor=#ffffcc>
            <pre>package bus;<br><br>import org.apache.commons.logging.Log;<br>import org.apache.commons.logging.LogFactory;<br><br>public class PriceIncrease {<br><br>    /** Logger for this class and subclasses */<br>    protected final Log logger = LogFactory.getLog(getClass());<br><br>    private int percentage;<br><br>    public void setPercentage(int i) {<br>        percentage = i;<br>        logger.info("Percentage set to " + i);<br>    }<br><br>    public int getPercentage() {<br>        return percentage;<br>    }<br><br>}</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">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.</p>
<table borderColor=#000000 cellSpacing=0 cellPadding=4 width=875 border=1>
    <colgroup>
    <col width=865></colgroup>
    <tbody>
        <tr>
            <td vAlign=top width=865 bgColor=#ffcc99>
            <p><font face="Nimbus Mono L"><font size=2><strong>springapp/src/bus/PriceIncreaseValidator.java</strong> </font></font></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width=865 bgColor=#ffffcc>
            <pre>package bus;<br><br>import java.io.Serializable;<br>import org.springframework.validation.Validator;<br>import org.springframework.validation.Errors;<br><br>import org.apache.commons.logging.Log;<br>import org.apache.commons.logging.LogFactory;<br><br>public class PriceIncreaseValidator implements Validator {<br>    private int DEFAULT_MIN_PERCENTAGE = 0;<br>    private int DEFAULT_MAX_PERCENTAGE = 50;<br>    private int minPercentage = DEFAULT_MIN_PERCENTAGE;<br>    private int maxPercentage = DEFAULT_MAX_PERCENTAGE;<br><br>    /** Logger for this class and subclasses */<br>    protected final Log logger = LogFactory.getLog(getClass());<br><br>    public boolean supports(Class clazz) {<br>        return clazz.equals(PriceIncrease.class);<br>    }<br><br>    public void validate(Object obj, Errors errors) {<br>        PriceIncrease pi = (PriceIncrease) obj;<br>        if (pi == null) {<br>            errors.rejectValue("percentage", "error.not-specified", null, "Value required.");<br>        }<br>        else {<br>            logger.info("Validating with " + pi + ": " + pi.getPercentage());<br>            if (pi.getPercentage() &gt; maxPercentage) {<br>                errors.rejectValue("percentage", "error.too-high",<br>                    new Object[] {new Integer(maxPercentage)}, "Value too high.");<br>            }<br>            if (pi.getPercentage() &lt;= minPercentage) {<br>                errors.rejectValue("percentage", "error.too-low",<br>                    new Object[] {new Integer(minPercentage)}, "Value too low.");<br>            }<br>        }<br>    }<br><br>    public void setMinPercentage(int i) {<br>        minPercentage = i;<br>    }<br><br>    public int getMinPercentage() {<br>        return minPercentage;<br>    }<br><br>    public void setMaxPercentage(int i) {<br>        maxPercentage = i;<br>    }<br><br>    public int getMaxPercentage() {<br>        return maxPercentage;<br>    }<br><br>}</pre>
            </td>
        </tr>
    </tbody>
</table>
<p>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.</p>
<table borderColor=#000000 cellSpacing=0 cellPadding=4 width=900 border=1>
    <colgroup>
    <col width=890></colgroup>
    <tbody>
        <tr>
            <td vAlign=top width=890 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=890 bgColor=#ffffcc>
            <pre>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"<br> "http://www.springframework.org/dtd/spring-beans.dtd"&gt;<br><br>&lt;!--<br>  - Application context definition for "springapp" DispatcherServlet.<br>  --&gt;<br><br>&lt;beans&gt;<br><br><font color=#800000>    &lt;!--  Controller for the initial "Hello" page --&gt;</font>
            &lt;bean id="springappController" class="web.SpringappController"&gt;
            &lt;property name="productManager"&gt;
            &lt;ref bean="prodMan"/&gt;
            &lt;/property&gt;
            &lt;/bean&gt;
            <font color=#800000>    &lt;!--  Validator and Form Controller for the "Price Increase" page --&gt;</font><font color=#800000>    &lt;bean id="priceIncreaseValidator" class="bus.PriceIncreaseValidator"/&gt;</font><font color=#800000>    &lt;bean id="priceIncreaseForm" class="web.PriceIncreaseFormController"&gt;</font><font color=#800000>        &lt;property name="sessionForm"&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="commandName"&gt;&lt;value&gt;priceIncrease&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="commandClass"&gt;&lt;value&gt;bus.PriceIncrease&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="validator"&gt;&lt;ref bean="priceIncreaseValidator"/&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="formView"&gt;&lt;value&gt;priceincrease&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="successView"&gt;&lt;value&gt;hello.htm&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="productManager"&gt;</font><font color=#800000>            &lt;ref bean="prodMan"/&gt;</font><font color=#800000>        &lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font>
            &lt;bean id="prodMan" class="bus.ProductManager"&gt;
            &lt;property name="products"&gt;
            &lt;list&gt;
            &lt;ref bean="product1"/&gt;
            &lt;ref bean="product2"/&gt;
            &lt;ref bean="product3"/&gt;
            &lt;/list&gt;
            &lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="product1" class="bus.Product"&gt;
            &lt;property name="description"&gt;&lt;value&gt;Lamp&lt;/value&gt;&lt;/property&gt;
            &lt;property name="price"&gt;&lt;value&gt;5.75&lt;/value&gt;&lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="product2" class="bus.Product"&gt;
            &lt;property name="description"&gt;&lt;value&gt;Table&lt;/value&gt;&lt;/property&gt;
            &lt;property name="price"&gt;&lt;value&gt;75.25&lt;/value&gt;&lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="product3" class="bus.Product"&gt;
            &lt;property name="description"&gt;&lt;value&gt;Chair&lt;/value&gt;&lt;/property&gt;
            &lt;property name="price"&gt;&lt;value&gt;22.79&lt;/value&gt;&lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"&gt;
            &lt;property name="basename"&gt;&lt;value&gt;messages&lt;/value&gt;&lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;
            &lt;property name="mappings"&gt;
            &lt;props&gt;
            &lt;prop key="/hello.htm"&gt;springappController&lt;/prop&gt;
            <font color=#800000>                &lt;prop key="/priceincrease.htm"&gt;priceIncreaseForm&lt;/prop&gt;</font>
            &lt;/props&gt;
            &lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
            &lt;property name="viewClass"&gt;
            &lt;value&gt;org.springframework.web.servlet.view.JstlView&lt;/value&gt;
            &lt;/property&gt;
            &lt;property name="prefix"&gt;&lt;value&gt;/WEB-INF/jsp/&lt;/value&gt;&lt;/property&gt;
            &lt;property name="suffix"&gt;&lt;value&gt;.jsp&lt;/value&gt;&lt;/property&gt;
            &lt;/bean&gt;
            &lt;/beans&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">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.</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/PriceIncreaseFormController.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.SimpleFormController;<br>import org.springframework.web.servlet.ModelAndView;<br>import org.springframework.web.servlet.view.RedirectView;<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>import java.util.Map;<br>import java.util.HashMap;<br><br>import org.apache.commons.logging.Log;<br>import org.apache.commons.logging.LogFactory;<br><br>import bus.Product;<br>import bus.ProductManager;<br>import bus.PriceIncrease;<br><br>public class PriceIncreaseFormController extends SimpleFormController {<br><br>    /** Logger for this class and subclasses */<br>    protected final Log logger = LogFactory.getLog(getClass());<br><br>    private ProductManager prodMan;<br><br>    public ModelAndView onSubmit(Object command)<br>            throws ServletException {<br><br>        int increase = ((PriceIncrease) command).getPercentage();<br>        logger.info("Increasing prices by " + increase + "%.");<br><br>        prodMan.increasePrice(increase);<br><br>        String now = (new java.util.Date()).toString();<br>        logger.info("returning from PriceIncreaseForm view to " + getSuccessView();<br><br>        return new ModelAndView(new RedirectView(getSuccessView()));<br>    }<br><br>    protected Object formBackingObject(HttpServletRequest request) throws ServletException {<br><br>        PriceIncrease priceIncrease = new PriceIncrease();<br>        priceIncrease.setPercentage(20);<br><br>        return priceIncrease;<br><br>    }<br><br>    public void setProductManager(ProductManager pm) {<br>        prodMan = pm;<br>    }<br><br>    public ProductManager getProductManager() {<br>        return prodMan;<br>    }<br><br>}</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">We are also adding some messages to the messages.properties resource 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><font face="Nimbus Mono L"><font size=2><strong>springapp/war/WEB-INF/classes/messages.properties</strong> </font></font></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width="100%" bgColor=#ffffcc>
            <pre>title=SpringApp<br>heading=Hello :: SpringApp<br>greeting=Greetings, it is now<br><font color=#800000>priceincrease.heading=Price Increase :: SpringApp</font><font color=#800000>error.not-specified=Percentage not specified!!!</font><font color=#800000>error.too-low=You have to specify a percentage higher than {0}!</font><font color=#800000>error.too-high=Don't be greedy - you can't raise prices by more than {0}%!</font><font color=#800000>required=Entry required.</font><font color=#800000>typeMismatch=Invalid data.</font><font color=#800000>typeMismatch.percentage=That is not a number!!! </font></pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">Finally, we have to provide a link to the priceincrease page from 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/jsp/hello.jsp</font> </font></strong></p>
            </td>
        </tr>
        <tr>
            <td vAlign=top width="100%" bgColor=#ffffcc>
            <pre>&lt;%@ include file="/WEB-INF/jsp/include.jsp" %&gt;<br><br>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;&lt;fmt:message key="title"/&gt;&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;&lt;fmt:message key="heading"/&gt;&lt;/h1&gt;<br>&lt;p&gt;&lt;fmt:message key="greeting"/&gt; &lt;c:out value="${model.now}"/&gt;<br>&lt;/p&gt;<br>&lt;h3&gt;Products&lt;/h3&gt;<br>&lt;c:forEach items="${model.products}" var="prod"&gt;<br>  &lt;c:out value="${prod.description}"/&gt; &lt;i&gt;$&lt;c:out value="${prod.price}"/&gt;&lt;/i&gt;&lt;br&gt;&lt;br&gt;<br>&lt;/c:forEach&gt;<br><font color=#800000>&lt;br&gt;</font><font color=#800000>&lt;a href="&lt;c:url value="priceincrease.htm"/&gt;"&gt;Increase Prices&lt;/a&gt;</font><font color=#800000>&lt;br&gt;</font>
            &lt;/body&gt;
            &lt;/html&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in">Compile and deploy all this and after reloading the application we can test it. This is what the form looks like with errors displayed.</p>
<p style="MARGIN-BOTTOM: 0in"><a href="file:///G:/Guest%20Documents/topquan/develop/spring-framework-1.2.8/docs/MVC-step-by-step/Spring-MVC-Step22.png"><img height=506 src="file:///G:/Guest%20Documents/topquan/develop/spring-framework-1.2.8/docs/MVC-step-by-step/Spring-MVC-Step22.png" width=728 align=left border=0 name=Graphic1> <br clear=left></a></p>
<img src ="http://www.blogjava.net/topquan/aggbug/62676.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 23:23 <a href="http://www.blogjava.net/topquan/articles/62676.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Developing a Spring Framework MVC application（二）</title><link>http://www.blogjava.net/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.blogjava.net/topquan/articles/62675.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62675.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62675.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62675.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/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 &#8211; 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 &#8211; 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 &#8220;header&#8221; 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>&lt;%@ page session="false"%&gt;<br><br>&lt;%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %&gt;<br>&lt;%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %&gt;        </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 &lt;c:redirect&gt; 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>&lt;%@ include file="/WEB-INF/jsp/include.jsp" %&gt;<br><br>&lt;%-- Redirected because we can't set the welcome page to a virtual URL. --%&gt;<br>&lt;c:redirect url="/hello.htm"/&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 14 &#8211; 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 &lt;c:out&gt; 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>&lt;%@ include file="/WEB-INF/jsp/include.jsp" %&gt;<br><br>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;Hello :: Spring Application&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Hello - Spring Application&lt;/h1&gt;<br>&lt;p&gt;Greetings, it is now &lt;c:out value="${now}"/&gt;<br>&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</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 &#8211; 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>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;<br><br>&lt;!--<br>  - Application context definition for "springapp" DispatcherServlet.<br>  --&gt;<br><br>&lt;beans&gt;<br>    &lt;bean id="springappController" class="SpringappController"/&gt;<br><br>    &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;<br>        &lt;property name="mappings"&gt;<br>            &lt;props&gt;<br>                &lt;prop key="/hello.htm"&gt;springappController&lt;/prop&gt;<br>            &lt;/props&gt;<br>        &lt;/property&gt;<br>    &lt;/bean&gt;<br><br><font color=#800000>    &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;</font><font color=#800000>        &lt;property name="viewClass"&gt;&lt;value&gt;org.springframework.web.servlet.view.JstlView&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="prefix"&gt;&lt;value&gt;/WEB-INF/jsp/&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="suffix"&gt;&lt;value&gt;.jsp&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font>
            &lt;/beans&gt;        </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 &#8211; 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 &#8211; 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 &#8211; 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 &#8211; 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 &#8211; Modify the view to display business data and add support for message bundle</strong> </p>
<p style="MARGIN-BOTTOM: 0in">Using the JSTL &lt;c:forEach&gt; tag, I add a section that displays product information. I have also replaced the title, heading and greeting text with a JSTL &lt;fmt:message&gt; tag that pulls the text to display from a provided 'message' source &#8211; 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>&lt;%@ include file="/WEB-INF/jsp/include.jsp" %&gt;<br><br>&lt;html&gt;<br>&lt;head&gt;<font color=#800000>&lt;title&gt;&lt;fmt:message key="title"/&gt;&lt;/title&gt;</font>&lt;/head&gt;<br>&lt;body&gt;<br><font color=#800000>&lt;h1&gt;&lt;fmt:message key="heading"/&gt;&lt;/h1&gt;</font>
            &lt;p&gt;<font color=#800000>&lt;fmt:message key="greeting"/&gt;</font> &lt;c:out value="${model.now}"/&gt;<br>&lt;/p&gt;<br><font color=#800000>&lt;h3&gt;Products&lt;/h3&gt;</font><font color=#800000>&lt;c:forEach items="${model.products}" var="prod"&gt;</font><font color=#800000>  &lt;c:out value="${prod.description}"/&gt; &lt;i&gt;$&lt;c:out value="${prod.price}"/&gt;&lt;/i&gt;&lt;br&gt;&lt;br&gt;</font><font color=#800000>&lt;/c:forEach&gt;</font>
            &lt;/body&gt;
            &lt;/html&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 18 &#8211; 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 &#8220;wire up&#8221; 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>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;<br><br>&lt;!--<br>  - Application context definition for "springapp" DispatcherServlet.<br>  --&gt;<br><br><br>&lt;beans&gt;<br>    &lt;bean id="springappController" class="web.SpringappController"<font color=#800000>&gt;</font><font color=#800000>        &lt;property name="productManager"&gt;</font><font color=#800000>            &lt;ref bean="prodMan"/&gt;</font><font color=#800000>        &lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font><font color=#800000>    &lt;bean id="prodMan" class="bus.ProductManager"&gt;</font><font color=#800000>        &lt;property name="products"&gt;</font><font color=#800000>            &lt;list&gt;</font><font color=#800000>                &lt;ref bean="product1"/&gt;</font><font color=#800000>                &lt;ref bean="product2"/&gt;</font><font color=#800000>                &lt;ref bean="product3"/&gt;</font><font color=#800000>            &lt;/list&gt;</font><font color=#800000>        &lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font><font color=#800000>    &lt;bean id="product1" class="bus.Product"&gt;</font><font color=#800000>        &lt;property name="description"&gt;&lt;value&gt;Lamp&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="price"&gt;&lt;value&gt;5.75&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font><font color=#800000></font><font color=#800000>    &lt;bean id="product2" class="bus.Product"&gt;</font><font color=#800000>        &lt;property name="description"&gt;&lt;value&gt;Table&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="price"&gt;&lt;value&gt;75.25&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font><font color=#800000>    &lt;bean id="product3" class="bus.Product"&gt;</font><font color=#800000>        &lt;property name="description"&gt;&lt;value&gt;Chair&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>        &lt;property name="price"&gt;&lt;value&gt;22.79&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font><font color=#800000>    &lt;bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"&gt;</font><font color=#800000>        &lt;property name="basename"&gt;&lt;value&gt;messages&lt;/value&gt;&lt;/property&gt;</font><font color=#800000>    &lt;/bean&gt;</font>
            &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;
            &lt;property name="mappings"&gt;
            &lt;props&gt;
            &lt;prop key="/hello.htm"&gt;springappController&lt;/prop&gt;
            &lt;/props&gt;
            &lt;/property&gt;
            &lt;/bean&gt;
            &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;
            &lt;property name="viewClass"&gt;&lt;value&gt;org.springframework.web.servlet.view.JstlView&lt;/value&gt;&lt;/property&gt;
            &lt;property name="prefix"&gt;&lt;value&gt;/WEB-INF/jsp/&lt;/value&gt;&lt;/property&gt;
            &lt;property name="suffix"&gt;&lt;value&gt;.jsp&lt;/value&gt;&lt;/property&gt;
            &lt;/bean&gt;
            &lt;/beans&gt;        </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 &#8211; 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 &lt;fmt:message&gt; 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>    &lt;target name="clean" description="Clean output directories"&gt;</font>
            <font color=#800000>        &lt;delete&gt;</font>
            <font color=#800000>            &lt;fileset dir="${build.dir}"&gt;</font>
            <font color=#800000>                &lt;include name="**/*.class"/&gt;</font>
            <font color=#800000>            &lt;/fileset&gt;</font>
            <font color=#800000>        &lt;/delete&gt;</font>
            <font color=#800000>    &lt;/target&gt;</font>
            <font color=#800000>    &lt;target name="undeploy" description="Un-Deploy application"&gt;</font>
            <font color=#800000>        &lt;delete&gt;</font>
            <font color=#800000>            &lt;fileset dir="${deploy.path}/${name}"&gt;</font>
            <font color=#800000>                &lt;include name="**/*.*"/&gt;</font>
            <font color=#800000>            &lt;/fileset&gt;</font>
            <font color=#800000>        &lt;/delete&gt;</font>
            <font color=#800000>    &lt;/target&gt;</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.blogjava.net/topquan/aggbug/62675.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 23:22 <a href="http://www.blogjava.net/topquan/articles/62675.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Developing a Spring Framework MVC application（一）</title><link>http://www.blogjava.net/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.blogjava.net/topquan/articles/62673.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62673.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62673.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62673.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/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 &#8211; 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 &#8211; 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>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;Example :: Spring Application&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Example - Spring Application&lt;/h1&gt;<br>&lt;p&gt;This is my test.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</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>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'&gt;<br><br>&lt;web-app&gt;<br><br>&lt;/web-app&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 3 &#8211; 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>&lt;?xml version="1.0"?&gt;<br><br>&lt;project name="springapp" basedir="." default="usage"&gt;<br>    &lt;property file="build.properties"/&gt;<br><br>    &lt;property name="src.dir" value="src"/&gt;<br>    &lt;property name="web.dir" value="war"/&gt;<br>    &lt;property name="build.dir" value="${web.dir}/WEB-INF/classes"/&gt;<br>    &lt;property name="name" value="springapp"/&gt;<br><br>    &lt;path id="master-classpath"&gt;<br>        &lt;fileset dir="${web.dir}/WEB-INF/lib"&gt;<br>            &lt;include name="*.jar"/&gt;<br>        &lt;/fileset&gt;<br>        &lt;!-- We need the servlet API classes:        --&gt;<br>        &lt;!--   for Tomcat 4.1 use servlet.jar        --&gt;<br>        &lt;!--   for Tomcat 5.0 use servlet-api.jar    --&gt;<br>        &lt;!--   for Other app server - check the docs --&gt;<br>        &lt;fileset dir="${appserver.home}/common/lib"&gt;<br>            &lt;include name="servlet*.jar"/&gt;<br>        &lt;/fileset&gt;<br>        &lt;pathelement path="${build.dir}"/&gt;<br>    &lt;/path&gt;<br><br>    &lt;target name="usage"&gt;<br>        &lt;echo message=""/&gt;<br>        &lt;echo message="${name} build file"/&gt;<br>        &lt;echo message="-----------------------------------"/&gt;<br>        &lt;echo message=""/&gt;<br>        &lt;echo message="Available targets are:"/&gt;<br>        &lt;echo message=""/&gt;<br>        &lt;echo message="build     --&gt; Build the application"/&gt;<br>        &lt;echo message="deploy    --&gt; Deploy application as directory"/&gt;<br>        &lt;echo message="deploywar --&gt; Deploy application as a WAR file"/&gt;<br>        &lt;echo message="install   --&gt; Install application in Tomcat"/&gt;<br>        &lt;echo message="reload    --&gt; Reload application in Tomcat"/&gt;<br>        &lt;echo message="start     --&gt; Start Tomcat application"/&gt;<br>        &lt;echo message="stop      --&gt; Stop Tomcat application"/&gt;<br>        &lt;echo message="list      --&gt; List Tomcat applications"/&gt;<br>        &lt;echo message=""/&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="build" description="Compile main source tree java files"&gt;<br>        &lt;mkdir dir="${build.dir}"/&gt;<br>        &lt;javac destdir="${build.dir}" target="1.3" debug="true"<br>               deprecation="false" optimize="false" failonerror="true"&gt;<br>            &lt;src path="${src.dir}"/&gt;<br>            &lt;classpath refid="master-classpath"/&gt;<br>        &lt;/javac&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="deploy" depends="build" description="Deploy application"&gt;<br>        &lt;copy todir="${deploy.path}/${name}" preservelastmodified="true"&gt;<br>            &lt;fileset dir="${web.dir}"&gt;<br>                &lt;include name="**/*.*"/&gt;<br>            &lt;/fileset&gt;<br>        &lt;/copy&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="deploywar" depends="build" description="Deploy application as a WAR file"&gt;<br>        &lt;war destfile="${name}.war"<br>             webxml="${web.dir}/WEB-INF/web.xml"&gt;<br>            &lt;fileset dir="${web.dir}"&gt;<br>                &lt;include name="**/*.*"/&gt;<br>            &lt;/fileset&gt;<br>        &lt;/war&gt;<br>        &lt;copy todir="${deploy.path}" preservelastmodified="true"&gt;<br>            &lt;fileset dir="."&gt;<br>                &lt;include name="*.war"/&gt;<br>            &lt;/fileset&gt;<br>        &lt;/copy&gt;<br>    &lt;/target&gt;<br><br>&lt;!-- ============================================================== --&gt;<br>&lt;!-- Tomcat tasks - remove these if you don't have Tomcat installed --&gt;<br>&lt;!-- ============================================================== --&gt;<br><br>    &lt;taskdef name="install" classname="org.apache.catalina.ant.InstallTask"&gt;<br>        &lt;classpath&gt;<br>            &lt;path location="${appserver.home}/server/lib/catalina-ant.jar"/&gt;<br>        &lt;/classpath&gt;<br>    &lt;/taskdef&gt;<br>    &lt;taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask"&gt;<br>        &lt;classpath&gt;<br>            &lt;path location="${appserver.home}/server/lib/catalina-ant.jar"/&gt;<br>        &lt;/classpath&gt;<br>    &lt;/taskdef&gt;<br>    &lt;taskdef name="list" classname="org.apache.catalina.ant.ListTask"&gt;<br>        &lt;classpath&gt;<br>            &lt;path location="${appserver.home}/server/lib/catalina-ant.jar"/&gt;<br>        &lt;/classpath&gt;<br>    &lt;/taskdef&gt;<br>    &lt;taskdef name="start" classname="org.apache.catalina.ant.StartTask"&gt;<br>        &lt;classpath&gt;<br>            &lt;path location="${appserver.home}/server/lib/catalina-ant.jar"/&gt;<br>        &lt;/classpath&gt;<br>    &lt;/taskdef&gt;<br>    &lt;taskdef name="stop" classname="org.apache.catalina.ant.StopTask"&gt;<br>        &lt;classpath&gt;<br>            &lt;path location="${appserver.home}/server/lib/catalina-ant.jar"/&gt;<br>        &lt;/classpath&gt;<br>    &lt;/taskdef&gt;<br><br>    &lt;target name="install" description="Install application in Tomcat"&gt;<br>        &lt;install url="${tomcat.manager.url}"<br>                 username="${tomcat.manager.username}"<br>                 password="${tomcat.manager.password}"<br>                 path="/${name}"<br>                 war="${name}"/&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="reload" description="Reload application in Tomcat"&gt;<br>        &lt;reload url="${tomcat.manager.url}"<br>                 username="${tomcat.manager.username}"<br>                 password="${tomcat.manager.password}"<br>                 path="/${name}"/&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="start" description="Start Tomcat application"&gt;<br>        &lt;start url="${tomcat.manager.url}"<br>                 username="${tomcat.manager.username}"<br>                 password="${tomcat.manager.password}"<br>                 path="/${name}"/&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="stop" description="Stop Tomcat application"&gt;<br>        &lt;stop url="${tomcat.manager.url}"<br>                 username="${tomcat.manager.username}"<br>                 password="${tomcat.manager.password}"<br>                 path="/${name}"/&gt;<br>    &lt;/target&gt;<br><br>    &lt;target name="list" description="List Tomcat applications"&gt;<br>        &lt;list url="${tomcat.manager.url}"<br>                 username="${tomcat.manager.username}"<br>                 password="${tomcat.manager.password}"/&gt;<br>    &lt;/target&gt;<br><br>&lt;!-- End Tomcat tasks --&gt;<br><br>&lt;/project&gt;</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     --&gt; Build the application</font>
            <font color=#280099>     [echo] deploy    --&gt; Deploy application as directory</font>
            <font color=#280099>     [echo] deploywar --&gt; Deploy application as a WAR file</font>
            <font color=#280099>     [echo] install   --&gt; Install application in Tomcat</font>
            <font color=#280099>     [echo] reload    --&gt; Reload application in Tomcat</font>
            <font color=#280099>     [echo] start     --&gt; Start Tomcat application</font>
            <font color=#280099>     [echo] stop      --&gt; Stop Tomcat application</font>
            <font color=#280099>     [echo] list      --&gt; 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 &#8211; 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 &#8211; 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 href="http://www.springframework.org/download.html">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 &#8211; 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>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE web-app PUBLIC '-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN' 'http://java.sun.com/dtd/web-app_2_3.dtd'&gt;<br><br>&lt;web-app&gt;<br><br><font color=#800000>  &lt;servlet&gt;</font><font color=#800000>    &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;</font><font color=#800000>    &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;</font><font color=#800000>    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;</font><font color=#800000>  &lt;/servlet&gt;</font><font color=#800000>  &lt;servlet-mapping&gt;</font><font color=#800000>    &lt;servlet-name&gt;springapp&lt;/servlet-name&gt;</font><font color=#800000>    &lt;url-pattern&gt;*.htm&lt;/url-pattern&gt;</font><font color=#800000>  &lt;/servlet-mapping&gt;</font><font color=#800000>  &lt;welcome-file-list&gt;</font><font color=#800000>    &lt;welcome-file&gt;</font><font color=#800000>      index.jsp</font><font color=#800000>    &lt;/welcome-file&gt;</font><font color=#800000>  &lt;/welcome-file-list&gt;</font>
            &lt;/web-app&gt;</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>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt;<br><br>&lt;!--<br>  - Application context definition for "springapp" DispatcherServlet.<br>  --&gt;<br><br>&lt;beans&gt;<br>    &lt;bean id="springappController" class="SpringappController"/&gt;<br><br>    &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt;<br>        &lt;property name="mappings"&gt;<br>            &lt;props&gt;<br>                &lt;prop key="/hello.htm"&gt;springappController&lt;/prop&gt;<br>            &lt;/props&gt;<br>        &lt;/property&gt;<br>    &lt;/bean&gt;<br>&lt;/beans&gt;</pre>
            </td>
        </tr>
    </tbody>
</table>
<p style="MARGIN-BOTTOM: 0in"><br></p>
<p style="MARGIN-BOTTOM: 0in"><strong>Step 7 &#8211; Copy jars to WEB-INF/lib</strong> </p>
<p style="MARGIN-BOTTOM: 0in">First create a 'lib' directory in the 'war/WEB-INF' directory.&nbsp; 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 &#8211; Create your Controller</strong> </p>
<p style="MARGIN-BOTTOM: 0in">Create your Controller &#8211; 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 &#8220;handles&#8221; 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 &#8211; 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 &#8211; 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] - &lt;%m&gt;%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 &#8211; 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 &#8211; 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 &#8211; 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>&lt;html&gt;<br>&lt;head&gt;&lt;title&gt;Example :: Spring Application&lt;/title&gt;&lt;/head&gt;<br>&lt;body&gt;<br>&lt;h1&gt;Hello - Spring Application&lt;/h1&gt;<br>&lt;p&gt;Greetings.&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</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 &#8211; 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 &#8211; 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 &#8211; 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.blogjava.net/topquan/aggbug/62673.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 23:21 <a href="http://www.blogjava.net/topquan/articles/62673.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>eclipse下struts+spring+hibernate快速入门（二）</title><link>http://www.blogjava.net/topquan/articles/62672.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:15:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/62672.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62672.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62672.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62672.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/62672.html</trackback:ping><description><![CDATA[<p>Web层． <br>创建Struts Action，为了在一个action中实现CRUD操作，Action继承了DispatchAction根据参数决定调用方法。在src/com.jandar.web.struts.action下创建UserAction.java<br>import javax.servlet.http.HttpServletRequest;<br>import javax.servlet.http.HttpServletResponse;<br>import org.apache.commons.logging.Log;<br>import org.apache.commons.logging.LogFactory;<br>import org.apache.struts.action.ActionForm;<br>import org.apache.struts.action.ActionForward;<br>import org.apache.struts.action.ActionMapping;<br>import org.apache.struts.action.ActionMessage;<br>import org.apache.struts.action.ActionMessages;<br>import org.apache.struts.action.DynaActionForm;<br>import org.apache.struts.actions.DispatchAction;<br>import com.jandar.model.User;<br>import com.jandar.service.spring.UserManager;<br>public class UserAction extends DispatchAction {<br>private static Log log = LogFactory.getLog(UserAction.class);<br>private UserManager mgr = null;<br>public void setUserManager(UserManager userManager) {<br>this.mgr = userManager;<br>}<br>public ActionForward delete(ActionMapping mapping, ActionForm form,<br>HttpServletRequest request,<br>HttpServletResponse response)<br>throws Exception {<br>if (log.isDebugEnabled()) {<br>log.debug("entering ''delete'' method...");<br>}<br>mgr.removeUser(request.getParameter("user.id"));<br>ActionMessages messages = new ActionMessages();<br>messages.add(ActionMessages.GLOBAL_MESSAGE, <br>new ActionMessage("user.deleted"));<br>saveMessages(request, messages);<br>return list(mapping, form, request, response);<br>}<br>public ActionForward edit(ActionMapping mapping, ActionForm form,<br>HttpServletRequest request,<br>HttpServletResponse response)<br>throws Exception {<br>if (log.isDebugEnabled()) {<br>log.debug("entering ''edit'' method...");<br>}<br>DynaActionForm userForm = (DynaActionForm) form;<br>String userId = request.getParameter("id");<br>// null userId indicates an add<br>if (userId != null) {<br>User user = mgr.getUser(userId);<br>if (user == null) {<br>ActionErrors errors = new ActionMessages();<br>errors.add(ActionMessages.GLOBAL_MESSAGE,<br>new ActionMessage("user.missing"));<br>saveErrors(request, errors);<br>return mapping.findForward("list");<br>}<br>userForm.set("user", user);<br>}<br>return mapping.findForward("edit");<br>}<br>public ActionForward list(ActionMapping mapping, ActionForm form,<br>HttpServletRequest request,<br>HttpServletResponse response)<br>throws Exception {<br>if (log.isDebugEnabled()) {<br>log.debug("entering ''list'' method...");<br>}<br>request.setAttribute("users", mgr.getUsers());<br>return mapping.findForward("list");<br>}<br>public ActionForward save(ActionMapping mapping, ActionForm form,<br>HttpServletRequest request,<br>HttpServletResponse response)<br>throws Exception {<br>if (log.isDebugEnabled()) {<br>log.debug("entering ''save'' method...");<br>}<br>// run validation rules on this form<br>ActionErrors errors = form.validate(mapping, request);<br>if (!errors.isEmpty()) {<br>saveErrors(request, errors);<br>return mapping.findForward("edit");<br>}<br>DynaActionForm userForm = (DynaActionForm) form;<br>mgr.saveUser((User)userForm.get("user"));<br>ActionMessages messages = new ActionMessages();<br>messages.add(ActionMessages.GLOBAL_MESSAGE,<br>new ActionMessage("user.saved"));<br>saveMessages(request, messages);<br>return list(mapping, form, request, response);<br>}<br>public ActionForward unspecified(ActionMapping mapping, ActionForm form,<br>HttpServletRequest request,<br>HttpServletResponse response)<br>throws Exception {<br>return list(mapping, form, request, response);<br>}<br>}<br>UserAction.java通过UserManger访问业务层，UserManager通过依赖注入<br>2． 创建struts ActionFrom<br>可以在src/com.jandar.web.struts.form下创建一个UserForm.java的struts ActionForm，我们也可以采用已建好的模型来配置form bean即采用动态form <br>org.apache.struts.validator.DynaValidatorForm 同时指定property 为<br>com.jandar.model.User详见struts-config.xml配置文件.</p>
<p>配置struts-config.xml<br>1． 配置struts-config.xml<br>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE struts-config PUBLIC<br>"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"<br>"<a href="http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd</a>"&gt;<br>&lt;struts-config&gt;<br>&lt;!-- ======================================== Form Bean Definitions --&gt;<br>&lt;form-beans&gt;<br>&lt;form-bean<br>name="userForm" type="org.apache.struts.validator.DynaValidatorForm"&gt;<br>&lt;form-property name="user" type="com.jandar.model.User"/&gt;<br>&lt;/form-bean&gt;<br>&lt;/form-beans&gt;<br>&lt;!-- =================================== Global Forward Definitions --&gt;<br>&lt;global-forwards&gt;<br>&lt;/global-forwards&gt;<br>&lt;!-- =================================== Action Mapping Definitions --&gt;<br>&lt;action-mappings&gt;<br>&lt;action path="/user" type="com.jandar.web.struts.action.UserAction " <br>name="userForm" scope="request" parameter="method" validate="false"&gt;<br>&lt;forward name="list" path="/userList.jsp"/&gt;<br>&lt;forward name="edit" path="/userForm.jsp"/&gt;<br>&lt;/action&gt;<br>&lt;/action-mappings&gt;<br>&lt;!-- ================================ Message Resources Definitions --&gt;<br>&lt;message-resources parameter="messages"/&gt;<br>&lt;/struts-config&gt;<br>2． 通过struts-config.xml把struts和spring结合起来<br>UserAction.java中的UserManager需要通过依赖注入，通过plug-in技术将spring加到struts中，在struts-config.xml中增加一下代码<br>&lt;plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"&gt;<br>&lt;set-property property="contextConfigLocation" <br>value="/WEB-INF/applicationContext.xml,<br>/WEB-INF/action-servlet.xml"/&gt;<br>&lt;/plug-in&gt;<br>让struts启动同时初始化spring，读取spring的配置文件applicationContext.xml,并且把struts的action也交给spring管理，把action配置到action-servlet.xml中<br>新建action-servlet.xml<br>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"<br>"<a href="http://www.springframework.org/dtd/spring-beans.dtd">http://www.springframework.org/dtd/spring-beans.dtd</a>"&gt;<br>&lt;beans&gt;<br>&lt;bean name="/user" class="com.jandar.web.struts.action.UserAction" singleton="false"&gt;<br>&lt;property name="userManager"&gt;&lt;ref bean="userManager"/&gt;&lt;/property&gt;<br>&lt;/bean&gt;<br>&lt;/beans&gt;<br>同时将action映射到org.springframework.web.struts.DelegatingActionProxy即修改<br>&lt;action path="/user" type="org.springframework.web.struts.DelegatingActionProxy" <br>name="userForm" scope="request" parameter="method" validate="false"&gt;<br>&lt;forward name="list" path="/userList.jsp"/&gt;<br>&lt;forward name="edit" path="/userForm.jsp"/&gt;<br>&lt;/action&gt;<br>3． 新建web.xml配置文件<br>&lt;?xml version="1.0" encoding="UTF-8"?&gt;</p>
<p>&lt;web-app xmlns="<a href="http://java.sun.com/xml/ns/j2ee">http://java.sun.com/xml/ns/j2ee</a>"</p>
<p>xmlns:xsi="<a href="http://www.w3.org/2001/XMLSchema-instance">http://www.w3.org/2001/XMLSchema-instance</a>"</p>
<p>xsi:schemaLocation="<a href="http://java.sun.com/xml/ns/j2ee">http://java.sun.com/xml/ns/j2ee</a><a href="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd</a>" version="2.4"&gt;</p>
<p>&lt;servlet&gt;</p>
<p>&lt;servlet-name&gt;action&lt;/servlet-name&gt;</p>
<p>&lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt;</p>
<p>&lt;init-param&gt;</p>
<p>&lt;param-name&gt;config&lt;/param-name&gt;</p>
<p>&lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt;</p>
<p>&lt;/init-param&gt;</p>
<p>&lt;init-param&gt;</p>
<p>&lt;param-name&gt;debug&lt;/param-name&gt;</p>
<p>&lt;param-value&gt;3&lt;/param-value&gt;</p>
<p>&lt;/init-param&gt;</p>
<p>&lt;init-param&gt;</p>
<p>&lt;param-name&gt;detail&lt;/param-name&gt;</p>
<p>&lt;param-value&gt;3&lt;/param-value&gt;</p>
<p>&lt;/init-param&gt;</p>
<p>&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;</p>
<p>&lt;/servlet&gt;</p>
<p><br>&lt;servlet-mapping&gt;</p>
<p>&lt;servlet-name&gt;action&lt;/servlet-name&gt;</p>
<p>&lt;url-pattern&gt;*.do&lt;/url-pattern&gt;</p>
<p>&lt;/servlet-mapping&gt;</p>
<p><br>&lt;welcome-file-list&gt;</p>
<p>&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;</p>
<p>&lt;/welcome-file-list&gt; </p>
<p><br>&lt;/web-app&gt;</p>
<p>4． 新建index.jsp,userList.jsp,userForm.jsp<br>index.jsp<br>&lt;%@ page language="java"%&gt;</p>
<p>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-bean">http://jakarta.apache.org/struts/tags-bean</a>" prefix="bean" %&gt;</p>
<p>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-html">http://jakarta.apache.org/struts/tags-html</a>" prefix="html" %&gt;</p>
<p>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-logic">http://jakarta.apache.org/struts/tags-logic</a>" prefix="logic" %&gt;</p>
<p>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-tiles">http://jakarta.apache.org/struts/tags-tiles</a>" prefix="tiles" %&gt;</p>
<p>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-template">http://jakarta.apache.org/struts/tags-template</a>" prefix="template" %&gt;</p>
<p>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-nested">http://jakarta.apache.org/struts/tags-nested</a>" prefix="nested" %&gt;<br>&lt;html:html locale="true"&gt;</p>
<p>&lt;head&gt;</p>
<p>&lt;html:base /&gt;</p>
<p><br>&lt;title&gt;index.jsp&lt;/title&gt; </p>
<p>&lt;/head&gt;</p>
<p><br>&lt;body&gt;</p>
<p>&lt;html:link href="user.do?method=list"&gt;List all user&lt;/html:link&gt;</p>
<p>&lt;/body&gt;</p>
<p>&lt;/html:html&gt;</p>
<p>userForm.jsp<br>&lt;%@ page language="java"%&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-html">http://jakarta.apache.org/struts/tags-html</a>" prefix="html" %&gt;<br>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt;<br>&lt;html:html locale="true"&gt;<br>&lt;head&gt;<br>&lt;html:base /&gt;<br>&lt;title&gt;userform.jsp&lt;/title&gt; <br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;html:form action="user.do?method=save" method="post" focus="id"&gt;<br>&lt;html:hidden property="user.id"/&gt;<br>&lt;table border="0"&gt;<br>&lt;tr&gt;<br>&lt;td&gt;id:&lt;/td&gt;<br>&lt;td&gt;&lt;html:text property="user.firstname"/&gt;&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;tr&gt;<br>&lt;td&gt;lastname:&lt;/td&gt;<br>&lt;td&gt;&lt;html:text property="user.lastname" /&gt;&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;tr&gt;<br>&lt;td colspan="2" align="center"&gt;&lt;html:submit property="tijiao"/&gt;&lt;/td&gt;<br>&lt;/tr&gt;<br>&lt;/table&gt;<br>&lt;/html:form&gt;<br>&lt;/body&gt;<br>&lt;/html:html&gt;<br>userList.jsp<br>&lt;%@ page language="java"%&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-bean">http://jakarta.apache.org/struts/tags-bean</a>" prefix="bean" %&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-html">http://jakarta.apache.org/struts/tags-html</a>" prefix="html" %&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-logic">http://jakarta.apache.org/struts/tags-logic</a>" prefix="logic" %&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-tiles">http://jakarta.apache.org/struts/tags-tiles</a>" prefix="tiles" %&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-template">http://jakarta.apache.org/struts/tags-template</a>" prefix="template" %&gt;<br>&lt;%@ taglib uri="<a href="http://jakarta.apache.org/struts/tags-nested">http://jakarta.apache.org/struts/tags-nested</a>" prefix="nested" %&gt;<br>&lt;%@ taglib uri="<a href="http://java.sun.com/jstl/core_rt">http://java.sun.com/jstl/core_rt</a>" prefix="c" %&gt;<br>&lt;html:html locale="true"&gt;<br>&lt;head&gt;<br>&lt;html:base /&gt;<br>&lt;title&gt;userList.jsp&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>This a struts page. &lt;br&gt;<br>&lt;table class="list"&gt;<br>&lt;thead&gt;<br>&lt;tr&gt;<br>&lt;th&gt;id&lt;/th&gt;<br>&lt;th&gt;firstName&lt;/th&gt;<br>&lt;th&gt;lastName&lt;/th&gt;<br>&lt;/tr&gt;<br>&lt;/thead&gt;<br>&lt;tbody&gt;<br>&lt;logic:iterate id="user" name="users"&gt;<br>&lt;tr&gt;<br>&lt;td&gt;<br>&lt;a href="user.do?method=edit&amp;amp;id=&lt;bean:write name="user" property="id"/&gt;"&gt;&lt;bean:write name="user" property="id"/&gt;&lt;/a&gt;<br>&lt;/td&gt;<br>&lt;td&gt;&lt;bean:write name="user" property="firstName"/&gt;&lt;/td&gt;</p>
<p>&lt;td&gt;&lt;bean:write name="user" property="lastName"/&gt;&lt;/td&gt;&lt;/tr&gt;<br>&lt;/logic:iterate&gt;<br>&lt;/tbody&gt;<br>&lt;/table&gt;<br>&lt;/body&gt;<br>&lt;/html:html&gt;</p>
<img src ="http://www.blogjava.net/topquan/aggbug/62672.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 23:15 <a href="http://www.blogjava.net/topquan/articles/62672.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>eclipse下struts+spring+hibernate快速入门（一）</title><link>http://www.blogjava.net/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.blogjava.net/topquan/articles/62670.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62670.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62670.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62670.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/62670.html</trackback:ping><description><![CDATA[<p>本文是开发基于spring的web应用的入门文章，前端采用Struts MVC框架，中间层采用spring，后台采用Hibernate。 <br>概览<br>本文包含以下内容： <br>&#8226;配置Hibernate和事务 &#8226;装载Spring的applicationContext.xml文件 <br>&#8226;建立业务层和DAO之间的依赖关系 &#8226;将Spring应用到Struts中 <br>这个例子是建立一个简单的web应用，叫MyUsers,完成用户管理操作，包含简单的数据库增，删，查，该即CRUD（新建，访问，更新，删除）操作。这是一个三层的web应用，通过Action（Struts）访问业务层，业务层访问DAO。应用的总体结构－从web（UserAction）到中间层（UserManager），再到数据访问层（UserDAO），然后将结果返回。 <br>Spring层的真正强大在于它的声明型事务处理，帮定和对持久层支持（例如Hiberate和iBATIS） <br>以下是完成这个例子的步骤： <br>&nbsp;1）安装Eclipse插件 2）数据库建表 3）配置Hibernate和Spring <br>4）建立Hibernate DAO接口的实现类 5）运行测试类，测试DAO的CRUD操作 <br>6）创建一个处理类，声明事务&nbsp; 7）创建Struts Action的测试类 <br>8）创建web层的Action和model 9）运行Action的测试类测试CRUD操作 <br>10）创建jsp文件通过浏览器进行CRUD操作 11）通过浏览器校验jsp <br>开发环境<br>Eclipse3.0.1 , MyEclispe 3.8.4, MySQL4.1.8, spring-framework-1.2.6-with-dependencies,Tomcat5.0<br>&nbsp;&nbsp; 数据库建表&nbsp;&nbsp; use appfuse;<br>CREATE TABLE app_user (<br>&nbsp; id int(11) NOT NULL auto_increment,<br>&nbsp; firstname varchar(20) NOT NULL,<br>&nbsp; lastname varchar(20) ,<br>&nbsp; PRIMARY KEY&nbsp; (id)<br>);<br>&nbsp;&nbsp;&nbsp; 新建项目<br>新建一个web project，分别add struts,hibernate capabilities.将spring 包中的dist<a></a><a></a>文件夹中的jar文件拷贝到WEB-INF/lib中。<br>创建持久层O/R mapping <br>1． 在src/com.jandar.model下用hibernate插件从数据库导出app_user的.hbm.xml文件改名为User.hbm.xml <br>&lt;?xml version="1.0"?&gt;<br>&lt;!DOCTYPE hibernate-mapping PUBLIC<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "-//Hibernate/Hibernate Mapping DTD 2.0//EN"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "<a href="http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd</a>" &gt;</p>
<p>&lt;!-- DO NOT EDIT: This is a generated file that is synchronized --&gt;<br>&lt;!-- by MyEclipse Hibernate tool integration.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; --&gt;<br>&lt;!-- Created Mon Jul 24 11:48:15 CST 2006&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; --&gt;<br>&lt;hibernate-mapping package=""&gt;</p>
<p>&nbsp;&nbsp;&nbsp; &lt;class name="AppUser" table="app_user"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;id name="id" column="id" type="integer"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;generator class="identity"/&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/id&gt;<br>&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="firstName" column="firstname" type="string"&nbsp; not-null="true" /&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="lastName" column="lastname" type="string" /&gt;<br>&nbsp;&nbsp;&nbsp; &lt;/class&gt;<br>&nbsp;&nbsp;&nbsp; <br>&lt;/hibernate-mapping&gt;<br>2．在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>&nbsp;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>&nbsp;} <br>/** <br>&nbsp;* @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>&nbsp;public String getLastName() { <br>&nbsp;return lastName; <br>} <br>public void setLastName(String lastName) { <br>this.lastName = lastName; <br>} <br>}<br>创建DAO，访问对象 <br>1． 在src/com.jandar.service.dao新建IDAO.java接口，所有的DAO都继承该接口 <br>package com.jandar.service.dao; <br>public interface IDAO { <br>} <br>2． 在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>该接口提供了访问对象的方法， <br>3． 在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>/* （非 Javadoc） <br>* @see com.jandar.dao.IUserDAO#getUsers() <br>*/ <br>public List getUsers() { <br>return getHibernateTemplate().find("from User"); <br>} <br>/* （非 Javadoc） <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>/* （非 Javadoc） <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>/* （非 Javadoc） <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>在这个类中实现了IUserDAO接口的方法，并且继承了HibernateDAOSupport类。这个类的作用是通过hibernate访问、操作对象，进而实现对数据库的操作。 <br>创建业务层，声明事务 <br>业务层主要处理业务逻辑，提供给web层友好的访问接口和实现访问DAO层。用业务层的另一个好处是，可以适应数据访问层从Hibernate技术转移到其他数据访问技术。 <br>1． 在src/com.jandar.service下新建一个IUserManager接口，该接口有几乎于IUserDAO同样的方法，不同的是处理参数，应为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． 在src/com.jandar.service.spring下新建IUserManager实现类，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;&nbsp; <br>public class UserManager implements IUserManager { <br>/* （非 Javadoc） <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 返回 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>/* （非 Javadoc） <br>* @see com.jandar.service.IUserManager#getUsers() <br>*/ <br>public List getUsers() { <br>// TODO 自动生成方法存根 <br>return userDao.getUsers(); <br>} <br>/* （非 Javadoc） <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>/* （非 Javadoc） <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通过访问dao接口实现业务逻辑和数据库操作。同时该类中提供了set方法，运用了Spring的依赖注入机制。但尚未使用spring的AOP和声明事务。 <br>配置applicationContext.xml <br>在WEB-INF 下新建applicationContext.xml<br>&lt;?xml version="1.0" encoding="UTF-8"?&gt;</p>
<p>&lt;!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"</p>
<p>"<a href="http://www.springframework.org/dtd/spring-beans.dtd">http://www.springframework.org/dtd/spring-beans.dtd</a>"&gt;</p>
<p><br>&lt;beans&gt;</p>
<p><br>&lt;bean id="dataSource" </p>
<p>class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;</p>
<p>&lt;property name="driverClassName"&gt;&lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt;&lt;/property&gt;</p>
<p>&lt;property name="url"&gt;&lt;value&gt;jdbc:mysql://localhost:3306/appfuse&lt;/value&gt;&lt;/property&gt;</p>
<p>&lt;property name="username"&gt;&lt;value&gt;root&lt;/value&gt;&lt;/property&gt;</p>
<p>&lt;!-- Make sure &lt;value&gt; tags are on same line - if they''re not, </p>
<p>authentication will fail --&gt;</p>
<p>&lt;property name="password"&gt;&lt;value&gt;root&lt;/value&gt;&lt;/property&gt;</p>
<p>&lt;/bean&gt;</p>
<p><br>&lt;!-- Hibernate SessionFactory --&gt;</p>
<p>&lt;bean id="sessionFactory" </p>
<p>class="org.springframework.orm.hibernate.LocalSessionFactoryBean"&gt;</p>
<p>&lt;property name="dataSource"&gt;&lt;ref local="dataSource"/&gt;&lt;/property&gt;</p>
<p>&lt;property name="mappingResources"&gt;</p>
<p>&lt;list&gt;</p>
<p>&lt;value&gt;com/jandar/model/User.hbm.xml&lt;/value&gt;</p>
<p>&lt;/list&gt;</p>
<p>&lt;/property&gt;</p>
<p>&lt;property name="hibernateProperties"&gt;</p>
<p>&lt;props&gt;</p>
<p>&lt;prop key="hibernate.dialect"&gt;net.sf.hibernate.dialect.MySQLDialect&lt;/prop&gt;</p>
<p>&lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt;</p>
<p>&lt;/props&gt;</p>
<p>&lt;/property&gt;</p>
<p>&lt;/bean&gt;</p>
<p><br>&lt;!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --&gt;</p>
<p>&lt;bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"&gt;</p>
<p>&lt;property name="sessionFactory"&gt;&lt;ref local="sessionFactory"/&gt;&lt;/property&gt;</p>
<p>&lt;/bean&gt;</p>
<p><br>&lt;bean id="userDAO" class="com.jandar.service.dao.hibernate.UserDAOHibernate"&gt;</p>
<p>&lt;property name="sessionFactory"&gt;&lt;ref local="sessionFactory"/&gt;&lt;/property&gt;</p>
<p>&lt;/bean&gt; </p>
<p><br>&lt;bean id="userManagerTarget" class="com.jandar.service.spring.UserManager"&gt;</p>
<p>&lt;property name="userDAO"&gt;&lt;ref local="userDAO"/&gt;&lt;/property&gt;</p>
<p>&lt;/bean&gt;</p>
<p><br>&lt;bean id="userManager" </p>
<p>class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"&gt;</p>
<p>&lt;property name="transactionManager"&gt;&lt;ref local="transactionManager"/&gt;&lt;/property&gt;</p>
<p>&lt;property name="target"&gt;&lt;ref local="userManagerTarget"/&gt;&lt;/property&gt;</p>
<p>&lt;property name="transactionAttributes"&gt;</p>
<p>&lt;props&gt;</p>
<p>&lt;prop key="save*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt;</p>
<p>&lt;prop key="remove*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt;</p>
<p>&lt;prop key="*"&gt;PROPAGATION_REQUIRED,readOnly&lt;/prop&gt;</p>
<p>&lt;/props&gt;</p>
<p>&lt;/property&gt;<br>&lt;/bean&gt;</p>
<p>&lt;bean name="/user" class="com.jandar.web.struts.action.UserAction"<br>singleton="false"&gt;<br>&lt;property name="mgr"&gt;<br>&lt;ref bean="userManager" /&gt;<br>&lt;/property&gt;<br>&lt;/bean&gt;</p>
<p><br>&lt;/beans&gt;<br></p>
<p>&#160;</p>
<p class=diaryFoot></p>
<img src ="http://www.blogjava.net/topquan/aggbug/62670.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 23:14 <a href="http://www.blogjava.net/topquan/articles/62670.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>进入 Spring MVC</title><link>http://www.blogjava.net/topquan/articles/62658.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 14:26:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/62658.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/62658.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/62658.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/62658.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/62658.html</trackback:ping><description><![CDATA[<p><strong>Spring MVC 框架</strong> </p>
<p>　　<a href="http://www.javafan.net/special/spring/index.jsp" target=_blank>Spring</a> 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构，可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口，Spring 框架是高度可配置的，而且包含多种视图技术，例如 JavaServer Pages（JSP）技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图，所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色，这种分离让它们更容易进行定制。</p>
<p>　　Spring 的 Web MVC 框架是围绕 DispatcherServlet 设计的，它把请求分派给处理程序，同时带有可配置的处理程序映射、视图解析、本地语言、主题解析以及上载文件支持。默认的处理程序是非常简单的 Controller 接口，只有一个方法 ModelAndView handleRequest(request, response)。Spring 提供了一个控制器层次结构，可以派生子类。如果应用程序需要处理用户输入表单，那么可以继承 AbstractFormController。如果需要把多页输入处理到一个表单，那么可以继承 AbstractWizardFormController。</p>
<p>　　示例应用程序有助于直观地学习这些特性。银行应用程序允许用户检索他们的帐户信息。在构建银行应用程序的过程中，可以学到如何配置 Spring MVC 框架和实现框架的视图层，视图层包括 JSTL 标记（用于显示输出的数据）和JavaServer Pages 技术。</p>
<p>　　<strong>配置 Spring MVC</strong></p>
<p>　　要开始构建示例应用程序，请配置 Spring MVC 的 DispatcherServlet。请在 web.xml 文件中注册所有配置。清单 1 显示了如何配置 sampleBankingServlet。</p>
<p>清单 1. 配置 Spring MVC DispatcherServlet</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&lt;servlet&gt;<br>&nbsp;&nbsp; &lt;servlet-name&gt;sampleBankingServlet&lt;/servlet-name&gt;<br>&nbsp;&nbsp; &lt;servlet-class&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; org.springframework.we.servlet.DispatcherServlet<br>&nbsp;&nbsp; &lt;servlet-class&gt;<br>&nbsp;&nbsp; &lt;load-on-startup&gt;1&lt;load-on-startup&gt;<br>&lt;servlet&gt;</p>
<p>　　DispatcherServlet 从一个 XML 文件装入 Spring 应用程序上下文，XML 文件的名称是 servlet 的名称后面加上 -servlet 。在这个示例中，DispatcherServlet 会从 sampleBankingServlet-servlet.xml 文件装入应用程序上下文。 </p>
<p>　　<strong>配置应用程序的 URL</strong></p>
<p>　　下一步是配置想让 sampleBankingServlet 处理的 URL。同样，还是要在 web.xml 中注册所有这些信息。</p>
<p>清单 2. 配置想要处理的 URL</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&lt;servlet-mapping&gt;<br>&lt;servlet-name&gt; sampleBankingServlet&lt;servlet-name&gt;<br>&lt;url-pattern&gt;*.jsp&lt;/url-pattern&gt;<br>&lt;/servlet-mapping&gt;</p>
<p>　　<strong>装入配置文件</strong></p>
<p>　　下面，装入配置文件。为了做到这点，请为 Servlet 2.3 规范注册 ContextLoaderListener 或为 Servlet 2.2 及以下的容器注册 ContextLoaderServlet。为了保障后向兼容性，请用 ContextLoaderServlet。在启动 Web 应用程序时，ContextLoaderServlet 会装入 Spring 配置文件。清单 3 注册了 ContextLoaderServlet。</p>
<p>清单 3. 注册 ContextLoaderServlet</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&lt;servlet&gt;<br>&nbsp; &lt;servlet-name&gt;context&gt;servlet-name&gt;<br>&nbsp; &lt;servlet-class&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp; org.springframework.web.context.ContextLoaderServlet<br>&nbsp; &lt;/servlet-class&gt;<br>&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;<br>&lt;/servlet&gt;</p>
<p>　　contextConfigLocation 参数定义了要装入的 Spring 配置文件，如下面的 servlet 上下文所示。</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&lt;context-param&gt;<br>&lt;param-value&gt;contextConfigLocation&lt;/param-value&gt;<br>&lt;param-value&gt;/WEB-INF/sampleBanking-services.xml&lt;/param-value&gt;<br>&lt;/context-param&gt;</p>
<p>　　sampleBanking-services.xml 文件代表示例银行应用程序服务的配置和 bean 配置。如果想装入多个配置文件，可以在 &lt;param-value&gt; 标记中用逗号作分隔符。</p>
<p>　　<strong>Spring MVC 示例</strong></p>
<p>　　示例银行应用程序允许用户根据惟一的 ID 和口令查看帐户信息。虽然 Spring MVC 提供了其他选项，但是我将采用 JSP 技术作为视图页面。这个简单的应用程序包含一个视图页用于用户输入（ID 和口令），另一页显示用户的帐户信息。</p>
<p>　　我从 LoginBankController 开始，它扩展了 Spring MVC 的 SimpleFormController。SimpleFormContoller 提供了显示从 HTTP GET 请求接收到的表单的功能，以及处理从 HTTP POST 接收到的相同表单数据的功能。LoginBankController 用 AuthenticationService 和 AccountServices 服务进行验证，并执行帐户活动。&#8220; 配置视图属性 &#8221;一节中的清单 5 描述了如何把 AuthenticationService 和 AccountServices 连接到 LoginBankController。 清单 4 显示了 LoginBankController 的代码。</p>
<p>清单 4. LoginBankController 扩展 SimpleFormController</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">public class LoginBankController extends SimpleFormController {<br><br>&nbsp;&nbsp; public LoginBankController(){<br><br>&nbsp;&nbsp; }<br><br>&nbsp;&nbsp; protected ModelAndView onSubmit(Object command) throws Exception{<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LoginCommand loginCommand = (LoginCommand) command;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; authenticationService.authenticate(loginCommand);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AccountDetail accountdetail = accountServices.getAccountSummary(loginCommand.getUserId());<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return new ModelAndView(getSuccessView(),"accountdetail",accountdetail);<br>&nbsp;&nbsp; }<br><br>&nbsp;&nbsp; private AuthenticationService authenticationService;<br><br>&nbsp;&nbsp; private AccountServices accountServices;<br><br>&nbsp;&nbsp; public AccountServices getAccountServices() {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return accountServices;<br>&nbsp;&nbsp; }<br><br>&nbsp;&nbsp; public void setAccountServices(AccountServices accountServices) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.accountServices = accountServices;<br>&nbsp;&nbsp; }<br><br>&nbsp;&nbsp; public AuthenticationService getAuthenticationService() {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return authenticationService;<br>&nbsp;&nbsp; }<br><br>&nbsp;&nbsp; public void setAuthenticationService(<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AuthenticationService authenticationService) {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.authenticationService = authenticationService;<br>&nbsp;&nbsp; }<br>}</p>
<p>　　<strong>配置视图属性</strong></p>
<p>　　下面，必须注册在接收到 HTTP GET 请求时显示的页面。在 Spring 配置中用 formView 属性注册这个页面，如清单 5 所示。sucessView 属性代表表单数据提交而且 doSubmitAction() 方法中的逻辑成功执行之后显示的页面。formView 和 sucessView 属性都代表被定义的视图的逻辑名称，逻辑名称映射到实际的视图页面。</p>
<p>清单 5. 注册 LoginBankController</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&nbsp;&nbsp; &lt;bean id="loginBankController"<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; class="springexample.controller.LoginBankController"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="sessionForm"&gt;&lt;value&gt;true&lt;/value&gt;&lt;/property&gt;<br>&nbsp;&nbsp; &lt;property name="commandName"&gt;&lt;value&gt;loginCommand&lt;/value&gt;&lt;/property&gt;<br>&nbsp;&nbsp; &lt;property name="commandClass"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;springexample.commands.LoginCommand&lt;/value&gt;<br>&nbsp;&nbsp; &lt;/property&gt;<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="authenticationService"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;ref bean="authenticationService" /&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/property&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="accountServices"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;ref bean="accountServices" /&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/property&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="formView"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;login&lt;/value&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/property&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;property name="successView"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;accountdetail&lt;/value&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/property&gt;<br><br>&nbsp;&nbsp; &lt;/bean&gt;</p>
<p>　　commandClass 和 commandName 标记决定将在视图页面中活动的 bean。例如，可以通过 login.jsp 页面访问 loginCommand bean，这个页面是应用程序的登录页面。一旦用户提交了登录页面，应用程序就可以从 LoginBankController 的 onSubmit() 方法中的命令对象检索出表单数据。</p>
<p>　　<strong>视图解析器</strong></p>
<p>　　Spring MVC 的 视图解析器 把每个逻辑名称解析成实际的资源，即包含帐户信息的 JSP 文件。我用的是 Spring 的 InternalResourceViewResolver，如 清单 6 所示。</p>
<p>清单 6. InternalResourceViewResolver</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&lt;bean id="view-Resolver" <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt;<br>&nbsp;&nbsp; &lt;property name="viewClass"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;value&gt;org.springframework.web.servlet.view.JstlView&lt;/value&gt;<br>&nbsp;&nbsp; &lt;/property&gt;<br>&nbsp;&nbsp; &lt;property name="prefix"&gt;&lt;value&gt;/jsp/&lt;/value&gt;&lt;/property&gt;<br>&nbsp;&nbsp; &lt;property name="suffix"&gt;&lt;value&gt;.jsp&lt;/value&gt;&lt;/property&gt;<br>&lt;/bean&gt;</p>
<p>　　因为我在 JSP 页面中使用了 JSTL 标记，所以用户的登录名称解析成资源 /jsp/login.jsp，而 viewClass 成为 JstlView。</p>
<p>　　<strong>验证和帐户服务</strong></p>
<p>　　就像前面提到的，LoginBankController 内部连接了 Spring 的 AccountServices 和 AuthenticationService。AuthenticationService 类处理银行应用程序的验证。AccountServices 类处理典型的银行服务，例如查找交易和电汇。清单 7 显示了银行应用程序的验证和帐户服务的配置。</p>
<p>清单 7. 配置验证和帐户服务</p>
<p style="BACKGROUND: rgb(221,221,221) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">&lt;beans&gt;<br><br>&nbsp;&nbsp; &lt;bean id="accountServices" <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; class="springexample.services.AccountServices"&gt;<br>&nbsp;&nbsp; &lt;/bean&gt;<br><br>&nbsp;&nbsp; &lt;bean id="authenticationService" <br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; class="springexample.services.AuthenticationService"&gt;<br>&nbsp;&nbsp; &lt;/bean&gt;<br><br>&lt;/beans&gt;</p>
<p>　　以上服务在 sampleBanking-services.xml 中注册，然后装入 web.xml 文件中，就像 前面讨论的那样。控制器和服务配置好后，这个简单的应用程序就完成了。现在我们来看看部署和测试它时会发生什么!</p>
<p>　　<strong>部署应用程序</strong></p>
<p>　　把示例应用程序部署在 Tomcat servlet 容器中。Tomcat 是 Java Servlet 和 Java ServerPagest 技术的官方参考实现中使用的 servlet 容器。如果以前没这么做过，请 下载 jakarta-tomcat-5.0.28.exe 并运行它把 Tomcat 安装到自己喜欢的任何位置，例如 c:\tomcat5.0。</p>
<p>　　接下来，下载示例代码 并释放到驱动器（例如 c:\ ）上。创建了 Spring 项目的文件夹之后，打开它并把 spring-banking 子文件夹拷贝到 c:\tomvat5.0\webapps。spring-banking 文件夹是一个 Web 档案，里面包含 Spring MVC 示例应用程序。lib 文件夹包含应用程序需要的 Spring 框架、与Spring 相关的 MVC 库以及 JSTL 标记库和 jar 文件。</p>
<p>　　要启动 Tomcat 服务器，请使用以下命令：</p>
<p style="BACKGROUND: rgb(0,0,0) 0% 50%; moz-background-clip: -moz-initial; moz-background-origin: -moz-initial; moz-background-inline-policy: -moz-initial">　　<font color=#ffffff>cd bin C:\Tomcat 5.0\bin&gt; catalina.bat start</font></p>
<p>　　Tomcat 应当启动并部署 Spring MVC 示例应用程序。</p>
<p>　　<strong>测试应用程序</strong></p>
<p>　　要测试应用程序，请打开 Web 浏览器，指向 http://localhost:tomcatport/springbanking 并用 Tomcat 服务器实际运行的端口替换 tomcatport。应当看到图 1 所示的登录屏幕。输入用户 ID &#8220;admin&#8221;和口令&#8220;password&#8221;，并按下登录按钮。其他用户 ID 或口令会造成来自验证服务的错误。</p>
<p align=center><img height=445 src="http://www-128.ibm.com/developerworks/cn/java/wa-spring3/image1.jpg" width=600 border=0> <br>图 1. Spring MVC 示例登录屏幕</p>
<p>　　登录成功之后，会看到图 2 所示的帐户细节页面。</p>
<p align=center><img height=200 src="http://www-128.ibm.com/developerworks/cn/java/wa-spring3/image2.jpg" width=600 border=0> <br>图 2. Spring MVC 示例帐户细节页面<br><span class=h1b>Spring MVC框架的高级配置<br><a href="http://dev2dev.bea.com.cn/techdoc/2006068810.html">http://dev2dev.bea.com.cn/techdoc/2006068810.html</a></span></p>
<img src ="http://www.blogjava.net/topquan/aggbug/62658.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-09 22:26 <a href="http://www.blogjava.net/topquan/articles/62658.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>一个Spring程序 </title><link>http://www.blogjava.net/topquan/articles/61889.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Fri, 04 Aug 2006 16:56:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/61889.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/61889.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/61889.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/61889.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/61889.html</trackback:ping><description><![CDATA[<div class=postTitle>Spring通过XML文件，完成bean配置和bean间依赖关系的注入。<br><br>1.需要用到的包：<br>spring-core.jar<br>spring-beans.jar<br>spring-context.jar<br>commons-logging.jar<br><br>2.Bean文件<br>HelloBean.java<br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #0000ff">package</span><span style="COLOR: #000000">&nbsp;cn.blogjava.hello;<br><br></span><span style="COLOR: #0000ff">import</span><span style="COLOR: #000000">&nbsp;java.util.Date;<br><br></span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">class</span><span style="COLOR: #000000">&nbsp;HelloBean&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">private</span><span style="COLOR: #000000">&nbsp;String&nbsp;helloWord;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">private</span><span style="COLOR: #000000">&nbsp;String&nbsp;name;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">private</span><span style="COLOR: #000000">&nbsp;Date&nbsp;date;<br>&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;HelloBean()&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;HelloBean(String&nbsp;helloWord,&nbsp;String&nbsp;name)&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">this</span><span style="COLOR: #000000">.helloWord&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;helloWord;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">this</span><span style="COLOR: #000000">.name&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;name;<br>&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;String&nbsp;getHelloWord()&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;helloWord;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">void</span><span style="COLOR: #000000">&nbsp;setHelloWord(String&nbsp;helloword)&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">this</span><span style="COLOR: #000000">.helloWord&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;helloword;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;String&nbsp;getName()&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;name;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">void</span><span style="COLOR: #000000">&nbsp;setName(String&nbsp;name)&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">this</span><span style="COLOR: #000000">.name&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;name;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;Date&nbsp;getDate()&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">return</span><span style="COLOR: #000000">&nbsp;date;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">void</span><span style="COLOR: #000000">&nbsp;setDate(Date&nbsp;date)&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">this</span><span style="COLOR: #000000">.date&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;date;<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>}<br></span></div>
<br>配置文件<br>beans-config.xml<br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #0000ff">&lt;?</span><span style="COLOR: #ff00ff">xml&nbsp;version="1.0"&nbsp;encoding="UTF-8"</span><span style="COLOR: #0000ff">?&gt;</span><span style="COLOR: #000000"><br></span><span style="COLOR: #0000ff">&lt;!</span><span style="COLOR: #ff00ff">DOCTYPE&nbsp;beans&nbsp;PUBLIC&nbsp;"-//SPRING/DTD&nbsp;BEAN/EN"<br>&nbsp;&nbsp;&nbsp;&nbsp;"http://www.springframework.org/dtd/spring-beans.dtd"</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br></span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">beans</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">bean&nbsp;</span><span style="COLOR: #ff0000">id</span><span style="COLOR: #0000ff">="dateBean"</span><span style="COLOR: #ff0000">&nbsp;class</span><span style="COLOR: #0000ff">="java.util.Date"</span><span style="COLOR: #0000ff">/&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">bean&nbsp;</span><span style="COLOR: #ff0000">id</span><span style="COLOR: #0000ff">="helloBean"</span><span style="COLOR: #ff0000">&nbsp;class</span><span style="COLOR: #0000ff">="cn.blogjava.hello.HelloBean"</span><span style="COLOR: #ff0000">&nbsp;</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">property&nbsp;</span><span style="COLOR: #ff0000">name</span><span style="COLOR: #0000ff">="helloWord"</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">value</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000">Hello!</span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">value</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">property</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">property&nbsp;</span><span style="COLOR: #ff0000">name</span><span style="COLOR: #0000ff">="name"</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">value</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000">YYY!</span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">value</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">property</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000">&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">property&nbsp;</span><span style="COLOR: #ff0000">name</span><span style="COLOR: #0000ff">="date"</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;</span><span style="COLOR: #800000">ref&nbsp;</span><span style="COLOR: #ff0000">bean</span><span style="COLOR: #0000ff">="dateBean"</span><span style="COLOR: #ff0000">&nbsp;</span><span style="COLOR: #0000ff">/&gt;</span><span style="COLOR: #000000"><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">property</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">bean</span><span style="COLOR: #0000ff">&gt;</span><span style="COLOR: #000000"><br></span><span style="COLOR: #0000ff">&lt;/</span><span style="COLOR: #800000">beans</span><span style="COLOR: #0000ff">&gt;</span></div>
<br>3.测试程序<br>SpringDemo.java<br>
<div style="BORDER-RIGHT: #cccccc 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #cccccc 1px solid; PADDING-LEFT: 4px; FONT-SIZE: 13px; PADDING-BOTTOM: 4px; BORDER-LEFT: #cccccc 1px solid; WIDTH: 98%; WORD-BREAK: break-all; PADDING-TOP: 4px; BORDER-BOTTOM: #cccccc 1px solid; BACKGROUND-COLOR: #eeeeee"><span style="COLOR: #0000ff">package</span><span style="COLOR: #000000">&nbsp;cn.blogjava.hello;<br><br></span><span style="COLOR: #0000ff">import</span><span style="COLOR: #000000">&nbsp;org.springframework.context.ApplicationContext;<br></span><span style="COLOR: #0000ff">import</span><span style="COLOR: #000000">&nbsp;org.springframework.context.support.FileSystemXmlApplicationContext;<br><br></span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">class</span><span style="COLOR: #000000">&nbsp;SpringDemo&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">public</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">static</span><span style="COLOR: #000000">&nbsp;</span><span style="COLOR: #0000ff">void</span><span style="COLOR: #000000">&nbsp;main(String[]&nbsp;args)&nbsp;{<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ApplicationContext&nbsp;context&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="COLOR: #0000ff">new</span><span style="COLOR: #000000">&nbsp;FileSystemXmlApplicationContext(</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">beans-config.xml</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HelloBean&nbsp;helloBean&nbsp;</span><span style="COLOR: #000000">=</span><span style="COLOR: #000000">&nbsp;(HelloBean)context.getBean(</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">helloBean</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.print(</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">Name:&nbsp;</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(helloBean.getName());<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.print(</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">Word:&nbsp;</span><span style="COLOR: #000000">"</span><span style="COLOR: #000000">);<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(helloBean.getHelloWord());<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(helloBean.getDate());<br>&nbsp;&nbsp;&nbsp;&nbsp;}<br>}<br></span></div>
</div>
<img src ="http://www.blogjava.net/topquan/aggbug/61889.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-05 00:56 <a href="http://www.blogjava.net/topquan/articles/61889.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Spring:Bean基本管理 </title><link>http://www.blogjava.net/topquan/articles/61887.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Fri, 04 Aug 2006 16:55:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/61887.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/61887.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/61887.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/61887.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/61887.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: 一.从XML文件中获取Bean的方法1.采用BeanFactory方式&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Resource&nbsp;rs&nbsp;=&nbsp;new&nbsp;FileSystemResource("beans-config.xml");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n...&nbsp;&nbsp;<a href='http://www.blogjava.net/topquan/articles/61887.html'>阅读全文</a><img src ="http://www.blogjava.net/topquan/aggbug/61887.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-05 00:55 <a href="http://www.blogjava.net/topquan/articles/61887.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>在myeclipse下整合spring和hibernate </title><link>http://www.blogjava.net/topquan/articles/61877.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Fri, 04 Aug 2006 16:28:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/61877.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/61877.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/61877.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/61877.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/61877.html</trackback:ping><description><![CDATA[<p>引用&nbsp; <a href="http://www.blogjava.net/dyerac/archive/2006/08/04/61805.html">http://www.blogjava.net/dyerac/archive/2006/08/04/61805.html</a></p>
<img src ="http://www.blogjava.net/topquan/aggbug/61877.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-08-05 00:28 <a href="http://www.blogjava.net/topquan/articles/61877.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Struts+Spring+Hibernate组合使用</title><link>http://www.blogjava.net/topquan/articles/45101.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Mon, 08 May 2006 14:46:00 GMT</pubDate><guid>http://www.blogjava.net/topquan/articles/45101.html</guid><wfw:comment>http://www.blogjava.net/topquan/comments/45101.html</wfw:comment><comments>http://www.blogjava.net/topquan/articles/45101.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/topquan/comments/commentRss/45101.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/topquan/services/trackbacks/45101.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: 本文是开发基于 spring 的 web 应用的入门文章，前端采用 Struts MVC 框架，中间层采用 spring ，后台采用 Hibernate。 　　 　　本文包含以下内容： 　　 　　 &#183; 配置 Hibernate 和事务 　　 　　 &#183; 装载 Spring 的 applicationContext.xml 文件 　　 　　 &#183; 建立业务层和 DAO 之间...&nbsp;&nbsp;<a href='http://www.blogjava.net/topquan/articles/45101.html'>阅读全文</a><img src ="http://www.blogjava.net/topquan/aggbug/45101.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/topquan/" target="_blank">topquan</a> 2006-05-08 22:46 <a href="http://www.blogjava.net/topquan/articles/45101.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>