锘??xml version="1.0" encoding="utf-8" standalone="yes"?>亚洲欧洲中文日韩av乱码,自拍偷自拍亚洲精品播放,国产亚洲一卡2卡3卡4卡新区http://www.tkk7.com/topquan/category/23897.html鍒嗕韓浠峰?---鎴愬氨浣犳垜----鎴戠殑鍗氬----浣犵殑瀹?/description>zh-cnSat, 07 Jul 2007 14:45:52 GMTSat, 07 Jul 2007 14:45:52 GMT60Developing a Spring Framework MVC application錛堝洓錛?/title><link>http://www.tkk7.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.tkk7.com/topquan/articles/62677.html</guid><wfw:comment>http://www.tkk7.com/topquan/comments/62677.html</wfw:comment><comments>http://www.tkk7.com/topquan/articles/62677.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/topquan/comments/commentRss/62677.html</wfw:commentRss><trackback:ping>http://www.tkk7.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.tkk7.com/topquan/articles/62677.html'>闃呰鍏ㄦ枃</a><img src ="http://www.tkk7.com/topquan/aggbug/62677.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:25 <a href="http://www.tkk7.com/topquan/articles/62677.html#Feedback" target="_blank" style="text-decoration:none;">鍙戣〃璇勮</a></div>]]></description></item><item><title>Developing a Spring Framework MVC application 錛堜笁錛?http://www.tkk7.com/topquan/articles/62676.htmltopquantopquanWed, 09 Aug 2006 15:23:00 GMThttp://www.tkk7.com/topquan/articles/62676.htmlhttp://www.tkk7.com/topquan/comments/62676.htmlhttp://www.tkk7.com/topquan/articles/62676.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/62676.htmlhttp://www.tkk7.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 application錛堜簩錛?/title><link>http://www.tkk7.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.tkk7.com/topquan/articles/62675.html</guid><wfw:comment>http://www.tkk7.com/topquan/comments/62675.html</wfw:comment><comments>http://www.tkk7.com/topquan/articles/62675.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/topquan/comments/commentRss/62675.html</wfw:commentRss><trackback:ping>http://www.tkk7.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.tkk7.com/topquan/aggbug/62675.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:22 <a href="http://www.tkk7.com/topquan/articles/62675.html#Feedback" target="_blank" style="text-decoration:none;">鍙戣〃璇勮</a></div>]]></description></item><item><title>Developing a Spring Framework MVC application錛堜竴錛?/title><link>http://www.tkk7.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.tkk7.com/topquan/articles/62673.html</guid><wfw:comment>http://www.tkk7.com/topquan/comments/62673.html</wfw:comment><comments>http://www.tkk7.com/topquan/articles/62673.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/topquan/comments/commentRss/62673.html</wfw:commentRss><trackback:ping>http://www.tkk7.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.tkk7.com/topquan/aggbug/62673.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:21 <a href="http://www.tkk7.com/topquan/articles/62673.html#Feedback" target="_blank" style="text-decoration:none;">鍙戣〃璇勮</a></div>]]></description></item><item><title>eclipse涓媠truts+spring+hibernate蹇熷叆闂紙浜岋級http://www.tkk7.com/topquan/articles/62672.htmltopquantopquanWed, 09 Aug 2006 15:15:00 GMThttp://www.tkk7.com/topquan/articles/62672.htmlhttp://www.tkk7.com/topquan/comments/62672.htmlhttp://www.tkk7.com/topquan/articles/62672.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/62672.htmlhttp://www.tkk7.com/topquan/services/trackbacks/62672.htmlWeb灞傦紟
鍒涘緩Struts Action錛屼負浜嗗湪涓涓猘ction涓疄鐜癈RUD鎿嶄綔錛孉ction緇ф壙浜咲ispatchAction鏍規嵁鍙傛暟鍐沖畾璋冪敤鏂規硶銆傚湪src/com.jandar.web.struts.action涓嬪垱寤篣serAction.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璁塊棶涓氬姟灞傦紝UserManager閫氳繃渚濊禆娉ㄥ叆
2錛?鍒涘緩struts ActionFrom
鍙互鍦╯rc/com.jandar.web.struts.form涓嬪垱寤轟竴涓猆serForm.java鐨剆truts ActionForm錛屾垜浠篃鍙互閲囩敤宸插緩濂界殑妯″瀷鏉ラ厤緗甪orm bean鍗抽噰鐢ㄥ姩鎬乫orm
org.apache.struts.validator.DynaValidatorForm 鍚屾椂鎸囧畾property 涓?br>com.jandar.model.User璇﹁struts-config.xml閰嶇疆鏂囦歡.

