SpringMVC结合REST实现入门级的CRUD

jopen 11年前

这是一个WebProject,用到的是spring-framework-3.1.1.RELEASE</span></strong></span>

 

首先是web.xml(最终应用访问地址为http://IP:port/contextPath/user/add)</span></strong></span>

<?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">    <servlet>    <servlet-name>user</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <load-on-startup>1</load-on-startup>   </servlet>   <servlet-mapping>    <servlet-name>user</servlet-name>    <url-pattern>/</url-pattern>   </servlet-mapping>     <filter>    <filter-name>SpringCharacterEncodingFilter</filter-name>    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>    <init-param>     <param-name>encoding</param-name>     <param-value>UTF-8</param-value>    </init-param>   </filter>   <filter-mapping>    <filter-name>SpringCharacterEncodingFilter</filter-name>    <url-pattern>/*</url-pattern>   </filter-mapping>  </web-app>

然后是SpringMVC的配置文件user-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: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-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd        http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd">   <context:component-scan base-package="com.jadyer"/>      <mvc:annotation-driven/>      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="prefix" value="/WEB-INF/jsp/"/>    <property name="suffix" value=".jsp"/>   </bean>  </beans>

用来添加用户信息的//WEB-INF//jsp/user/add.jsp</strong></span>

<%@ page language="java" pageEncoding="UTF-8"%>  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>    <%-- 这里并没有指定action="",说明表单是提交给自己的,说白了就是"哪来的回哪儿去 --%>    <form:form method="POST" modelAttribute="user">   username: <form:input path="username"/><br/>   nickname: <form:input path="nickname"/><br/>   password: <form:password path="password"/><br/>   yourmail: <form:input path="email"/><br/>   <input type="submit" value="添加新用户"/>  </form:form>

用来列出所有用户信息的//WEB-INF//jsp/user/list.jsp</strong></span>

<%@ page language="java" pageEncoding="UTF-8"%>  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  <c:forEach items="${users}" var="user">   ${user.value.username}----${user.value.nickname}----${user.value.password}----${user.value.email}       <a href="<%=request.getContextPath()%>/user/${user.value.username}">查看</a>       <a href="<%=request.getContextPath()%>/user/${user.value.username}/update">编辑</a>       <a href="<%=request.getContextPath()%>/user/${user.value.username}/delete">删除</a>   <br/>  </c:forEach>  <br/>  <a href="<%=request.getContextPath()%>/user/add">继续添加用户</a>

用来显示单个用户信息的//WEB-INF//jsp/user/show.jsp</strong></span>

<%@ page language="java" pageEncoding="UTF-8"%>  ${user.username}----${user.nickname}----${user.password}----${user.email}  <br/>  <br/>  <a href="<%=request.getContextPath()%>/user/add">继续添加用户</a>

用来更新单个用户信息的//WEB-INF//jsp/user/update.jsp</strong></span>

<%@ page language="java" pageEncoding="UTF-8"%>  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  <form:form method="POST" modelAttribute="user">   username: <form:input path="username"/><br/>   nickname: <form:input path="nickname"/><br/>   password: <form:password path="password"/><br/>   yourmail: <form:input path="email"/><br/>   <input type="submit" value="更新用户信息"/>  </form:form>

下面是用户的实体类User.java</strong></span>

package com.jadyer.model;    /**   * User   * @author http://blog.csdn.net/jadyer   * @create May 12, 2012 1:24:43 AM   */  public class User {   private String username;   private String nickname;   private String password;   private String email;      public User() {}   public User(String username, String nickname, String password, String email) {    this.username = username;    this.nickname = nickname;    this.password = password;    this.email = email;   }      public String getUsername() {    return username;   }   public void setUsername(String username) {    this.username = username;   }   public String getNickname() {    return nickname;   }   public void setNickname(String nickname) {    this.nickname = nickname;   }   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;   }  }

最后是核心的UserController.java</strong></span>
package com.jadyer.controller;    import java.util.HashMap;  import java.util.Map;    import org.springframework.stereotype.Controller;  import org.springframework.ui.Model;  import org.springframework.web.bind.annotation.PathVariable;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RequestMethod;    import com.jadyer.model.User;    /**   * UserController   * @author http://blog.csdn.net/jadyer   * @create May 12, 2012 1:26:21 AM   */  @Controller  @RequestMapping("/user")  public class UserController {   private final static Map<String,User> users = new HashMap<String,User>();      //模拟数据源,构造初始数据   public UserController(){    users.put("张起灵", new User("张起灵", "闷油瓶", "02200059", "menyouping@yeah.net"));    users.put("李寻欢", new User("李寻欢", "李探花", "08866659", "lixunhuan@gulong.cn"));    users.put("拓拔野", new User("拓拔野", "搜神记", "05577759", "tuobaye@manhuang.cc"));    users.put("孙悟空", new User("孙悟空", "美猴王", "03311159", "sunhouzi@xiyouji.zh"));   }      /**    * 添加新用户    * @see 访问/user/add时,GET请求就执行addUser(Model model)方法,POST请求就执行addUser(User user)方法    */   @RequestMapping(value="/add", method=RequestMethod.GET)   public String addUser(Model model){    //这里要传给前台一个空对象,否则会报告java.lang.IllegalStateException异常    //异常信息为Neither BindingResult nor plain target object for bean name 'user' available as request attribute    //并且传过去的key值要与前台modelAttribute属性值相同,即model.addAttribute("user", new User());    //我们也可以写成下面这种方式,此时SpringMVC会自动把对象名转换为小写值作为key,即User-->user    model.addAttribute(new User());    return "user/add";   }   @RequestMapping(value="/add", method=RequestMethod.POST)   public String addUser(User user){ //这里参数中的user就应该与add.jsp中的modelAttribute="user"一致了    users.put(user.getUsername(), user);    return "redirect:/user/list";   }      /**    * 列出所有用户信息    */   @RequestMapping("/list")   public String list(Model model){    model.addAttribute("users", users);    return "user/list";   }      /**    * 查询用户信息    * @see 访问该方法的路径就应该是"/user/具体的用户名"    * @see 这里value="/{username}"的写法,需要格外注意一下,它是一个路径变量,此时用来接收前台的一个资源    * @see 这时value="/{username}"就会到方法参数中找@PathVariable String username,并将路径变量值传给username参数    */   @RequestMapping(value="/{myname}", method=RequestMethod.GET)   public String show(@PathVariable String myname, Model model){    model.addAttribute(users.get(myname));    return "user/show";   }      /**    * 编辑用户信息    * @see 访问该方法的路径就应该是"/user/具体的用户名/update"    */   @RequestMapping(value="/{myname}/update", method=RequestMethod.GET)   public String update(@PathVariable String myname, Model model){    model.addAttribute(users.get(myname));    return "user/update";   }   @RequestMapping(value="/{myname}/update", method=RequestMethod.POST)   public String update(User user){    users.put(user.getUsername(), user);    return "redirect:/user/list"; //也可以retun "forward:/user/list",此时浏览器地址栏会有不同   }      /**    * 删除用户信息    */   @RequestMapping(value="/{myname}/delete", method=RequestMethod.GET)   public String delete(@PathVariable String myname){    users.remove(myname);    return "redirect:/user/list"; //删除完成后显示当前存在的所有用户信息   }  }
来自:http://blog.csdn.net/jadyer/article/details/7574659