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


Step 20 – Add unit test for the SpringappController

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

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

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

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

springapp/src/tests/TestSpringappController.java

package tests;

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

public class TestSpringappController extends TestCase {

private ApplicationContext ac;

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

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

}

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

springapp/src/tests/WEB-INF/springapp-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

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


<beans>
<bean id="springappController" class="web.SpringappController"><property name="productManager"> <ref bean="prodMan"/> </property> </bean> <bean id="prodMan" class="bus.ProductManager"> <property name="products"> <list> <ref bean="product1"/> <ref bean="product2"/> <ref bean="product3"/> </list> </property> </bean> <bean id="product1" class="bus.Product"> <property name="description"><value>Lamp</value></property> <property name="price"><value>5.75</value></property> </bean> <bean id="product2" class="bus.Product"> <property name="description"><value>Table</value></property> <property name="price"><value>75.25</value></property> </bean> <bean id="product3" class="bus.Product"> <property name="description"><value>Chair</value></property> <property name="price"><value>22.79</value></property> </bean> </beans>

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


Step 21 – Add unit test and new functionality for ProductManager

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

springapp/src/tests/TestProductManager .java

package tests;

import java.util.List;
import java.util.ArrayList;
import junit.framework.TestCase;
import bus.ProductManager;
import bus.Product;

public class TestProductManager extends TestCase {

private ProductManager pm;

public void setUp() {
pm = new ProductManager();
Product p = new Product();
p.setDescription("Chair");
p.setPrice(new Double("20.50"));
ArrayList al = new ArrayList();
al.add(p);
p = new Product();
p.setDescription("Table");
p.setPrice(new Double("150.10"));
al.add(p);
pm.setProducts(al);
}

public void testGetProducs() {
List l = pm.getProducts();
Product p1 = (Product) l.get(0);
assertEquals("Chair", p1.getDescription());
Product p2 = (Product) l.get(1);
assertEquals("Table", p2.getDescription());
}

public void testIncreasePrice() {
pm.increasePrice(10);
List l = pm.getProducts();
Product p = (Product) l.get(0);
assertEquals(new Double("22.55"), p.getPrice());
p = (Product) l.get(1);
assertEquals(new Double("165.11"), p.getPrice());
}

}

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

springapp/src/bus/ProductManager.java

package bus;

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

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


Step 22 – Adding a form

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

springapp/war/WEB-INF/web.xml

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

<web-app>

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

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

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

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

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

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

springapp/src/bus/PriceIncrease.java

package bus;

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

public class PriceIncrease {

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

private int percentage;

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

public int getPercentage() {
return percentage;
}

}

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

springapp/src/bus/PriceIncreaseValidator.java

package bus;

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

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

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

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

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

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

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

public int getMinPercentage() {
return minPercentage;
}

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

public int getMaxPercentage() {
return maxPercentage;
}

}

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

springapp/war/WEB-INF/springapp-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

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

<beans>

<!-- Controller for the initial "Hello" page --> <bean id="springappController" class="web.SpringappController"> <property name="productManager"> <ref bean="prodMan"/> </property> </bean> <!-- Validator and Form Controller for the "Price Increase" page --> <bean id="priceIncreaseValidator" class="bus.PriceIncreaseValidator"/> <bean id="priceIncreaseForm" class="web.PriceIncreaseFormController"> <property name="sessionForm"><value>true</value></property> <property name="commandName"><value>priceIncrease</value></property> <property name="commandClass"><value>bus.PriceIncrease</value></property> <property name="validator"><ref bean="priceIncreaseValidator"/></property> <property name="formView"><value>priceincrease</value></property> <property name="successView"><value>hello.htm</value></property> <property name="productManager"> <ref bean="prodMan"/> </property> </bean> <bean id="prodMan" class="bus.ProductManager"> <property name="products"> <list> <ref bean="product1"/> <ref bean="product2"/> <ref bean="product3"/> </list> </property> </bean> <bean id="product1" class="bus.Product"> <property name="description"><value>Lamp</value></property> <property name="price"><value>5.75</value></property> </bean> <bean id="product2" class="bus.Product"> <property name="description"><value>Table</value></property> <property name="price"><value>75.25</value></property> </bean> <bean id="product3" class="bus.Product"> <property name="description"><value>Chair</value></property> <property name="price"><value>22.79</value></property> </bean> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename"><value>messages</value></property> </bean> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/hello.htm">springappController</prop> <prop key="/priceincrease.htm">priceIncreaseForm</prop> </props> </property> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"><value>/WEB-INF/jsp/</value></property> <property name="suffix"><value>.jsp</value></property> </bean> </beans>

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