閰嶇疆struts-config.xml
1錛?閰嶇疆struts-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"<struts-config>
<!-- ======================================== Form Bean Definitions -->
<form-beans>
<form-bean
name="userForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="user" type="com.jandar.model.User"/>
</form-bean>
</form-beans>
<!-- =================================== Global Forward Definitions -->
<global-forwards>
</global-forwards>
<!-- =================================== Action Mapping Definitions -->
<action-mappings>
<action path="/user" type="com.jandar.web.struts.action.UserAction "
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
</action-mappings>
<!-- ================================ Message Resources Definitions -->
<message-resources parameter="messages"/>
</struts-config>
2錛?閫氳繃struts-config.xml鎶妔truts鍜宻pring緇撳悎璧鋒潵
UserAction.java涓殑UserManager闇瑕侀氳繃渚濊禆娉ㄥ叆錛岄氳繃plug-in鎶鏈皢spring鍔犲埌struts涓紝鍦╯truts-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>
璁﹕truts鍚姩鍚屾椂鍒濆鍖杝pring錛岃鍙杝pring鐨勯厤緗枃浠禷pplicationContext.xml,騫朵笖鎶妔truts鐨刟ction涔熶氦緇檚pring綆$悊錛屾妸action閰嶇疆鍒癮ction-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>
鍚屾椂灝哸ction鏄犲皠鍒皁rg.springframework.web.struts.DelegatingActionProxy鍗充慨鏀?br><action path="/user" type="org.springframework.web.struts.DelegatingActionProxy"
name="userForm" scope="request" parameter="method" validate="false">
<forward name="list" path="/userList.jsp"/>
<forward name="edit" path="/userForm.jsp"/>
</action>
3錛?鏂板緩web.xml閰嶇疆鏂囦歡
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="

xmlns:xsi="

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

<servlet>

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

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

<init-param>

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

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

</init-param>

<init-param>

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

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

</init-param>

<init-param>

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

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

</init-param>

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

</servlet>


<servlet-mapping>

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

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

</servlet-mapping>


<welcome-file-list>

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

</welcome-file-list>


</web-app>

