Eclipse+Spring从头学到脚之5-入门篇B

10 篇文章 0 订阅
5 篇文章 0 订阅

接上回书,我们继续~~~

首先,添加一个表单,来实现增加产品价格的功能,这里是通过一个新的jsp文件来实现的,在WebContent/ WEB-INF/ jsp下新建一个priceincrease.jsp文件,内容如下

  1. <%@ include file="/WEB-INF/jsp/include.jsp" %>
  2. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
  3. <html>
  4. <head>
  5.   <title><fmt:message key="title"/></title>
  6.   <style>
  7.     .error { color: red; }
  8.   </style>  
  9. </head>
  10. <body>
  11. <h1><fmt:message key="priceincrease.heading"/></h1>
  12. <form:form method="post" commandName="priceIncrease">
  13.   <table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
  14.     <tr>
  15.       <td align="right" width="20%">Increase (%):</td>
  16.         <td width="20%">
  17.           <form:input path="percentage"/>
  18.         </td>
  19.         <td width="60%">
  20.           <form:errors path="percentage" cssClass="error"/>
  21.         </td>
  22.     </tr>
  23.   </table>
  24.   <br>
  25.   <input type="submit" align="center" value="Execute">
  26. </form:form>
  27. <a href="<c:url value="hello.htm"/>">Home</a>
  28. </body>
  29. </html>

因为里面用到了spring的标签,需要引入一个spring的tld标签文件,具体引入方法如下

在WEB-INF下新建一个tld的文件夹,然后把D:/StudySpring/spring-framework-2.5.5/dist/resources/ spring-form.tld文件拷贝过来。

接下来,为了让程序知道这个引用,需要在web.xml里追加一个 ,修改后的web.xml内容如下


  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.4"
  3.          xmlns="http://java.sun.com/xml/ns/j2ee"
  4.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5.          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
  6.          http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
  7.   <servlet>
  8.     <servlet-name>springapp</servlet-name>
  9.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10.     <load-on-startup>1</load-on-startup>
  11.   </servlet>
  12.   <servlet-mapping>
  13.     <servlet-name>springapp</servlet-name>
  14.     <url-pattern>*.htm</url-pattern>
  15.   </servlet-mapping>
  16.   <welcome-file-list>
  17.     <welcome-file>
  18.       index.jsp
  19.     </welcome-file>
  20.   </welcome-file-list>
  21.   <jsp-config>
  22.     <taglib>
  23.       <taglib-uri>/spring</taglib-uri>
  24.       <taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
  25.     </taglib>
  26.   </jsp-config>
  27. </web-app>

然后来实现增加价格的业务逻辑类,即在springapp.service包下新建一个PriceIncrease.java类,内容如下


  1. package springapp.service;
  2. import org.apache.commons.logging.Log;
  3. import org.apache.commons.logging.LogFactory;
  4. public class PriceIncrease {
  5.     /** Logger for this class and subclasses */
  6.     protected final Log logger = LogFactory.getLog(getClass());
  7.     private int percentage;
  8.     public void setPercentage(int i) {
  9.         percentage = i;
  10.         logger.info("Percentage set to " + i);
  11.     }
  12.     public int getPercentage() {
  13.         return percentage;
  14.     }
  15. }

然后在加点难度,给我们的增加价格业务来个验证,或者说加一些限制条件,只有符合我们的条件,才可以增加价格,这个条件是

· The maximum increase is limited to 50%.

· The minimum increase must be greater than 0%

因此增加一个验证的逻辑类,即在springapp.service包下新建一个PriceIncreaseValidator.java类,内容如下


  1. package springapp.service;
  2. import org.springframework.validation.Validator;
  3. import org.springframework.validation.Errors;
  4. import org.apache.commons.logging.Log;
  5. import org.apache.commons.logging.LogFactory;
  6. public class PriceIncreaseValidator implements Validator {
  7.     private int DEFAULT_MIN_PERCENTAGE = 0;
  8.     private int DEFAULT_MAX_PERCENTAGE = 50;
  9.     private int minPercentage = DEFAULT_MIN_PERCENTAGE;
  10.     private int maxPercentage = DEFAULT_MAX_PERCENTAGE;
  11.     /** Logger for this class and subclasses */
  12.     protected final Log logger = LogFactory.getLog(getClass());
  13.     public boolean supports(Class clazz) {
  14.         return PriceIncrease.class.equals(clazz);
  15.     }
  16.     public void validate(Object obj, Errors errors) {
  17.         PriceIncrease pi = (PriceIncrease) obj;
  18.         if (pi == null) {
  19.             errors.rejectValue("percentage""error.not-specified"null"Value required.");
  20.         }
  21.         else {
  22.             logger.info("Validating with " + pi + ": " + pi.getPercentage());
  23.             if (pi.getPercentage() > maxPercentage) {
  24.                 errors.rejectValue("percentage""error.too-high",
  25.                     new Object[] {new Integer(maxPercentage)}, "Value too high.");
  26.             }
  27.             if (pi.getPercentage() <= minPercentage) {
  28.                 errors.rejectValue("percentage""error.too-low",
  29.                     new Object[] {new Integer(minPercentage)}, "Value too low.");
  30.             }
  31.         }
  32.     }
  33.     public void setMinPercentage(int i) {
  34.         minPercentage = i;
  35.     }
  36.     public int getMinPercentage() {
  37.         return minPercentage;
  38.     }
  39.     public void setMaxPercentage(int i) {
  40.         maxPercentage = i;
  41.     }
  42.     public int getMaxPercentage() {
  43.         return maxPercentage;
  44.     }
  45. }
