Spring MVC之用户管理
余志勇
SINA微博:http://weibo.com/web8i
QQ微博:http://t.qq.com/webiiiiiiii
博客:http://blog.youkuaiyun.com/web8i
本文在上篇【Spring MVC之HelloWorld】的基础上开发一个简单的CRUD应用,为了减少非Spring MVC相关知识,本应用没有使用数据库而是直接把数据存入内存中。当然这也不是本文的重点。
目标:如下图完成用户的增删改查功能。
工具:MyEclipse 8.6(也可以选择任何其它IDE工具,本系列文章尽量不使用工具特有的东东)
主要任务:
工程:
userdemo Web项目(新增)
视图:
index.jsp(新增)
user_add.jsp(新增)
user_edit.jsp(新增)
user_list.jsp(新增)
控制器:
UserController.java(新增)重点
模型:
UserService.java
User.java
配置:
web.xml(如上文)
spring_servlet.xml(如上文)
项目结构如下图:
参考代码:
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<a href="user/list.html">UserManager</a> <br>
</body>
</html>
user_list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<h2>User Manager</h2><hr />
<table border="1" width="80%">
<tr>
<td>ID</td>
<td>User Name</td>
<td>Password</td>
<td>Email</td>
<td>COMMAND</td>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.userName}</td>
<td>${user.password}</td>
<td>${user.email}</td>
<td>
<a href="${user.id}/edit.html">Edit</a>|
<a href="add.html">Add</a>|
<a href="${user.id}/remove.html">Remove</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
user_add.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<h2>User Manager</h2>
<form:form method="post" action="save.html">
<table>
<tr>
<td><form:label path="id">ID</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td><form:label path="userName">UserName</form:label></td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add User"/>
</td>
</tr>
</table>
</form:form>
<a href="list.html">Go</a>
</body>
</html>
user_edit.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<body>
<h2>User Manager</h2>
<form:form method="post" action="update.html">
<table>
<form:hidden path="id" />
<tr>
<td><form:label path="userName">UserName</form:label></td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Update User"/>
</td>
</tr>
</table>
</form:form>
<a href="list.html">Go</a>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>HelloWorld</display-name>
<servlet>
<display-name>spring</display-name>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring_servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 自动扫描的包名 -->
<context:component-scan base-package="org.web8i.controller,org.web8i.service"/>
<!-- 视图解释类 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver"
>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/jsp/" />
<property name="suffix" value=".jsp" /><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
</bean>
</beans>
UserController.java
package org.web8i.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.web8i.model.User;
import org.web8i.service.UserService;
@Controller
public class UserController {
@Autowired(required=true)
private UserService userService;
//用户列表界面
@RequestMapping(value="/user/list")
public ModelAndView listUsers(){
List<User> userList = new ArrayList<User>();
userList = userService.getUserList();
/**ModelAndView构造函数3个参数中,参数1表示返回的视图名即相应的JSP,这里会
* 这里是/WEB-INF/view/jsp/user_list.jsp,为什么呢?请参考
* spring_servlet.xml文件中的viewResolver的配置;参数2表示放入模型中
* 属性的名字;参数3表示模型中对应属性的值。
*/
return new ModelAndView("user_list","userList",userList);
}
//新增界面
@RequestMapping(value="/user/add")
public ModelAndView addUser(User user){
return new ModelAndView("user_add","command",user);//command是系统默认的模型属性名
}
//新增保存功能
@RequestMapping(value="/user/save")
public String saveUser(User user){
userService.addUser(user);
return "redirect:list.html";
}
//修改界面
@RequestMapping(value="/user/{userId}/edit")
public ModelAndView editUser(@PathVariable("userId") int userId){
User user = userService.getUserById(userId);
return new ModelAndView("user_edit","command",user);
}
//修改保存功能
@RequestMapping(value="/user/{userId}/update")
public String updateUser(User user){
userService.updateUser(user);
return "redirect:../list.html";
}
//删除功能
@RequestMapping(value="/user/{userId}/remove")
public String removeUser(@PathVariable("userId") int userId){
userService.removeUser(userId);
return "redirect:../list.html";
}
}
UserService.java
package org.web8i.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import org.web8i.model.User;
@Service
public class UserService {
static List<User> userList = new ArrayList<User>();
static{
User u1 = new User();
u1.setId(1);
u1.setUserName("David");
u1.setPassword("123456");
u1.setEmail("david@web8i.org");
userList.add(u1);
User u2 = new User();
u2.setId(2);
u2.setUserName("Naivee");
u2.setPassword("123456");
u2.setEmail("naivee@web8i.org");
userList.add(u2);
User u3 = new User();
u3.setId(3);
u3.setUserName("Mike");
u3.setPassword("123456");
u3.setEmail("mike@web8i.org");
userList.add(u3);
}
public List<User> getUserList(){
return userList;
}
public User getUserById(int userId){
for(User u : userList){
if(u.getId() == userId){
return u;
}
}
return null;
}
public void addUser(User user){
userList.add(user);
}
public void updateUser(User user){
int index = -1;
for(User u : userList){
if(u.getId() == user.getId()) index++;
}
userList.set(index, user);
}
public void removeUser(int userId){
userList.remove(this.getUserById(userId));
}
}
User.java
package org.web8i.model;
public class User {
private int id;
private String userName;
private String password;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}