4錛?鏂板緩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涓媠truts+spring+hibernate蹇熷叆闂紙涓錛?/title><link>http://www.tkk7.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.tkk7.com/topquan/articles/62670.html</guid><wfw:comment>http://www.tkk7.com/topquan/comments/62670.html</wfw:comment><comments>http://www.tkk7.com/topquan/articles/62670.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.tkk7.com/topquan/comments/commentRss/62670.html</wfw:commentRss><trackback:ping>http://www.tkk7.com/topquan/services/trackbacks/62670.html</trackback:ping><description><![CDATA[<p>鏈枃鏄紑鍙戝熀浜巗pring鐨剋eb搴旂敤鐨勫叆闂ㄦ枃绔狅紝鍓嶇閲囩敤Struts MVC妗嗘灦錛屼腑闂村眰閲囩敤spring錛屽悗鍙伴噰鐢℉ibernate銆?<br>姒傝<br>鏈枃鍖呭惈浠ヤ笅鍐呭錛?<br>•閰嶇疆Hibernate鍜屼簨鍔?•瑁呰澆Spring鐨刟pplicationContext.xml鏂囦歡 <br>•寤虹珛涓氬姟灞傚拰DAO涔嬮棿鐨勪緷璧栧叧緋?•灝哠pring搴旂敤鍒癝truts涓?<br>榪欎釜渚嬪瓙鏄緩绔嬩竴涓畝鍗曠殑web搴旂敤錛屽彨MyUsers,瀹屾垚鐢ㄦ埛綆$悊鎿嶄綔錛屽寘鍚畝鍗曠殑鏁版嵁搴撳錛屽垹錛屾煡錛岃鍗矯RUD錛堟柊寤猴紝璁塊棶錛屾洿鏂幫紝鍒犻櫎錛夋搷浣溿傝繖鏄竴涓笁灞傜殑web搴旂敤錛岄氳繃Action錛圫truts錛夎闂笟鍔″眰錛屼笟鍔″眰璁塊棶DAO銆傚簲鐢ㄧ殑鎬諱綋緇撴瀯錛嶄粠web錛圲serAction錛夊埌涓棿灞傦紙UserManager錛夛紝鍐嶅埌鏁版嵁璁塊棶灞傦紙UserDAO錛夛紝鐒跺悗灝嗙粨鏋滆繑鍥炪?<br>Spring灞傜殑鐪熸寮哄ぇ鍦ㄤ簬瀹冪殑澹版槑鍨嬩簨鍔″鐞嗭紝甯畾鍜屽鎸佷箙灞傛敮鎸侊紙渚嬪Hiberate鍜宨BATIS錛?<br>浠ヤ笅鏄畬鎴愯繖涓緥瀛愮殑姝ラ錛?<br> 1錛夊畨瑁匛clipse鎻掍歡 2錛夋暟鎹簱寤鴻〃 3錛夐厤緗瓾ibernate鍜孲pring <br>4錛夊緩绔婬ibernate DAO鎺ュ彛鐨勫疄鐜扮被 5錛夎繍琛屾祴璇曠被錛屾祴璇旸AO鐨凜RUD鎿嶄綔 <br>6錛夊垱寤轟竴涓鐞嗙被錛屽0鏄庝簨鍔?nbsp; 7錛夊垱寤篠truts Action鐨勬祴璇曠被 <br>8錛夊垱寤簑eb灞傜殑Action鍜宮odel 9錛夎繍琛孉ction鐨勬祴璇曠被嫻嬭瘯CRUD鎿嶄綔 <br>10錛夊垱寤簀sp鏂囦歡閫氳繃嫻忚鍣ㄨ繘琛孋RUD鎿嶄綔 11錛夐氳繃嫻忚鍣ㄦ牎楠宩sp <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>鏂板緩涓涓獁eb project錛屽垎鍒玜dd struts,hibernate capabilities.灝唖pring 鍖呬腑鐨刣ist<a></a><a></a>鏂囦歡澶逛腑鐨刯ar鏂囦歡鎷瘋礉鍒癢EB-INF/lib涓?br>鍒涘緩鎸佷箙灞侽/R mapping <br>1錛?鍦╯rc/com.jandar.model涓嬬敤hibernate鎻掍歡浠庢暟鎹簱瀵煎嚭app_user鐨?hbm.xml鏂囦歡鏀瑰悕涓篣ser.hbm.xml <br><?xml version="1.0"?><br><!DOCTYPE hibernate-mapping PUBLIC<br>                            "-//Hibernate/Hibernate Mapping DTD 2.0//EN"<br>                            "<a ></p> <p><!-- DO NOT EDIT: This is a generated file that is synchronized --><br><!-- by MyEclipse Hibernate tool integration.                   --><br><!-- Created Mon Jul 24 11:48:15 CST 2006                         --><br><hibernate-mapping package=""></p> <p>    <class name="AppUser" table="app_user"><br>        <id name="id" column="id" type="integer"><br>            <generator class="identity"/><br>        </id><br> <br>        <property name="firstName" column="firstname" type="string"  not-null="true" /><br>        <property name="lastName" column="lastname" type="string" /><br>    </class><br>    <br></hibernate-mapping><br>2錛庡湪com.jandar.model涓嬪垎鍒緩 BaseObject.java 鍜孶ser.java<br>package com.jandar.model;<br>import java.io.Serializable; <br>import org.apache.commons.lang.builder.EqualsBuilder; <br>import org.apache.commons.lang.builder.HashCodeBuilder; <br>import org.apache.commons.lang.builder.ToStringBuilder; <br>import org.apache.commons.lang.builder.ToStringStyle; <br>public class BaseObject implements Serializable { <br>public String toString() { <br>return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); <br>} <br>public boolean equals(Object o) { <br>return EqualsBuilder.reflectionEquals(this, o); <br>}<br> public int hashCode() { <br>return HashCodeBuilder.reflectionHashCode(this); <br>} <br>} <br>package com.jandar.model;<br>public class User extends BaseObject { <br>private Long id; <br>private String firstName; <br>private String lastName; <br>/** <br>* @return Returns the id. <br>*/ <br>public Long getId() { <br>return id; <br> } <br>/** <br> * @param id The id to set. <br>*/ <br>public void setId(Long id) { <br>this.id = id; <br>}<br>public void getFirstName() { <br>return firstName; <br>}</p> <p>public void setFirstName(String firstName) { <br>this.firstName = firstName; <br>} <br> public String getLastName() { <br> return lastName; <br>} <br>public void setLastName(String lastName) { <br>this.lastName = lastName; <br>} <br>}<br>鍒涘緩DAO錛岃闂璞?<br>1錛?鍦╯rc/com.jandar.service.dao鏂板緩IDAO.java鎺ュ彛錛屾墍鏈夌殑DAO閮界戶鎵胯鎺ュ彛 <br>package com.jandar.service.dao; <br>public interface IDAO { <br>} <br>2錛?鍦╯rc/com.jandar.service.dao涓嬫柊寤篒UserDAO.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>璇ユ帴鍙f彁渚涗簡璁塊棶瀵硅薄鐨勬柟娉曪紝 <br>3錛?鍦╯rc/com.jandar.service.dao.hibernate涓嬫柊寤篣serDAOHiberante.java <br>package com.jandar.service.dao.hibernate;<br>import java.util.List; <br>import org.apache.commons.logging.Log; <br>import org.apache.commons.logging.LogFactory; <br>import org.springframework.orm.hibernate.support.HibernateDaoSupport; <br>import com.jandar.model.User; <br>import com.jandar.service.dao.IUserDAO; <br>public class UserDaoHibernate extends HibernateDaoSupport implements IUserDAO { <br>private Log log=LogFactory.getLog(UserDaoHibernate.class); <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.dao.IUserDAO#getUsers() <br>*/ <br>public List getUsers() { <br>return getHibernateTemplate().find("from User"); <br>} <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.dao.IUserDAO#getUser(java.lang.Long) <br>*/ <br>public User getUser(Integer id) { <br>// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴 <br>return (User) getHibernateTemplate().get(User.class,id); <br>} <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.dao.IUserDAO#saveUser(com.jandar.model.User) <br>*/ <br>public void saveUser(User user) { <br>log.debug("xxxxxxx"); <br>System.out.println("yyyy"); <br>getHibernateTemplate().saveOrUpdate(user); <br>if(log.isDebugEnabled()) <br>{ <br>log.debug("userId set to "+user.getId()); <br>} <br>} <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.dao.IUserDAO#removeUser(java.lang.Long) <br>*/ <br>public void removeUser(Integer id) { <br>Object user=getHibernateTemplate().load(User.class,id); <br>getHibernateTemplate().delete(user); <br>if(log.isDebugEnabled()){ <br>log.debug("del user "+id); <br>} <br>} <br>} <br>鍦ㄨ繖涓被涓疄鐜頒簡IUserDAO鎺ュ彛鐨勬柟娉曪紝騫朵笖緇ф壙浜咹ibernateDAOSupport綾匯傝繖涓被鐨勪綔鐢ㄦ槸閫氳繃hibernate璁塊棶銆佹搷浣滃璞★紝榪涜屽疄鐜板鏁版嵁搴撶殑鎿嶄綔銆?<br>鍒涘緩涓氬姟灞傦紝澹版槑浜嬪姟 <br>涓氬姟灞備富瑕佸鐞嗕笟鍔¢昏緫錛屾彁渚涚粰web灞傚弸濂界殑璁塊棶鎺ュ彛鍜屽疄鐜拌闂瓺AO灞傘傜敤涓氬姟灞傜殑鍙︿竴涓ソ澶勬槸錛屽彲浠ラ傚簲鏁版嵁璁塊棶灞備粠Hibernate鎶鏈漿縐誨埌鍏朵粬鏁版嵁璁塊棶鎶鏈?<br>1錛?鍦╯rc/com.jandar.service涓嬫柊寤轟竴涓狪UserManager鎺ュ彛錛岃鎺ュ彛鏈夊嚑涔庝簬IUserDAO鍚屾牱鐨勬柟娉曪紝涓嶅悓鐨勬槸澶勭悊鍙傛暟錛屽簲涓篒UserManager鏄緵web灞傝闂殑銆?<br>package com.jandar.service;<br>import java.util.List;<br>import com.jandar.model.User;<br>public interface IUserManager { <br>User getUser(String userid); <br>List getUsers(); <br>User saveUser(User user); <br>void removeUser(String userid); <br>} <br>2錛?鍦╯rc/com.jandar.service.spring涓嬫柊寤篒UserManager瀹炵幇綾伙紝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>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.service.IUserManager#getUser(java.lang.String) <br>*/ <br>private static Log log=LogFactory.getLog(UserManager.class); <br>public IUserDAO userDao; <br>/** <br>* @return 榪斿洖 userDao銆?<br>*/ <br>public IUserDAO getUserDao() { <br>return userDao; <br>} <br>/** <br>* @param userDao 瑕佽緗殑 userDao銆?<br>*/ <br>public void setUserDao(IUserDAO userDao) { <br>this.userDao = userDao; <br>} <br>public User getUser(String userid) { <br>User user=userDao.getUser(Integer.valueOf(userid)); <br>if(user==null){ <br>log.warn(" user id "+userid+" not found in database"); <br>} <br>if(log.isDebugEnabled()){ <br>log.debug("get a user with id "+userid); <br>} <br>return user; <br>} <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.service.IUserManager#getUsers() <br>*/ <br>public List getUsers() { <br>// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴 <br>return userDao.getUsers(); <br>} <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.service.IUserManager#saveUser(com.jandar.model.User) <br>*/ <br>public User saveUser(User user) { <br>// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴 <br>userDao.saveUser(user); <br>return user; <br>} <br>/* 錛堥潪 Javadoc錛?<br>* @see com.jandar.service.IUserManager#removeUser(java.lang.String) <br>*/ <br>public void removeUser(String userid) { <br>// TODO 鑷姩鐢熸垚鏂規硶瀛樻牴 <br>userDao.removeUser(Integer.valueOf(userid)); <br>} <br>} <br>UserManager.java閫氳繃璁塊棶dao鎺ュ彛瀹炵幇涓氬姟閫昏緫鍜屾暟鎹簱鎿嶄綔銆傚悓鏃惰綾諱腑鎻愪緵浜唖et鏂規硶錛岃繍鐢ㄤ簡Spring鐨勪緷璧栨敞鍏ユ満鍒躲備絾灝氭湭浣跨敤spring鐨凙OP鍜屽0鏄庝簨鍔°?<br>閰嶇疆applicationContext.xml <br>鍦╓EB-INF 涓嬫柊寤篴pplicationContext.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.tkk7.com/topquan/aggbug/62670.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.tkk7.com/topquan/" target="_blank">topquan</a> 2006-08-09 23:14 <a href="http://www.tkk7.com/topquan/articles/62670.html#Feedback" target="_blank" style="text-decoration:none;">鍙戣〃璇勮</a></div>]]></description></item><item><title>榪涘叆 Spring MVChttp://www.tkk7.com/topquan/articles/62658.htmltopquantopquanWed, 09 Aug 2006 14:26:00 GMThttp://www.tkk7.com/topquan/articles/62658.htmlhttp://www.tkk7.com/topquan/comments/62658.htmlhttp://www.tkk7.com/topquan/articles/62658.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/62658.htmlhttp://www.tkk7.com/topquan/services/trackbacks/62658.htmlSpring MVC 妗嗘灦

