---
title: "spring mvc之实现简单的用户管理二"
author: "虚弱的java"
date: "2013-04-24T21:19:50Z"
tags: []
categories: ["开源软件"]
slug: "spring-mvc"
draft: false
lastmod: "2013-04-24T21:19:50Z"
id: 1853131
url: "https://appleblue.iteye.com/blog/1853131"
---

接下来实现用户管理中的增加，删除，修改功能。

在UserController类中添加如下方法：

@RequestMapping(value="/add",method=RequestMethod.GET)  
 public String add(Model model){

//在进入用户添加页面的时候，就必须将model设置进去，否则页面就会报错儿。因为add.jsp页面会

//找user.username.

//开启modelDriver(相对于struts2来讲)  
  model.addAttribute(new User());  
  return "user/add";//服务器端跳转，自动在前面加上forward  
 }

以上方法表示，当链接请求为GET时，会访问这个方法。此时，会跳转到用户的添加页面，add.jsp。

在add.jsp页中添加如下代码：

&lt;%@ page language="java" contentType="text/html; charset=UTF-8"  
    pageEncoding="UTF-8"%&gt;  
&lt;%@ taglib prefix="sf" uri="[http://www.springframework.org/tags/form](http://www.springframework.org/tags/form)" %&gt;  
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "[http://www.w3.org/TR/html4/loose.dtd](http://www.w3.org/TR/html4/loose.dtd)"&gt;  
&lt;html&gt;  
&lt;head&gt;  
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;  
&lt;title&gt;Insert title here&lt;/title&gt;  
&lt;/head&gt;  
&lt;body&gt;  
&lt;!-- 如果不写action,直接提交会提交给/add --&gt;  
&lt;sf:form method="post" modelAttribute="user" &gt;  
 用户名:&lt;sf:input path="username"/&gt;&lt;sf:errors path="username"/&gt;&lt;br/&gt;  
 密码:&lt;sf:password path="password"/&gt;&lt;sf:errors path="password"/&gt;&lt;br/&gt;  
 昵称:&lt;sf:input path="nickname"/&gt;&lt;br/&gt;  
 邮箱:&lt;sf:input path="email"/&gt;&lt;sf:errors path="email"/&gt;&lt;br/&gt;     
 &lt;input type="submit" value="添加用户"/&gt;  
&lt;/sf:form&gt;  
&lt;/body&gt;  
&lt;/html&gt;

如图：

![](http://dl.iteye.com/upload/attachment/0083/6310/eb06eea4-c81e-3392-baaf-e47a3bb269d2.png)  
在服务器中发布项目，在地址栏中输入请求地址，得到结果如图：

   
![](http://dl.iteye.com/upload/attachment/0083/6316/b61e4ef2-a848-3b11-9a9d-431ce29a4594.png)  
 输入用户信息，如下图：

![](http://dl.iteye.com/upload/attachment/0083/6320/ae86a4f0-f6cc-3e7d-b0cc-c773f7efc27e.png)  
 点击”添加用户“，得到结果如下图：

![](http://dl.iteye.com/upload/attachment/0083/6322/144ba541-fc3d-3bb1-aaf5-22005041de73.png)