springapp/src/web/PriceIncreaseFormController.java

package web;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

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

import bus.Product;
import bus.ProductManager;
import bus.PriceIncrease;

public class PriceIncreaseFormController extends SimpleFormController {

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

private ProductManager prodMan;

public ModelAndView onSubmit(Object command)
throws ServletException {

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

prodMan.increasePrice(increase);

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

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

protected Object formBackingObject(HttpServletRequest request) throws ServletException {

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

return priceIncrease;

}

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

public ProductManager getProductManager() {
return prodMan;
}

}

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

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

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

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

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

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

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

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




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

配置struts-config.xml
1Q?配置struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"<struts-config>
<!-- ======================================== Form Bean Definitions -->
<form-beans>
<form-bean
name="userForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="user" type="com.jandar.model.User"/>
</form-bean>
</form-beans>
<!-- =================================== Global Forward Definitions -->
<global-forwards>
</global-forwards>
<!-- =================================== Action Mapping Definitions -->
<action-mappings>
<action path="/user" type="com.jandar.web.struts.action.UserAction "
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
</action-mappings>
<!-- ================================ Message Resources Definitions -->
<message-resources parameter="messages"/>
</struts-config>
2Q?通过struts-config.xml把struts和springl合h
UserAction.java中的UserManager需要通过依赖注入Q通过plug-in技术将spring加到struts中,在struts-config.xml中增加一下代?br><plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml,
/WEB-INF/action-servlet.xml"/>
</plug-in>
让struts启动同时初始化springQ读取spring的配|文件applicationContext.xml,q且把struts的action也交lspring理Q把action配置到action-servlet.xml?br>新徏action-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"
<beans>
<bean name="/user" class="com.jandar.web.struts.action.UserAction" singleton="false">
<property name="userManager"><ref bean="userManager"/></property>
</bean>
</beans>
同时action映射到org.springframework.web.struts.DelegatingActionProxy即修?br><action path="/user" type="org.springframework.web.struts.DelegatingActionProxy"
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
3Q?新徏web.xml配置文g
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="

xmlns:xsi="

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

<servlet>

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

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

<init-param>

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

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

</init-param>

<init-param>

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

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

</init-param>

<init-param>

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

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

</init-param>

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

</servlet>


<servlet-mapping>

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

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

</servlet-mapping>


<welcome-file-list>

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

</welcome-file-list>


</web-app>

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

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="

<%@ taglib uri="

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

<head>

<html:base />


<title>index.jsp</title>

</head>


<body>

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

</body>

</html:html>

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

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



topquan 2006-08-09 23:15 发表评论
]]>
eclipse下struts+spring+hibernate快速入门(一Q?/title><link>http://www.aygfsteel.com/topquan/articles/62670.html</link><dc:creator>topquan</dc:creator><author>topquan</author><pubDate>Wed, 09 Aug 2006 15:14:00 GMT</pubDate><guid>http://www.aygfsteel.com/topquan/articles/62670.html</guid><wfw:comment>http://www.aygfsteel.com/topquan/comments/62670.html</wfw:comment><comments>http://www.aygfsteel.com/topquan/articles/62670.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.aygfsteel.com/topquan/comments/commentRss/62670.html</wfw:commentRss><trackback:ping>http://www.aygfsteel.com/topquan/services/trackbacks/62670.html</trackback:ping><description><![CDATA[<p>本文是开发基于spring的web应用的入门文章,前端采用Struts MVC框架Q中间层采用springQ后台采用Hibernate?<br>概览<br>本文包含以下内容Q?<br>•配置Hibernate和事?•装蝲Spring的applicationContext.xml文g <br>•建立业务层和DAO之间的依赖关p?•Spring应用到Struts?<br>q个例子是徏立一个简单的web应用Q叫MyUsers,完成用户理操作Q包含简单的数据库增Q删Q查Q该即CRUDQ新建,讉KQ更斎ͼ删除Q操作。这是一个三层的web应用Q通过ActionQStrutsQ访问业务层Q业务层讉KDAO。应用的Ml构Q从webQUserActionQ到中间层(UserManagerQ,再到数据讉K层(UserDAOQ,然后结果返回?<br>Spring层的真正强大在于它的声明型事务处理,帮定和对持久层支持(例如Hiberate和iBATISQ?<br>以下是完成这个例子的步骤Q?<br> 1Q安装Eclipse插g 2Q数据库 3Q配|Hibernate和Spring <br>4Q徏立Hibernate DAO接口的实现类 5Q运行测试类Q测试DAO的CRUD操作 <br>6Q创Z个处理类Q声明事?nbsp; 7Q创建Struts Action的测试类 <br>8Q创建web层的Action和model 9Q运行Action的测试类试CRUD操作 <br>10Q创建jsp文g通过览器进行CRUD操作 11Q通过览器校验jsp <br>开发环?br>Eclipse3.0.1 , MyEclispe 3.8.4, MySQL4.1.8, spring-framework-1.2.6-with-dependencies,Tomcat5.0<br>   数据库徏?nbsp;  use appfuse;<br>CREATE TABLE app_user (<br>  id int(11) NOT NULL auto_increment,<br>  firstname varchar(20) NOT NULL,<br>  lastname varchar(20) ,<br>  PRIMARY KEY  (id)<br>);<br>    新徏目<br>新徏一个web projectQ分别add struts,hibernate capabilities.spring 包中的dist<a></a><a></a>文g夹中的jar文g拯到WEB-INF/lib中?br>创徏持久层O/R mapping <br>1Q?在src/com.jandar.model下用hibernate插g从数据库导出app_user?hbm.xml文g改名为User.hbm.xml <br><?xml version="1.0"?><br><!DOCTYPE hibernate-mapping PUBLIC<br>                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"<br>                            "<a ></p> <p><!-- DO NOT EDIT: This is a generated file that is synchronized --><br><!-- by MyEclipse Hibernate tool integration.                   --><br><!-- Created Mon Jul 24 11:48:15 CST 2006                         --><br><hibernate-mapping package=""></p> <p>    <class name="AppUser" table="app_user"><br>        <id name="id" column="id" type="integer"><br>            <generator class="identity"/><br>        </id><br> <br>        <property name="firstName" column="firstname" type="string"  not-null="true" /><br>        <property name="lastName" column="lastname" type="string" /><br>    </class><br>    <br></hibernate-mapping><br>2Q在com.jandar.model下分别徏 BaseObject.java 和User.java<br>package com.jandar.model;<br>import java.io.Serializable; <br>import org.apache.commons.lang.builder.EqualsBuilder; <br>import org.apache.commons.lang.builder.HashCodeBuilder; <br>import org.apache.commons.lang.builder.ToStringBuilder; <br>import org.apache.commons.lang.builder.ToStringStyle; <br>public class BaseObject implements Serializable { <br>public String toString() { <br>return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); <br>} <br>public boolean equals(Object o) { <br>return EqualsBuilder.reflectionEquals(this, o); <br>}<br> public int hashCode() { <br>return HashCodeBuilder.reflectionHashCode(this); <br>} <br>} <br>package com.jandar.model;<br>public class User extends BaseObject { <br>private Long id; <br>private String firstName; <br>private String lastName; <br>/** <br>* @return Returns the id. <br>*/ <br>public Long getId() { <br>return id; <br> } <br>/** <br> * @param id The id to set. <br>*/ <br>public void setId(Long id) { <br>this.id = id; <br>}<br>public void getFirstName() { <br>return firstName; <br>}</p> <p>public void setFirstName(String firstName) { <br>this.firstName = firstName; <br>} <br> public String getLastName() { <br> return lastName; <br>} <br>public void setLastName(String lastName) { <br>this.lastName = lastName; <br>} <br>}<br>创徏DAOQ访问对?<br>1Q?在src/com.jandar.service.dao新徏IDAO.java接口Q所有的DAO都承该接口 <br>package com.jandar.service.dao; <br>public interface IDAO { <br>} <br>2Q?在src/com.jandar.service.dao下新建IUserDAO.java接口 <br>package com.jandar.service.dao;<br>import java.util.List;<br>public interface IUserDAO extends IDAO { <br>List getUsers(); <br>User getUser(Integer userid); <br>void saveUser(User user); <br>void removeUser(Integer id); <br>} <br>该接口提供了讉K对象的方法, <br>3Q?在src/com.jandar.service.dao.hibernate下新建UserDAOHiberante.java <br>package com.jandar.service.dao.hibernate;<br>import java.util.List; <br>import org.apache.commons.logging.Log; <br>import org.apache.commons.logging.LogFactory; <br>import org.springframework.orm.hibernate.support.HibernateDaoSupport; <br>import com.jandar.model.User; <br>import com.jandar.service.dao.IUserDAO; <br>public class UserDaoHibernate extends HibernateDaoSupport implements IUserDAO { <br>private Log log=LogFactory.getLog(UserDaoHibernate.class); <br>/* Q非 JavadocQ?<br>* @see com.jandar.dao.IUserDAO#getUsers() <br>*/ <br>public List getUsers() { <br>return getHibernateTemplate().find("from User"); <br>} <br>/* Q非 JavadocQ?<br>* @see com.jandar.dao.IUserDAO#getUser(java.lang.Long) <br>*/ <br>public User getUser(Integer id) { <br>// TODO 自动生成Ҏ存根 <br>return (User) getHibernateTemplate().get(User.class,id); <br>} <br>/* Q非 JavadocQ?<br>* @see com.jandar.dao.IUserDAO#saveUser(com.jandar.model.User) <br>*/ <br>public void saveUser(User user) { <br>log.debug("xxxxxxx"); <br>System.out.println("yyyy"); <br>getHibernateTemplate().saveOrUpdate(user); <br>if(log.isDebugEnabled()) <br>{ <br>log.debug("userId set to "+user.getId()); <br>} <br>} <br>/* Q非 JavadocQ?<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>在这个类中实CIUserDAO接口的方法,q且l承了HibernateDAOSupportcR这个类的作用是通过hibernate讉K、操作对象,q而实现对数据库的操作?<br>创徏业务层,声明事务 <br>业务层主要处理业务逻辑Q提供给web层友好的讉K接口和实现访问DAO层。用业务层的另一个好处是Q可以适应数据讉K层从Hibernate技术{Ud其他数据讉K技术?<br>1Q?在src/com.jandar.service下新Z个IUserManager接口Q该接口有几乎于IUserDAO同样的方法,不同的是处理参数Q应为IUserManager是供web层访问的?<br>package com.jandar.service;<br>import java.util.List;<br>import com.jandar.model.User;<br>public interface IUserManager { <br>User getUser(String userid); <br>List getUsers(); <br>User saveUser(User user); <br>void removeUser(String userid); <br>} <br>2Q?在src/com.jandar.service.spring下新建IUserManager实现c,UserManager.java <br>package com.jandar.service.spring; <br>import java.util.List; <br>import org.apache.commons.logging.Log; <br>import org.apache.commons.logging.LogFactory; <br>import com.jandar.model.User; <br>import com.jandar.service.IUserManager; <br>import com.jandar.service.dao.IUserDAO;  <br>public class UserManager implements IUserManager { <br>/* Q非 JavadocQ?<br>* @see com.jandar.service.IUserManager#getUser(java.lang.String) <br>*/ <br>private static Log log=LogFactory.getLog(UserManager.class); <br>public IUserDAO userDao; <br>/** <br>* @return q回 userDao?<br>*/ <br>public IUserDAO getUserDao() { <br>return userDao; <br>} <br>/** <br>* @param userDao 要设|的 userDao?<br>*/ <br>public void setUserDao(IUserDAO userDao) { <br>this.userDao = userDao; <br>} <br>public User getUser(String userid) { <br>User user=userDao.getUser(Integer.valueOf(userid)); <br>if(user==null){ <br>log.warn(" user id "+userid+" not found in database"); <br>} <br>if(log.isDebugEnabled()){ <br>log.debug("get a user with id "+userid); <br>} <br>return user; <br>} <br>/* Q非 JavadocQ?<br>* @see com.jandar.service.IUserManager#getUsers() <br>*/ <br>public List getUsers() { <br>// TODO 自动生成Ҏ存根 <br>return userDao.getUsers(); <br>} <br>/* Q非 JavadocQ?<br>* @see com.jandar.service.IUserManager#saveUser(com.jandar.model.User) <br>*/ <br>public User saveUser(User user) { <br>// TODO 自动生成Ҏ存根 <br>userDao.saveUser(user); <br>return user; <br>} <br>/* Q非 JavadocQ?<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通过讉Kdao接口实现业务逻辑和数据库操作。同时该cM提供了setҎQ运用了Spring的依赖注入机制。但未使用spring的AOP和声明事务?<br>配置applicationContext.xml <br>在WEB-INF 下新建applicationContext.xml<br><?xml version="1.0" encoding="UTF-8"?></p> <p><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"</p> <p>"<a ></p> <p><br><beans></p> <p><br><bean id="dataSource" </p> <p>class="org.springframework.jdbc.datasource.DriverManagerDataSource"></p> <p><property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property></p> <p><property name="url"><value>jdbc:mysql://localhost:3306/appfuse</value></property></p> <p><property name="username"><value>root</value></property></p> <p><!-- Make sure <value> tags are on same line - if they''re not, </p> <p>authentication will fail --></p> <p><property name="password"><value>root</value></property></p> <p></bean></p> <p><br><!-- Hibernate SessionFactory --></p> <p><bean id="sessionFactory" </p> <p>class="org.springframework.orm.hibernate.LocalSessionFactoryBean"></p> <p><property name="dataSource"><ref local="dataSource"/></property></p> <p><property name="mappingResources"></p> <p><list></p> <p><value>com/jandar/model/User.hbm.xml</value></p> <p></list></p> <p></property></p> <p><property name="hibernateProperties"></p> <p><props></p> <p><prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop></p> <p><prop key="hibernate.hbm2ddl.auto">create</prop></p> <p></props></p> <p></property></p> <p></bean></p> <p><br><!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) --></p> <p><bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager"></p> <p><property name="sessionFactory"><ref local="sessionFactory"/></property></p> <p></bean></p> <p><br><bean id="userDAO" class="com.jandar.service.dao.hibernate.UserDAOHibernate"></p> <p><property name="sessionFactory"><ref local="sessionFactory"/></property></p> <p></bean> </p> <p><br><bean id="userManagerTarget" class="com.jandar.service.spring.UserManager"></p> <p><property name="userDAO"><ref local="userDAO"/></property></p> <p></bean></p> <p><br><bean id="userManager" </p> <p>class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"></p> <p><property name="transactionManager"><ref local="transactionManager"/></property></p> <p><property name="target"><ref local="userManagerTarget"/></property></p> <p><property name="transactionAttributes"></p> <p><props></p> <p><prop key="save*">PROPAGATION_REQUIRED</prop></p> <p><prop key="remove*">PROPAGATION_REQUIRED</prop></p> <p><prop key="*">PROPAGATION_REQUIRED,readOnly</prop></p> <p></props></p> <p></property><br></bean></p> <p><bean name="/user" class="com.jandar.web.struts.action.UserAction"<br>singleton="false"><br><property name="mgr"><br><ref bean="userManager" /><br></property><br></bean></p> <p><br></beans><br></p> <p> </p> <p class=diaryFoot></p> <img src ="http://www.aygfsteel.com/topquan/aggbug/62670.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.aygfsteel.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:14 <a href="http://www.aygfsteel.com/topquan/articles/62670.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>q入 Spring MVChttp://www.aygfsteel.com/topquan/articles/62658.htmltopquantopquanWed, 09 Aug 2006 14:26:00 GMThttp://www.aygfsteel.com/topquan/articles/62658.htmlhttp://www.aygfsteel.com/topquan/comments/62658.htmlhttp://www.aygfsteel.com/topquan/articles/62658.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/62658.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/62658.htmlSpring MVC 框架

  Spring 框架提供了构?Web 应用E序的全功能 MVC 模块。?Spring 可插入的 MVC 架构Q可以选择是用内|的 Spring Web 框架q是 Struts q样?Web 框架。通过{略接口QSpring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer PagesQJSPQ技术、Velocity、Tiles、iText ?POI。Spring MVC 框架q不知道使用的视图,所以不会强q您只?JSP 技术。Spring MVC 分离了控制器、模型对象、分z֙以及处理E序对象的角Ԍq种分离让它们更Ҏq行定制?/p>

  Spring ?Web MVC 框架是围l?DispatcherServlet 设计的,它把h分派l处理程序,同时带有可配|的处理E序映射、视图解析、本地语a、主题解析以及上载文件支持。默认的处理E序是非常简单的 Controller 接口Q只有一个方?ModelAndView handleRequest(request, response)。Spring 提供了一个控制器层次l构Q可以派生子cR如果应用程序需要处理用戯入表单,那么可以l承 AbstractFormController。如果需要把多页输入处理C个表单,那么可以l承 AbstractWizardFormController?/p>

  CZ应用E序有助于直观地学习q些Ҏ。银行应用程序允许用h索他们的帐户信息。在构徏银行应用E序的过E中Q可以学到如何配|?Spring MVC 框架和实现框架的视图层,视图层包?JSTL 标记Q用于显C出的数据Q和JavaServer Pages 技术?/p>

  配置 Spring MVC

  要开始构建示例应用程序,请配|?Spring MVC ?DispatcherServlet。请?web.xml 文g中注册所有配|。清?1 昄了如何配|?sampleBankingServlet?/p>

清单 1. 配置 Spring MVC DispatcherServlet

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

  DispatcherServlet 从一?XML 文g装入 Spring 应用E序上下文,XML 文g的名U是 servlet 的名U后面加?-servlet 。在q个CZ中,DispatcherServlet 会从 sampleBankingServlet-servlet.xml 文g装入应用E序上下文?

  配置应用E序?URL

  下一步是配置惌 sampleBankingServlet 处理?URL。同Pq是要在 web.xml 中注册所有这些信息?/p>

清单 2. 配置惌处理?URL

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

  装入配置文g

  下面Q装入配|文件。ؓ了做到这点,请ؓ Servlet 2.3 规范注册 ContextLoaderListener 或ؓ Servlet 2.2 及以下的容器注册 ContextLoaderServlet。ؓ了保障后向兼Ҏ,L ContextLoaderServlet。在启动 Web 应用E序ӞContextLoaderServlet 会装?Spring 配置文g。清?3 注册?ContextLoaderServlet?/p>

清单 3. 注册 ContextLoaderServlet

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

  contextConfigLocation 参数定义了要装入?Spring 配置文gQ如下面?servlet 上下文所C?/p>

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

  sampleBanking-services.xml 文g代表CZ银行应用E序服务的配|和 bean 配置。如果想装入多个配置文gQ可以在 <param-value> 标记中用逗号作分隔符?/p>

  Spring MVC CZ

  CZ银行应用E序允许用户Ҏ惟一?ID 和口令查看帐户信息。虽?Spring MVC 提供了其他选项Q但是我采?JSP 技术作N面。这个简单的应用E序包含一个视N用于用户输入QID 和口令)Q另一|C用L帐户信息?/p>

  我从 LoginBankController 开始,它扩展了 Spring MVC ?SimpleFormController。SimpleFormContoller 提供了显CZ HTTP GET h接收到的表单的功能,以及处理?HTTP POST 接收到的相同表单数据的功能。LoginBankController ?AuthenticationService ?AccountServices 服务q行验证Qƈ执行帐户zd?#8220; 配置视图属?”一节中的清?5 描述了如何把 AuthenticationService ?AccountServices q接?LoginBankController?清单 4 昄?LoginBankController 的代码?/p>

清单 4. LoginBankController 扩展 SimpleFormController

public class LoginBankController extends SimpleFormController {

   public LoginBankController(){

   }

   protected ModelAndView onSubmit(Object command) throws Exception{

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

   private AuthenticationService authenticationService;

   private AccountServices accountServices;

   public AccountServices getAccountServices() {
      return accountServices;
   }

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

   public AuthenticationService getAuthenticationService() {
      return authenticationService;
   }

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

  配置视图属?/strong>

  下面Q必L册在接收?HTTP GET h时显C的面。在 Spring 配置中用 formView 属性注册这个页面,如清?5 所C。sucessView 属性代表表单数据提交而且 doSubmitAction() Ҏ中的逻辑成功执行之后昄的页面。formView ?sucessView 属性都代表被定义的视图的逻辑名称Q逻辑名称映射到实际的视图面?/p>

清单 5. 注册 LoginBankController

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

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

   </bean>

  commandClass ?commandName 标记军_在视图面中活动的 bean。例如,可以通过 login.jsp 面讉K loginCommand beanQ这个页面是应用E序的登录页面。一旦用h交了d面Q应用程序就可以?LoginBankController ?onSubmit() Ҏ中的命o对象索出表单数据?/p>

  视图解析?/strong>

  Spring MVC ?视图解析?把每个逻辑名称解析成实际的资源Q即包含帐户信息?JSP 文g。我用的?Spring ?InternalResourceViewResolverQ如 清单 6 所C?/p>

清单 6. InternalResourceViewResolver

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

  因ؓ我在 JSP 面中用了 JSTL 标记Q所以用Ld名称解析成资?/jsp/login.jspQ?viewClass 成ؓ JstlView?/p>

  验证和帐h?/strong>

  像前面提到的,LoginBankController 内部q接?Spring ?AccountServices ?AuthenticationService。AuthenticationService cd理银行应用程序的验证。AccountServices cd理典型的银行服务Q例如查找交易和甉|。清?7 昄了银行应用程序的验证和帐h务的配置?/p>

清单 7. 配置验证和帐h?/p>

<beans>

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

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

</beans>

  以上服务?sampleBanking-services.xml 中注册,然后装入 web.xml 文g中,像 前面讨论的那栗控制器和服务配|好后,q个单的应用E序完成了。现在我们来看看部v和测试它时会发生什?

  部v应用E序

  把示例应用程序部|在 Tomcat servlet 容器中。Tomcat ?Java Servlet ?Java ServerPagest 技术的官方参考实C使用?servlet 容器。如果以前没q么做过Q请 下蝲 jakarta-tomcat-5.0.28.exe q运行它?Tomcat 安装到自己喜Ƣ的M位置Q例?c:\tomcat5.0?/p>

  接下来,下蝲CZ代码 q攑ֈ驱动器(例如 c:\ Q上。创Z Spring 目的文件夹之后Q打开它ƈ?spring-banking 子文件夹拯?c:\tomvat5.0\webapps。spring-banking 文gҎ一?Web 档案Q里面包?Spring MVC CZ应用E序。lib 文g夹包含应用程序需要的 Spring 框架、与Spring 相关?MVC 库以?JSTL 标记库和 jar 文g?/p>

  要启?Tomcat 服务器,请用以下命令:

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

  Tomcat 应当启动q|?Spring MVC CZ应用E序?/p>

  试应用E序

  要测试应用程序,h开 Web 览器,指向 http://localhost:tomcatport/springbanking q用 Tomcat 服务器实际运行的端口替换 tomcatport。应当看到图 1 所C的d屏幕。输入用?ID “admin”和口?#8220;password”Qƈ按下d按钮。其他用?ID 或口令会造成来自验证服务的错误?/p>


?1. Spring MVC CZd屏幕

  d成功之后Q会看到?2 所C的帐户l节面?/p>


?2. Spring MVC CZ帐户l节面
Spring MVC框架的高U配|?br>http://dev2dev.bea.com.cn/techdoc/2006068810.html



topquan 2006-08-09 22:26 发表评论
]]>
一个SpringE序 http://www.aygfsteel.com/topquan/articles/61889.htmltopquantopquanFri, 04 Aug 2006 16:56:00 GMThttp://www.aygfsteel.com/topquan/articles/61889.htmlhttp://www.aygfsteel.com/topquan/comments/61889.htmlhttp://www.aygfsteel.com/topquan/articles/61889.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/61889.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/61889.htmlSpring通过XML文gQ完成bean配置和bean间依赖关pȝ注入?br>
1.需要用到的包:
spring-core.jar
spring-beans.jar
spring-context.jar
commons-logging.jar

2.Bean文g
HelloBean.java
package cn.blogjava.hello;

import java.util.Date;

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

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

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

    
public String getName() {
        
return name;
    }

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

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

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

3.试E序
SpringDemo.java
package cn.blogjava.hello;

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

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


topquan 2006-08-05 00:56 发表评论
]]>
Spring:Bean基本理 http://www.aygfsteel.com/topquan/articles/61887.htmltopquantopquanFri, 04 Aug 2006 16:55:00 GMThttp://www.aygfsteel.com/topquan/articles/61887.htmlhttp://www.aygfsteel.com/topquan/comments/61887.htmlhttp://www.aygfsteel.com/topquan/articles/61887.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/61887.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/61887.html阅读全文