銆銆Spring 妗嗘灦鎻愪緵浜嗘瀯寤?Web 搴旂敤紼嬪簭鐨勫叏鍔熻兘 MVC 妯″潡銆備嬌鐢?Spring 鍙彃鍏ョ殑 MVC 鏋舵瀯錛屽彲浠ラ夋嫨鏄嬌鐢ㄥ唴緗殑 Spring Web 妗嗘灦榪樻槸 Struts 榪欐牱鐨?Web 妗嗘灦銆傞氳繃絳栫暐鎺ュ彛錛孲pring 妗嗘灦鏄珮搴﹀彲閰嶇疆鐨勶紝鑰屼笖鍖呭惈澶氱瑙嗗浘鎶鏈紝渚嬪 JavaServer Pages錛圝SP錛夋妧鏈乂elocity銆乀iles銆乮Text 鍜?POI銆係pring MVC 妗嗘灦騫朵笉鐭ラ亾浣跨敤鐨勮鍥撅紝鎵浠ヤ笉浼氬己榪偍鍙嬌鐢?JSP 鎶鏈係pring MVC 鍒嗙浜嗘帶鍒跺櫒銆佹ā鍨嬪璞°佸垎媧懼櫒浠ュ強澶勭悊紼嬪簭瀵硅薄鐨勮鑹詫紝榪欑鍒嗙璁╁畠浠洿瀹規槗榪涜瀹氬埗銆?/p>

