Spring MVC --RESTful

什麼是RESTful?

  • 1.RESTful不是一套標準,只是一種開發方式,架構思想
  • 2.url更加簡潔
  • 3.有利於不同系統之間的資源共享

RESTful具體來講就是HTTP協議的四種形式

  • GET:獲取資源
  • POST:新建資源
  • PUT:修改資源
  • DELETE:刪除資源

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.imooc</groupId>
  <artifactId>SpringMVCRESTful</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>SpringMVCRESTful Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>

    <!-- SpringMVC -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!-- jackson -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.8.3</version>
    </dependency>

    <!-- JSTL -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>SpringMVCRESTful</finalName>
  </build>
</project>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!--處理中文亂碼-->
  <filter>
    <filter-name>encodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

web.xml加入HiddenHttpMethodFilte過濾器

  <!-- 增加HiddenHttpMethodFilte過濾器:給普通瀏覽器增加 put|delete請求方式 -->
  <filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>

 

springmvc.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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <mvc:annotation-driven >
        <!-- 消息轉換器 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

	<!-- 配置自動掃描 -->
    <context:component-scan base-package="com.imooc"></context:component-scan>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

Course.java

public class Course {
    private int id;
    private String name;
    private double price;

    //get和set方法
}

CourseDAO.java

package com.imooc.dao;

import com.imooc.entity.Course;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator.
 */
@Repository
public class CourseDAO {
    private Map<Integer,Course> courses = new HashMap<Integer,Course>();

    /**
     * 新增課程
     */
    public void add(Course course){
        courses.put(course.getId(),course);
    }

    /**
     * 查詢全部課程
     */
    public Collection<Course> getAll(){
        return courses.values();
    }

    /**
     * 通過id查詢課程
     */
    public Course getById(int id){
        return courses.get(id);
    }

    /**
     * 修改課程
     */
    public void update(Course course){
        courses.put(course.getId(),course);
    }

    /**
     * 刪除課程
     */
    public void deleteById(int id){
        courses.remove(id);
    }
}

CourseController.java

 @RequestParam和@PathVariable都能夠完成類似的功能——因爲本質上,它們都是用戶的輸入,只不過輸入的部分不同,一個在URL路徑部分,另一個在參數部分。要訪問一篇博客文章,這兩種URL設計都是可以的:

  • 通過@PathVariable,例如/blogs/1
  • 通過@RequestParam,例如blogs?blogId=1

那麼究竟應該選擇哪一種呢?建議:

1、當URL指向的是某一具體業務資源(或資源列表),例如博客,用戶時,使用@PathVariable

2、當URL需要對資源或者資源列表進行過濾,篩選時,用@RequestParam

例如我們會這樣設計URL:

  • /blogs/{blogId}
  • /blogs?state=publish而不是/blogs/state/publish來表示處於發佈狀態的博客文章

 

package com.imooc.controller;

import com.imooc.dao.CourseDAO;
import com.imooc.entity.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by Administrator.
 */
@Controller
public class CourseController {
    @Autowired
    private CourseDAO courseDAO;

    /**
     * 添加課程
     */
    @PostMapping(value = "/add")
    public String add(Course course){
        courseDAO.add(course);
        return "redirect:/getAll";
    }

    /**
     * 查詢全部課程
     * @return
     */
    @GetMapping(value = "/getAll")
    public ModelAndView getAll(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        modelAndView.addObject("courses",courseDAO.getAll());
        return modelAndView;
    }

    /**
     * 通過id查詢課程
     */
    @GetMapping(value = "/getById/{id}")
    public ModelAndView getById(@PathVariable(value = "id") int id){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("edit");
        modelAndView.addObject("course",courseDAO.getById(id));
        return modelAndView;
    }

    /**修改課程
     *
     */
    @PutMapping(value = "/update")
    public String update(Course course){
        courseDAO.update(course);
        return "redirect:/getAll";
    }

    /**
     * 刪除課程
     */
    @DeleteMapping(value = "/delete/{id}")
    public String delete(@PathVariable(value = "id")  int id){
        courseDAO.deleteById(id);
        return "redirect:/getAll";
    }

}

 add.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>add</title>
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        body{
            overflow-x:hidden;
        }
        #main{
            width:1200px;
            height:600px;
            margin-left:500px;
        }
    </style>
</head>
<body>

<div id="main">
    <!-- 標題 -->
    <div class="row">
        <div class="col-md-12">
            <h1>imooc-添加課程</h1>
        </div>
    </div>

    <form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/add" method="post">
        <div class="form-group">
            <label class="col-sm-1 control-label">課程編號</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="id" placeholder="請輸入課程編號">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">課程名稱</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="name" placeholder="請輸入課程名稱">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">課程價格</label>
            <div class="col-sm-3">
                <input type="text" class="form-control" name="price" placeholder="請輸入課程價格">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

edit.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>add</title>
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style type="text/css">
        body{
            overflow-x:hidden;
        }
        #main{
            width:1200px;
            height:600px;
            margin-left:500px;
        }
    </style>
</head>
<body>

<div id="main">
    <!-- 標題 -->
    <div class="row">
        <div class="col-md-12">
            <h1>imooc-修改課程</h1>
        </div>
    </div>

    <form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/update" method="post">
        <div class="form-group">
            <label class="col-sm-1 control-label">課程編號</label>
            <div class="col-sm-3">
                <input type="text" value="${course.id}" name="id" readonly="readonly" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">課程名稱</label>
            <div class="col-sm-3">
                <input type="text" value="${course.name}" name="name" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-1 control-label">課程價格</label>
            <div class="col-sm-3">
                <input type="text" value="${course.price}" name="price" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <input type="hidden" name="_method" value="PUT"/>
                <button type="submit" class="btn btn-default">提交</button>
            </div>
        </div>
    </form>
</div>
</body>
</html>

使用隱藏域

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>課程列表</title>
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">

    <!-- 標題 -->
    <div class="row">
        <div class="col-md-12">
            <h1>imooc-課程管理</h1>
        </div>
    </div>
    <!-- 顯示錶格數據 -->
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th>
                        <input type="checkbox" id="check_all"/>
                    </th>
                    <th>編號</th>
                    <th>課程名</th>
                    <th>價格</th>
                    <th>編輯</th>
                    <th>刪除</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach items="${courses}" var="course">
                    <tr>
                        <td><input type='checkbox' class='check_item'/></td>
                        <td>${course.id}</td>
                        <td>${course.name}</td>
                        <td>${course.price}</td>
                        <td>
                            <form action="${pageContext.request.contextPath}/getById/${course.id}" method="get">
                                <button class="btn btn-primary btn-sm edit_btn" type="submit">
                                    <span class="glyphicon glyphicon-pencil">編輯</span>
                                </button>
                            </form>
                        </td>
                        <td>
                            <form action="${pageContext.request.contextPath}/delete/${course.id}" method="post">
                                <button class="btn btn-danger btn-sm delete_btn" type="submit">
                                    <input type="hidden" name="_method" value="DELETE"/>
                                    <span class="glyphicon glyphicon-trash">刪除</span>
                                </button>
                            </form>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>

</div>
</body>
</html>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章