接下来,要为这个增加价格的功能加一个控制器,这里要修改之前的springapp-servlet.xml,修改后内容如下

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans
  5.        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  6. <!-- the application context definition for the springapp DispatcherServlet -->
  7. <beans>
  8.     <bean id="productManager" class="springapp.service.SimpleProductManager">
  9.         <property name="products">
  10.             <list>
  11.                 <ref bean="product1"/>
  12.                 <ref bean="product2"/>
  13.                 <ref bean="product3"/>
  14.             </list>
  15.         </property>
  16.     </bean>
  17.     <bean id="product1" class="springapp.domain.Product">
  18.         <property name="description" value="Lamp"/>
  19.         <property name="price" value="5.75"/>
  20.     </bean>
  21.         
  22.     <bean id="product2" class="springapp.domain.Product">
  23.         <property name="description" value="Table"/>
  24.         <property name="price" value="75.25"/>
  25.     </bean>
  26.     <bean id="product3" class="springapp.domain.Product">
  27.         <property name="description" value="Chair"/>
  28.         <property name="price" value="22.79"/>
  29.     </bean>
  30.     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  31.         <property name="basename" value="messages"/>
  32.     </bean>
  33.     <bean name="/hello.htm" class="springapp.web.InventoryController">
  34.         <property name="productManager" ref="productManager"/>
  35.     </bean>
  36.     <bean name="/priceincrease.htm" class="springapp.web.PriceIncreaseFormController">
  37.         <property name="sessionForm" value="true"/>
  38.         <property name="commandName" value="priceIncrease"/>
  39.         <property name="commandClass" value="springapp.service.PriceIncrease"/>
  40.         <property name="validator">
  41.             <bean class="springapp.service.PriceIncreaseValidator"/>
  42.         </property>
  43.         <property name="formView" value="priceincrease"/>
  44.         <property name="successView" value="hello.htm"/>
  45.         <property name="productManager" ref="productManager"/>
  46.     </bean>
  47.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  48.         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  49.         <property name="prefix" value="/WEB-INF/jsp/"/>
  50.         <property name="suffix" value=".jsp"/>
  51.     </bean>
  52. </beans>

※大家一定要看下修改前后的变化哦!!!

接下来,在springapp.web包下面新建一个控制器PriceIncreaseFormController.java,来对应springapp-servlet.xml里的变化,程序内容如下


  1. package springapp.web;
  2. import org.springframework.web.servlet.mvc.SimpleFormController;
  3. import org.springframework.web.servlet.ModelAndView;
  4. import org.springframework.web.servlet.view.RedirectView;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServletRequest;
  7. import org.apache.commons.logging.Log;
  8. import org.apache.commons.logging.LogFactory;
  9. import springapp.service.ProductManager;
  10. import springapp.service.PriceIncrease;
  11. public class PriceIncreaseFormController extends SimpleFormController {
  12.     /** Logger for this class and subclasses */
  13.     protected final Log logger = LogFactory.getLog(getClass());
  14.     private ProductManager productManager;
  15.     public ModelAndView onSubmit(Object command)
  16.             throws ServletException {
  17.         int increase = ((PriceIncrease) command).getPercentage();
  18.         logger.info("Increasing prices by " + increase + "%.");
  19.         productManager.increasePrice(increase);
  20.         logger.info("returning from PriceIncreaseForm view to " + getSuccessView());
  21.         return new ModelAndView(new RedirectView(getSuccessView()));
  22.     }
  23.     protected Object formBackingObject(HttpServletRequest request) throws ServletException {
  24.         PriceIncrease priceIncrease = new PriceIncrease();
  25.         priceIncrease.setPercentage(20);
  26.         return priceIncrease;
  27.     }
  28.     public void setProductManager(ProductManager productManager) {
  29.         this.productManager = productManager;
  30.     }
  31.     public ProductManager getProductManager() {
  32.         return productManager;
  33.     }
  34. }

然后,修改一下之前用到过的messages.properties文件,增加一些消息内容,
修改后的内容如下

 

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

然后,修改一下'hello.jsp'文件,在里面增加一个超链接,
修改后的内容如下

 

  1. <%@ include file="/WEB-INF/jsp/include.jsp" %>
  2. <html>
  3.   <head><title><fmt:message key="title"/></title></head>
  4.   <body>
  5.     <h1><fmt:message key="heading"/></h1>
  6.     <p><fmt:message key="greeting"/> <c:out value="${model.now}"/></p>
  7.     <h3>Products</h3>
  8.     <c:forEach items="${model.products}" var="prod">
  9.       <c:out value="${prod.description}"/> <i>$<c:out value="${prod.price}"/></i><br><br>
  10.     </c:forEach>
  11.     <br>
  12.     <a href="<c:url value="priceincrease.htm"/>">Increase Prices</a>
  13.     <br>
  14.   </body>
  15. </html>

ok,到这里,就完成了本次的学习,可以启动来欣赏我们的劳动成果了。

运行后的首页面如下图所示
5-1

然后点击“Increase Prices”的超链接,得到下面的画面,即增加价格的功能页面
5-2

然后在“Increase”里输入60的话,会得到下面的错误提示画面(因为大于50的原故)
5-3

如果输入“0”,会得到下面的错误提示画面,因为0也是不允许的数据
5-4

如果输入0到50之间的数字,就会得到正确的结果,比如,输入30就会得到下面的结果画面
5-5

 

如果你也和我一样的话,今天的学习内容的动手部分就到此结束了。
个人感觉要跑起这些例子来是比较容易的,关键是要理解其中的原理,只有这样才能变成自己的东东。

重点总结

1:了解下spring-form.tld文件及如何使用这个文件的。

2:业务逻辑和验证逻辑是如何加入到系统中的,请一定要理解透彻。

3:错误信息的显示方法要了解并熟悉。

 

END

 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值