銆銆Spring 鐨?Web MVC 妗嗘灦鏄洿緇?DispatcherServlet 璁捐鐨勶紝瀹冩妸璇鋒眰鍒嗘淳緇欏鐞嗙▼搴忥紝鍚屾椂甯︽湁鍙厤緗殑澶勭悊紼嬪簭鏄犲皠銆佽鍥捐В鏋愩佹湰鍦拌璦銆佷富棰樿В鏋愪互鍙婁笂杞芥枃浠舵敮鎸併傞粯璁ょ殑澶勭悊紼嬪簭鏄潪甯哥畝鍗曠殑 Controller 鎺ュ彛錛屽彧鏈変竴涓柟娉?ModelAndView handleRequest(request, response)銆係pring 鎻愪緵浜嗕竴涓帶鍒跺櫒灞傛緇撴瀯錛屽彲浠ユ淳鐢熷瓙綾匯傚鏋滃簲鐢ㄧ▼搴忛渶瑕佸鐞嗙敤鎴瘋緭鍏ヨ〃鍗曪紝閭d箞鍙互緇ф壙 AbstractFormController銆傚鏋滈渶瑕佹妸澶氶〉杈撳叆澶勭悊鍒頒竴涓〃鍗曪紝閭d箞鍙互緇ф壙 AbstractWizardFormController銆?/p>

銆銆紺轟緥搴旂敤紼嬪簭鏈夊姪浜庣洿瑙傚湴瀛︿範榪欎簺鐗規с傞摱琛屽簲鐢ㄧ▼搴忓厑璁哥敤鎴鋒绱粬浠殑甯愭埛淇℃伅銆傚湪鏋勫緩閾惰搴旂敤紼嬪簭鐨勮繃紼嬩腑錛屽彲浠ュ鍒板浣曢厤緗?Spring MVC 妗嗘灦鍜屽疄鐜版鏋剁殑瑙嗗浘灞傦紝瑙嗗浘灞傚寘鎷?JSTL 鏍囪錛堢敤浜庢樉紺鴻緭鍑虹殑鏁版嵁錛夊拰JavaServer Pages 鎶鏈?/p>

銆銆閰嶇疆 Spring MVC

銆銆瑕佸紑濮嬫瀯寤虹ず渚嬪簲鐢ㄧ▼搴忥紝璇烽厤緗?Spring MVC 鐨?DispatcherServlet銆傝鍦?web.xml 鏂囦歡涓敞鍐屾墍鏈夐厤緗傛竻鍗?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 鏂囦歡瑁呭叆 Spring 搴旂敤紼嬪簭涓婁笅鏂囷紝XML 鏂囦歡鐨勫悕縐版槸 servlet 鐨勫悕縐板悗闈㈠姞涓?-servlet 銆傚湪榪欎釜紺轟緥涓紝DispatcherServlet 浼氫粠 sampleBankingServlet-servlet.xml 鏂囦歡瑁呭叆搴旂敤紼嬪簭涓婁笅鏂囥?

銆銆閰嶇疆搴旂敤紼嬪簭鐨?URL

銆銆涓嬩竴姝ユ槸閰嶇疆鎯寵 sampleBankingServlet 澶勭悊鐨?URL銆傚悓鏍鳳紝榪樻槸瑕佸湪 web.xml 涓敞鍐屾墍鏈夎繖浜涗俊鎭?/p>