topquan 2006-08-05 00:55 发表评论
]]>
在myeclipse下整合spring和hibernate http://www.aygfsteel.com/topquan/articles/61877.htmltopquantopquanFri, 04 Aug 2006 16:28:00 GMThttp://www.aygfsteel.com/topquan/articles/61877.htmlhttp://www.aygfsteel.com/topquan/comments/61877.htmlhttp://www.aygfsteel.com/topquan/articles/61877.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/61877.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/61877.html引用  http://www.aygfsteel.com/dyerac/archive/2006/08/04/61805.html



topquan 2006-08-05 00:28 发表评论
]]>
Struts+Spring+Hibernatel合使用http://www.aygfsteel.com/topquan/articles/45101.htmltopquantopquanMon, 08 May 2006 14:46:00 GMThttp://www.aygfsteel.com/topquan/articles/45101.htmlhttp://www.aygfsteel.com/topquan/comments/45101.htmlhttp://www.aygfsteel.com/topquan/articles/45101.html#Feedback0http://www.aygfsteel.com/topquan/comments/commentRss/45101.htmlhttp://www.aygfsteel.com/topquan/services/trackbacks/45101.html阅读全文

topquan 2006-05-08 22:46 发表评论
]]>
վ֩ģ壺 | ֱ| ض| | ղ| ʯ̨| ƽ| ƽ| | | ǭ| | | | ƽ| | | | | ػ| | ƴ| | ¦| Ȫ| | ض| | | ɽ| | | Զ| ƽ| ͨ| ԭ| | | | | ˮ|