Eclipse+Spring从头学到脚之4-入门篇A

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

到今天我们已经进行了3次学习,打了一些基础,今天终于可以开始学习入门的知识了,那就开始入门吧,呵呵~~~
(之所以改成入门篇,是因为今天开始的内容比前面的内容稍微复杂一点,入门篇结束后,可以说spring的MVC框架的内容就可以基本了解,为日后的深入学习打下点点基础)

好,下面就开始今天的学习

还是在原有的项目spring001上修改,大家可以通过一次次的修改的内容,逐步体会一下spring的结构,而我越来越觉得spring的官方学习资料MVC-step-by-step的精妙所在了~~~

开始之前,请不要忘记备份下上次的成果~~

首先,改进一下上次的练习,修改对象是控制器HelloController.java,这里面把返回对象的路径都写成固定的了,不是很好的开发习惯,也造成了一种不必要的依赖关系,我们修改的方法如下,大家可以在修改后对照一下差别的地方。

Ok,把我们的HelloController.java用下面的内容替换

     
     
  1. package springapp.web;
  2. import org.springframework.web.servlet.mvc.Controller;
  3. import org.springframework.web.servlet.ModelAndView;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.commons.logging.Log;
  8. import org.apache.commons.logging.LogFactory;
  9. import java.io.IOException;
  10. import java.util.Date;
  11. public class HelloController implements Controller {
  12.     protected final Log logger = LogFactory.getLog(getClass());
  13.     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
  14.             throws ServletException, IOException {
  15.         String now = (new Date()).toString();
  16.         logger.info("Returning hello view with " + now);
  17.         return new ModelAndView("hello", "now", now);
  18.     }
  19. }
 既然这种依赖关系不存在于控制器中,那在哪里呢?肯定要有个地方指定,对吧,
答案是,在配置文件里设定,我们这里是体现在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.0.xsd">
  6.    
  7.     <!-- the application context definition for the springapp DispatcherServlet -->
  8.    
  9.     <bean name="/hello.htm" class="springapp.web.HelloController"/>
  10.    
  11.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  12.         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
  13.         <property name="prefix" value="/WEB-INF/jsp/"></property>
  14.         <property name="suffix" value=".jsp"></property>       
  15.     </bean>
  16.            
  17. </beans>

改造好后就可以开始我们今天的新内容了,大家可以通过运行一下自己的程序,
来验证一下,看到的画面应该和上次的一样。

 

下面就开始我们今天的主角,通过一个Inventory Management System(目录管理系统)来体会spring。

这个系统的业务逻辑如下图:
4-1

 

接下来,来添加我们的业务逻辑部分的程序文件,在springapp包下面建一个叫domain的包,
然后创建springapp/domain/Product.java类,内容如下


 

      
      
  1. package springapp.domain;
  2. import java.io.Serializable;
  3. public class Product implements Serializable {
  4.     private String description;
  5.     private Double price;
  6.    
  7.     public String getDescription() {
  8.         return description;
  9.     }
  10.    
  11.     public void setDescription(String description) {
  12.         this.description = description;
  13.     }
  14.    
  15.     public Double getPrice() {
  16.         return price;
  17.     }
  18.    
  19.     public void setPrice(Double price) {
  20.         this.price = price;
  21.     }
  22.    
  23.     public String toString() {
  24.         StringBuffer buffer = new StringBuffer();
  25.         buffer.append("Description: " + description + ";");
  26.         buffer.append("Price: " + price);
  27.         return buffer.toString();
  28.     }
  29. }

然后,再创建一个service包,在这个包里创建我们的
springapp/service/ProductManager
.java,
它是一个接口类,内容如下:


      
      
  1. package springapp.service;
  2. import java.io.Serializable;
  3. import java.util.List;
  4. import springapp.domain.Product;
  5. public interface ProductManager extends Serializable{
  6.     public void increasePrice(int percentage);
  7.    
  8.     public List<Product> getProducts();
  9.    
  10. }

 

 