娓呭崟 2. 閰嶇疆鎯寵澶勭悊鐨?URL

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

銆銆瑁呭叆閰嶇疆鏂囦歡

銆銆涓嬮潰錛岃鍏ラ厤緗枃浠躲備負浜嗗仛鍒拌繖鐐癸紝璇蜂負 Servlet 2.3 瑙勮寖娉ㄥ唽 ContextLoaderListener 鎴栦負 Servlet 2.2 鍙婁互涓嬬殑瀹瑰櫒娉ㄥ唽 ContextLoaderServlet銆備負浜嗕繚闅滃悗鍚戝吋瀹規э紝璇風敤 ContextLoaderServlet銆傚湪鍚姩 Web 搴旂敤紼嬪簭鏃訛紝ContextLoaderServlet 浼氳鍏?Spring 閰嶇疆鏂囦歡銆傛竻鍗?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 閰嶇疆鏂囦歡錛屽涓嬮潰鐨?servlet 涓婁笅鏂囨墍紺恒?/p>

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

銆銆sampleBanking-services.xml 鏂囦歡浠h〃紺轟緥閾惰搴旂敤紼嬪簭鏈嶅姟鐨勯厤緗拰 bean 閰嶇疆銆傚鏋滄兂瑁呭叆澶氫釜閰嶇疆鏂囦歡錛屽彲浠ュ湪 <param-value> 鏍囪涓敤閫楀彿浣滃垎闅旂銆?/p>

銆銆Spring MVC 紺轟緥

銆銆紺轟緥閾惰搴旂敤紼嬪簭鍏佽鐢ㄦ埛鏍規嵁鎯熶竴鐨?ID 鍜屽彛浠ゆ煡鐪嬪笎鎴蜂俊鎭傝櫧鐒?Spring MVC 鎻愪緵浜嗗叾浠栭夐」錛屼絾鏄垜灝嗛噰鐢?JSP 鎶鏈綔涓鴻鍥鵑〉闈€傝繖涓畝鍗曠殑搴旂敤紼嬪簭鍖呭惈涓涓鍥鵑〉鐢ㄤ簬鐢ㄦ埛杈撳叆錛圛D 鍜屽彛浠わ級錛屽彟涓欏墊樉紺虹敤鎴風殑甯愭埛淇℃伅銆?/p>

銆銆鎴戜粠 LoginBankController 寮濮嬶紝瀹冩墿灞曚簡 Spring MVC 鐨?SimpleFormController銆係impleFormContoller 鎻愪緵浜嗘樉紺轟粠 HTTP GET 璇鋒眰鎺ユ敹鍒扮殑琛ㄥ崟鐨勫姛鑳斤紝浠ュ強澶勭悊浠?HTTP POST 鎺ユ敹鍒扮殑鐩稿悓琛ㄥ崟鏁版嵁鐨勫姛鑳姐侺oginBankController 鐢?AuthenticationService 鍜?AccountServices 鏈嶅姟榪涜楠岃瘉錛屽茍鎵ц甯愭埛媧誨姩銆?#8220; 閰嶇疆瑙嗗浘灞炴?”涓鑺備腑鐨勬竻鍗?5 鎻忚堪浜嗗浣曟妸 AuthenticationService 鍜?AccountServices 榪炴帴鍒?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>

銆銆涓嬮潰錛屽繀欏繪敞鍐屽湪鎺ユ敹鍒?HTTP GET 璇鋒眰鏃舵樉紺虹殑欏甸潰銆傚湪 Spring 閰嶇疆涓敤 formView 灞炴ф敞鍐岃繖涓〉闈紝濡傛竻鍗?5 鎵紺恒俿ucessView 灞炴т唬琛ㄨ〃鍗曟暟鎹彁浜よ屼笖 doSubmitAction() 鏂規硶涓殑閫昏緫鎴愬姛鎵ц涔嬪悗鏄劇ず鐨勯〉闈€俧ormView 鍜?sucessView 灞炴ч兘浠h〃琚畾涔夌殑瑙嗗浘鐨勯昏緫鍚嶇О錛岄昏緫鍚嶇О鏄犲皠鍒板疄闄呯殑瑙嗗浘欏甸潰銆?/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 欏甸潰璁塊棶 loginCommand bean錛岃繖涓〉闈㈡槸搴旂敤紼嬪簭鐨勭櫥褰曢〉闈€備竴鏃︾敤鎴鋒彁浜や簡鐧誨綍欏甸潰錛屽簲鐢ㄧ▼搴忓氨鍙互浠?LoginBankController 鐨?onSubmit() 鏂規硶涓殑鍛戒護瀵硅薄媯绱㈠嚭琛ㄥ崟鏁版嵁銆?/p>

銆銆瑙嗗浘瑙f瀽鍣?/strong>

