Web - shenliuyang/development GitHub Wiki
在appdot的工程中,选用了SpringMVC 3作为Web层的实现,选用它的原因很多,此处不再详细论述,本质上还是认为它足够简单纯朴。
本章节主要讲述怎样编写Controller和Web页面,当然是以我们要求的方式。
测试Spring MVC的程序是很容易的,Spring的Controller是一种轻量化设计,并且Spring也提供了Mock库来方便测试,例如Servlet API的Mock实现。
在src/test/java/**/web目录下,创建PersonControllerTest.java类
package org.appdot.tutorial.web;
import org.appdot.test.spring.BaseControllerTestCase;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class PersonControllerTest extends BaseControllerTestCase {
@Autowired
private PersonController controller;
@Autowired
private PersonManager personManager;
@Test
public void testList() {
Model model = new RedirectAttributesModelMap();
personController.list(model);
Assert.assertNotNull(model.asMap().get("personList"));
Assert.assertFalse(model.asMap().isEmpty());
}
@Test
public void testSavePerson() {
Person person = personManager.get(-2L);
person.setFirstName("changed");
personController.save(person, new RedirectAttributesModelMap());
}
}
在src/main/java/**/web目录下创建PersonController.java类
@Controller
@RequestMapping(value = "/persons")
public class PersonController {
private PersonManager personManager;
@RequestMapping(value = { "list", "" })
public String list(Model model) {
List<Person> persons = personManager.getAll();
model.addAttribute("personList", persons);
return "persons";
}
@RequestMapping(value = "save")
public String save(Person person, RedirectAttributes redirectAttributes) {
personManager.save(person);
redirectAttributes.addFlashAttribute("message", "创建新人类" + person.getLoginName() + "成功");
return "redirect:/persons/";
}
@Autowired
@Qualifier("personManager")
public void setPersonManager(PersonManager personManager) {
this.personManager = personManager;
}
}
运行PersonControllerTest “mvn test -Dtest=PersonControllerTest”
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<head>
<title>人类管理</title>
<meta name="menu" content="SystemManagementMenu" />
</head>
<c:if test="${not empty message}">
<div id="message" class="alert alert-success">
<button data-dismiss="alert" class="close">×</button>
${message}
</div>
</c:if>
<table id="contentTable" class="table table-striped table-bordered table-condensed">
<caption>用户列表</caption>
<thead>
<tr>
<th>名字</th>
<th>姓氏</th>
</tr>
</thead>
<tbody>
<c:forEach items="${personList}" var="person">
<tr>
<td><a href="${ctx}/persons/update/${person.id}" id="editLink-${person.firstName}">${person.firstName}</a></td>
<td>${person.lastName}</td>
<td><a href="${ctx}/persons/delete/${person.id}">删除</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<div>
<a class="btn" href="${ctx}/persons/create">创建人类</a>
</div>
运行 mvn jetty:run 浏览器打开http://localhost:8080/persons