SpringMVC聯手REST實現入門級的CRUD

明天還有我發表於2016-03-08

這是一個WebProject,用到的是spring-framework-3.1.1.RELEASE


首先是web.xml(最終應用訪問地址為http://IP:port/contextPath/user/add)

<?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
<%@ 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
<%@ 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
<%@ 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
<%@ 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
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
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"; //刪除完成後顯示當前存在的所有使用者資訊  
    }  
}  


相關文章