銆銆Spring MVC 鐨?瑙嗗浘瑙f瀽鍣?鎶婃瘡涓昏緫鍚嶇О瑙f瀽鎴愬疄闄呯殑璧勬簮錛屽嵆鍖呭惈甯愭埛淇℃伅鐨?JSP 鏂囦歡銆傛垜鐢ㄧ殑鏄?Spring 鐨?InternalResourceViewResolver錛屽 娓呭崟 6 鎵紺恒?/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 鏍囪錛屾墍浠ョ敤鎴風殑鐧誨綍鍚嶇О瑙f瀽鎴愯祫婧?/jsp/login.jsp錛岃?viewClass 鎴愪負 JstlView銆?/p>

銆銆楠岃瘉鍜屽笎鎴鋒湇鍔?/strong>

銆銆灝卞儚鍓嶉潰鎻愬埌鐨勶紝LoginBankController 鍐呴儴榪炴帴浜?Spring 鐨?AccountServices 鍜?AuthenticationService銆侫uthenticationService 綾誨鐞嗛摱琛屽簲鐢ㄧ▼搴忕殑楠岃瘉銆侫ccountServices 綾誨鐞嗗吀鍨嬬殑閾惰鏈嶅姟錛屼緥濡傛煡鎵句氦鏄撳拰鐢墊眹銆傛竻鍗?7 鏄劇ず浜嗛摱琛屽簲鐢ㄧ▼搴忕殑楠岃瘉鍜屽笎鎴鋒湇鍔$殑閰嶇疆銆?/p>

娓呭崟 7. 閰嶇疆楠岃瘉鍜屽笎鎴鋒湇鍔?/p>

<beans>

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

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

</beans>

銆銆浠ヤ笂鏈嶅姟鍦?sampleBanking-services.xml 涓敞鍐岋紝鐒跺悗瑁呭叆 web.xml 鏂囦歡涓紝灝卞儚 鍓嶉潰璁ㄨ鐨勯偅鏍楓傛帶鍒跺櫒鍜屾湇鍔¢厤緗ソ鍚庯紝榪欎釜綆鍗曠殑搴旂敤紼嬪簭灝卞畬鎴愪簡銆傜幇鍦ㄦ垜浠潵鐪嬬湅閮ㄧ講鍜屾祴璇曞畠鏃朵細鍙戠敓浠涔?

銆銆閮ㄧ講搴旂敤紼嬪簭

銆銆鎶婄ず渚嬪簲鐢ㄧ▼搴忛儴緗插湪 Tomcat servlet 瀹瑰櫒涓俆omcat 鏄?Java Servlet 鍜?Java ServerPagest 鎶鏈殑瀹樻柟鍙傝冨疄鐜頒腑浣跨敤鐨?servlet 瀹瑰櫒銆傚鏋滀互鍓嶆病榪欎箞鍋氳繃錛岃 涓嬭澆 jakarta-tomcat-5.0.28.exe 騫惰繍琛屽畠鎶?Tomcat 瀹夎鍒拌嚜宸卞枩嬈㈢殑浠諱綍浣嶇疆錛屼緥濡?c:\tomcat5.0銆?/p>

銆銆鎺ヤ笅鏉ワ紝涓嬭澆紺轟緥浠g爜 騫墮噴鏀懼埌椹卞姩鍣紙渚嬪 c:\ 錛変笂銆傚垱寤轟簡 Spring 欏圭洰鐨勬枃浠跺す涔嬪悗錛屾墦寮瀹冨茍鎶?spring-banking 瀛愭枃浠跺す鎷瘋礉鍒?c:\tomvat5.0\webapps銆俿pring-banking 鏂囦歡澶規槸涓涓?Web 妗f錛岄噷闈㈠寘鍚?Spring MVC 紺轟緥搴旂敤紼嬪簭銆俵ib 鏂囦歡澶瑰寘鍚簲鐢ㄧ▼搴忛渶瑕佺殑 Spring 妗嗘灦銆佷笌Spring 鐩稿叧鐨?MVC 搴撲互鍙?JSTL 鏍囪搴撳拰 jar 鏂囦歡銆?/p>

銆銆瑕佸惎鍔?Tomcat 鏈嶅姟鍣紝璇蜂嬌鐢ㄤ互涓嬪懡浠わ細

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

銆銆Tomcat 搴斿綋鍚姩騫墮儴緗?Spring MVC 紺轟緥搴旂敤紼嬪簭銆?/p>

銆銆嫻嬭瘯搴旂敤紼嬪簭

銆銆瑕佹祴璇曞簲鐢ㄧ▼搴忥紝璇鋒墦寮 Web 嫻忚鍣紝鎸囧悜 http://localhost:tomcatport/springbanking 騫剁敤 Tomcat 鏈嶅姟鍣ㄥ疄闄呰繍琛岀殑绔彛鏇挎崲 tomcatport銆傚簲褰撶湅鍒板浘 1 鎵紺虹殑鐧誨綍灞忓箷銆傝緭鍏ョ敤鎴?ID “admin”鍜屽彛浠?#8220;password”錛屽茍鎸変笅鐧誨綍鎸夐挳銆傚叾浠栫敤鎴?ID 鎴栧彛浠や細閫犳垚鏉ヨ嚜楠岃瘉鏈嶅姟鐨勯敊璇?/p>