然后,创建实现这个接口类的springapp/service/SimpleProductManager.java,内容如下

 

      
      
  1. package springapp.service;
  2. import java.util.List;
  3. import springapp.domain.Product;
  4. public class SimpleProductManager implements ProductManager {
  5.     private List<Product> products;
  6.    
  7.     public List<Product> getProducts() {
  8.         return products;
  9.     }
  10.     public void increasePrice(int percentage) {
  11.         if (products != null) {
  12.             for (Product product : products) {
  13.                 double newPrice = product.getPrice().doubleValue() *
  14.                                     (100 + percentage)/100;
  15.                 product.setPrice(newPrice);
  16.             }
  17.         }
  18.     }
  19.    
  20.     public void setProducts(List<Product> products) {
  21.         this.products = products;
  22.     }
  23.    
  24. }
  
  

到这,创建好的类的结构,如下图所示
4-2

接下来,要新增加一个控制器,名叫InventoryController.java
位置在springapp/web/下,内容如下

     
     
  1. package springapp.web;
  2. import org.springframework.web.servlet.mvc.Controller;
  3. import org.springframework.web.servlet.ModelAndView;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.IOException;
  8. import java.util.Map;
  9. import java.util.HashMap;
  10. import org.apache.commons.logging.Log;
  11. import org.apache.commons.logging.LogFactory;
  12. import springapp.service.ProductManager;
  13. public class InventoryController implements Controller {
  14.     protected final Log logger = LogFactory.getLog(getClass());
  15.     private ProductManager productManager;
  16.     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
  17.             throws ServletException, IOException {
  18.         String now = (new java.util.Date()).toString();
  19.         logger.info("returning hello view with " + now);
  20.         Map<String, Object> myModel = new HashMap<String, Object>();
  21.         myModel.put("now", now);
  22.         myModel.put("products", this.productManager.getProducts());
  23.         return new ModelAndView("hello", "model", myModel);
  24.     }
  25.     public void setProductManager(ProductManager productManager) {
  26.         this.productManager = productManager;
  27.     }
  28. }

 

然后,修改我们的view,即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.   </body>
  12. </html>

到目前为止还没有引入数据库,所以我们只能在配置文件里造一些测试数据,这个配置文件就是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.     <bean id="productManager" class="springapp.service.SimpleProductManager">
  8.         <property name="products">
  9.             <list>
  10.                 <ref bean="product1"/>
  11.                 <ref bean="product2"/>
  12.                 <ref bean="product3"/>
  13.             </list>
  14.         </property>
  15.     </bean>
  16.     <bean id="product1" class="springapp.domain.Product">
  17.         <property name="description" value="Lamp"/>
  18.         <property name="price" value="5.75"/>
  19.     </bean>
  20.        
  21.     <bean id="product2" class="springapp.domain.Product">
  22.         <property name="description" value="Table"/>
  23.         <property name="price" value="75.25"/>
  24.     </bean>
  25.     <bean id="product3" class="springapp.domain.Product">
  26.         <property name="description" value="Chair"/>
  27.         <property name="price" value="22.79"/>
  28.     </bean>
  29.     <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
  30.         <property name="basename" value="messages"/>
  31.     </bean>
  32.     <bean name="/hello.htm" class="springapp.web.InventoryController">
  33.         <property name="productManager" ref="productManager"/>
  34.     </bean>
  35.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  36.         <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  37.         <property name="prefix" value="/WEB-INF/jsp/"/>
  38.         <property name="suffix" value=".jsp"/>
  39.     </bean>
  40. </beans>

 

接下来,添加我们的message内容文件,这个文件在hello.jsp里面用到,
创建的路径是我们的src下面,名字叫messages.properties,文件内容如下


  1. title=SpringApp
  2. heading=Hello :: SpringApp
  3. greeting=Greetings, it is now

OK,今天的内容就到这里,可以运行一下,看看我们的成果,如果没有问题,应该能看到下面的画面(运行方法见前面的教程)
4-3

 

或者在IE的地址栏里输入http://localhost:8080/spring001,得到下面的结果画面
4-4

 

 

重点总结

1:注意下控制器变了一个,原来的不使用了。

2:hello.jsp里如何使用message.properties内容,看一下springapp-servlet.xml就会明白了。

3:创建了service层,请体会下意义。

 

END


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值