2、开发和配置应用程序
(13)改进index.jsp
l 我们要在JSP中使用JSTL,所以将lib/j2ee/jstl.jar和lib/jakarta-taglibs/standard.jar导入到springapp/WEB-INF/lib目录下
l 创建include.jsp包含对Taglibs的引用,以便其它JSP包含引用:
<%@ page session="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
l 为了这些文件不让用户直接访问,可以将文件放在/WEB-INF目录下,这里将文件放在/WEB-INF/jsp目录下
l 修改index.jsp,使用<c:redirect>重定向到控制器
<%@ include file="/WEB-INF/jsp/include.jsp" %>
<%-- Redirected because we can't set the welcome page to a virtual URL. --%>
<c:redirect url="/hello.htm"/>
(14)改进视图和控制器
l 和include.jsp一样,hello.jsp也是不能直接访问的,所以将hello.jsp移动到/WEB-INF/jsp目录下
l 在hello.jsp中,我们增加当前日期和事件的输出,这是从后面讲到的Model中获取的
<%@ include file="/WEB-INF/jsp/include.jsp" %>
<html>
<head><title>Hello :: Spring Application</title></head>
<body>
<h1>Hello - Spring Application</h1>
<p>Greetings, it is now <c:out value="${now}"/>
</p>
</body>
</html>
l 由于hello.jsp的路径改变,并且需要Model数据,因此需要修改控制器来调整输出视图的路径并提供Model数据
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SpringappController implements Controller {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
return new ModelAndView("/WEB-INF/jsp/hello.jsp", "now", now);
}
}
l 在浏览器中输入http://localhost:8888/springapp,就会显示带当前日期和时间的欢迎页面
(15)减少视图和控制器的耦合
l 上面的例子中视图和控制器存在依赖关系。我们的想法是使用逻辑名字来映射视图。这就允许在改变视图(如名字、路径)时不需要修改控制器。
l 简单的映射就是使用InternalResourceViewResolver设置前缀和后缀
l 修改springapp-servlet.xml,增加viewResolver条目
<?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="SpringappController"/>
<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>
l 这样就可以在控制器中去掉视图的前缀和后缀
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SpringappController implements Controller {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
return new ModelAndView("hello", "now", now);
}
}
(16)增加业务逻辑类
l Product类提供业务数据,ProductManager类用来管理Product(即业务数据);它们都实现为JavaBean
package bus;
import java.io.Serializable;
public class Product implements Serializable {
private String description;
private Double price;
public void setDescription(String s) {
description = s;
}
public String getDescription() {
return description;
}
public void setPrice(Double d) {
price = d;
}
public Double getPrice() {
return price;
}
}
package bus;
import java.io.Serializable;
import java.util.List;
public class ProductManager implements Serializable {
private List products;
public void setProducts(List p) {
products = p;
}
public List getProducts() {
return products;
}
}
l 为了将Web表示和业务逻辑分离,这些类和控制器放在不同的包中bus和web;注意将SpringappController移动到web包中
l 修改SpringappController,保存ProductManager的引用,以便向视图传递业务数据;由于需要传递多个对象,使用Map结构
package web;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
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.ProductManager;
public class SpringappController implements Controller {
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
private ProductManager prodMan;
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
Map myModel = new HashMap();
myModel.put("now", now);
myModel.put("products", getProductManager().getProducts());
return new ModelAndView("hello", "model", myModel);
}
public void setProductManager(ProductManager pm) {
prodMan = pm;
}
public ProductManager getProductManager() {
return prodMan;
}
}
(17)修改视图显示业务数据,同时提供消息束支持
l 使用<c:forEach>遍历显示业务数据,使用<fmt:message>从后面介绍的的消息文件中获得消息显示
<%@ 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>
</body>
</html>
(18)增加测试数据以自动组装业务对象
l 上面的例子还没有增加从数据库来装载业务对象的功能代码,所以使用Spring的Bean和应用程序context功能来实例化,这需要在springapp-servlet.xml中加一些Bean条目
l 增加messageSource指定消息资源束保存的文件messages.properties
<?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>
<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>
</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>
(19)增加消息束
l 在springapp/WEB-INF/classes目录下创建messages.properties文件,注意key值与<fmt:message>中引用的一致
title=SpringApp
heading=Hello :: SpringApp
greeting=Greetings, it is now
l 重新部署,在浏览器中输入http://localhost:8888/springapp,就会显示带当前日期和时间以及业务数据的页面