鍥?1. Spring MVC 紺轟緥鐧誨綍灞忓箷

銆銆鐧誨綍鎴愬姛涔嬪悗錛屼細鐪嬪埌鍥?2 鎵紺虹殑甯愭埛緇嗚妭欏甸潰銆?/p>


鍥?2. Spring MVC 紺轟緥甯愭埛緇嗚妭欏甸潰
Spring MVC妗嗘灦鐨勯珮綰ч厤緗?br>http://dev2dev.bea.com.cn/techdoc/2006068810.html



topquan 2006-08-09 22:26 鍙戣〃璇勮
]]>
涓涓猄pring紼嬪簭 http://www.tkk7.com/topquan/articles/61889.htmltopquantopquanFri, 04 Aug 2006 16:56:00 GMThttp://www.tkk7.com/topquan/articles/61889.htmlhttp://www.tkk7.com/topquan/comments/61889.htmlhttp://www.tkk7.com/topquan/articles/61889.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/61889.htmlhttp://www.tkk7.com/topquan/services/trackbacks/61889.htmlSpring閫氳繃XML鏂囦歡錛屽畬鎴恇ean閰嶇疆鍜宐ean闂翠緷璧栧叧緋葷殑娉ㄥ叆銆?br>
1.闇瑕佺敤鍒扮殑鍖咃細
spring-core.jar
spring-beans.jar
spring-context.jar
commons-logging.jar

2.Bean鏂囦歡
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;
    }
}

閰嶇疆鏂囦歡
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.嫻嬭瘯紼嬪簭
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.tkk7.com/topquan/articles/61887.htmltopquantopquanFri, 04 Aug 2006 16:55:00 GMThttp://www.tkk7.com/topquan/articles/61887.htmlhttp://www.tkk7.com/topquan/comments/61887.htmlhttp://www.tkk7.com/topquan/articles/61887.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/61887.htmlhttp://www.tkk7.com/topquan/services/trackbacks/61887.html闃呰鍏ㄦ枃

topquan 2006-08-05 00:55 鍙戣〃璇勮
]]>
鍦╩yeclipse涓嬫暣鍚坰pring鍜宧ibernate http://www.tkk7.com/topquan/articles/61877.htmltopquantopquanFri, 04 Aug 2006 16:28:00 GMThttp://www.tkk7.com/topquan/articles/61877.htmlhttp://www.tkk7.com/topquan/comments/61877.htmlhttp://www.tkk7.com/topquan/articles/61877.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/61877.htmlhttp://www.tkk7.com/topquan/services/trackbacks/61877.html寮曠敤  http://www.tkk7.com/dyerac/archive/2006/08/04/61805.html



topquan 2006-08-05 00:28 鍙戣〃璇勮
]]>
Struts+Spring+Hibernate緇勫悎浣跨敤http://www.tkk7.com/topquan/articles/45101.htmltopquantopquanMon, 08 May 2006 14:46:00 GMThttp://www.tkk7.com/topquan/articles/45101.htmlhttp://www.tkk7.com/topquan/comments/45101.htmlhttp://www.tkk7.com/topquan/articles/45101.html#Feedback0http://www.tkk7.com/topquan/comments/commentRss/45101.htmlhttp://www.tkk7.com/topquan/services/trackbacks/45101.html闃呰鍏ㄦ枃

topquan 2006-05-08 22:46 鍙戣〃璇勮
]]>
主站蜘蛛池模板: ass亚洲**毛茸茸pics| 性色av无码免费一区二区三区| 亚洲一久久久久久久久| 亚洲开心婷婷中文字幕| 国产成人无码免费视频97 | 黄瓜视频高清在线看免费下载| 中文在线免费观看| 精品一区二区三区免费毛片| 91亚洲精品麻豆| 久久水蜜桃亚洲av无码精品麻豆| 中文字幕无码精品亚洲资源网| 最近免费中文字幕视频高清在线看| 特级精品毛片免费观看| 国产精品免费在线播放| 极品美女一级毛片免费| 亚洲变态另类一区二区三区| 亚洲一区二区三区四区视频| 亚洲视频一区在线播放| 亚洲人成网亚洲欧洲无码久久| 亚洲欧洲中文日韩av乱码| 日本免费电影一区| 夜夜嘿视频免费看| 成人免费在线观看网站| 久久这里只有精品国产免费10| 亚洲一区免费在线观看| 18女人腿打开无遮掩免费| 久久久久久国产精品免费免费男同 | 久久av免费天堂小草播放| 大片免费观看92在线视频线视频 | 成年女人18级毛片毛片免费 | 亚洲综合一区二区精品久久| 亚洲最大福利视频网站| 亚洲精品成人av在线| 久久久久久久久亚洲| 久久久久亚洲AV片无码| 亚洲AV乱码久久精品蜜桃| 亚洲电影国产一区| 91亚洲导航深夜福利| 亚洲成av人片在线看片| 亚洲av片不卡无码久久| 最新国产成人亚洲精品影院|