Spring MVC学习 ( RESTful)

  • 2019 年 10 月 9 日
  • 筆記

是一套规则,不同的系统之间(Vue java Python C#  PHP)具体四种不同类型的HTTP 请求分别表示四种基本操作(CRUD)

GET :查询(R)

POST:添加(C)

PUT:修改(U)

DELETE:删除(D)

Spring MVC 默认支持RESTful 结构 

RestHandler.java

package com.xcl.controller;      import com.xcl.entity.User;  import com.xcl.repository.UserRepository;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.web.bind.annotation.*;    import javax.servlet.http.HttpServletResponse;  import java.util.Collection;    @RestController  @RequestMapping("/rest")  public class RestHandler {        @Autowired      private UserRepository userRepository;          /**       * 查询所有  GET请求       *       * @param response       * @return       */      @GetMapping("/findAll")      public Collection<User> findAll(HttpServletResponse response) {          response.setContentType("text/json;charset=UTF-8");          return userRepository.findAll();      }        /**       * 根据ID查询  GET请求       *       * @param response       * @param id       * @return       */      @GetMapping("/findById/{id}")      public User findAll(HttpServletResponse response, @PathVariable("id") Integer id) {          response.setContentType("text/json;charset=UTF-8");          return userRepository.findById(id);      }        /**       * 添加  POST请求       *       * @param user       */      @PostMapping("/save")      public void save(User user) {          userRepository.saveOrUpdate(user);      }        /**       * 修改  PUT请求       *       * @param user       */      @PutMapping("/update")      public void update(User user) {          userRepository.saveOrUpdate(user);      }        /**       * 删除 DELETE请求       *       * @param id       */      @DeleteMapping("/delete/{id}")      public void deleteById(@PathVariable("id") Integer id) {          userRepository.deleteById(id);      }  }

 

User.java

package com.xcl.entity;      import lombok.AllArgsConstructor;  import lombok.Data;  import lombok.NoArgsConstructor;    @Data  @AllArgsConstructor  @NoArgsConstructor  public class User {      private  Integer id;      private  String name;  }

UserRepository 接口

package com.xcl.repository;    import com.xcl.entity.User;    import java.util.Collection;    public interface UserRepository {      public Collection<User> findAll();      public User findById(Integer id);      public void saveOrUpdate(User user);      public void  deleteById(Integer id);  }

UserRepositoryImpl 实现类

package com.xcl.repository.Impl;    import com.xcl.entity.User;  import com.xcl.repository.UserRepository;  import org.springframework.stereotype.Repository;    import java.util.Collection;  import java.util.HashMap;  import java.util.Map;      @Repository  public class UserRepositoryImpl implements UserRepository {        private  static Map<Integer,User> map;      static {          map=new HashMap<>();          map.put(1,new User(1,"张三"));          map.put(2,new User(2,"李四"));          map.put(3,new User(3,"王五"));          map.put(4,new User(4,"小张"));        }      @Override      public Collection<User> findAll() {         return  map.values();      }        @Override      public User findById(Integer id) {          return map.get(id);      }        @Override      public void saveOrUpdate(User user) {          map.put(user.getId(),user);      }        @Override      public void deleteById(Integer id) {          map.remove(id);      }  }

 

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">      <!-- ⾃动扫描 -->      <context:component-scan base-package="com.xcl"></context:component-scan>        <!-- 视图解析器 -->      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">          <!-- 前缀 -->          <property name="prefix" value="/"></property>          <!-- 后缀 -->          <property name="suffix" value=".jsp"></property>      </bean>      <!-- JSON  使用-->      <mvc:annotation-driven>          <!-- 消息转换器 -->          <mvc:message-converters>              <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">              </bean>          </mvc:message-converters>      </mvc:annotation-driven>    </beans>

 

pom.xml 配置

<?xml version="1.0" encoding="UTF-8"?>    <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/xsd/maven-4.0.0.xsd">      <modelVersion>4.0.0</modelVersion>        <groupId>com.xcl</groupId>      <artifactId>springmvc</artifactId>      <version>1.0-SNAPSHOT</version>      <packaging>war</packaging>        <name>springmvc Maven Webapp</name>      <!-- FIXME change it to the project's website -->      <url>http://www.example.com</url>        <properties>          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>          <maven.compiler.source>12</maven.compiler.source>          <maven.compiler.target>12</maven.compiler.target>      </properties>        <dependencies>            <dependency>              <groupId>junit</groupId>              <artifactId>junit</artifactId>              <version>4.11</version>              <scope>test</scope>          </dependency>            <dependency>              <groupId>org.springframework</groupId>              <artifactId>spring-webmvc</artifactId>              <version>5.1.7.RELEASE</version>          </dependency>            <dependency>              <groupId>javax.servlet</groupId>              <artifactId>javax.servlet-api</artifactId>              <version>3.0.1</version>          </dependency>            <dependency>              <groupId>org.projectlombok</groupId>              <artifactId>lombok</artifactId>              <version>1.18.10</version>              <scope>provided</scope>          </dependency>            <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->          <dependency>              <groupId>com.alibaba</groupId>              <artifactId>fastjson</artifactId>              <version>1.2.62</version>          </dependency>        </dependencies>        <build>          <finalName>springmvc</finalName>          <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->              <plugins>                  <plugin>                      <artifactId>maven-clean-plugin</artifactId>                      <version>3.1.0</version>                  </plugin>                  <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->                  <plugin>                      <artifactId>maven-resources-plugin</artifactId>                      <version>3.0.2</version>                  </plugin>                  <plugin>                      <artifactId>maven-compiler-plugin</artifactId>                      <version>3.8.0</version>                  </plugin>                  <plugin>                      <artifactId>maven-surefire-plugin</artifactId>                      <version>2.22.1</version>                  </plugin>                  <plugin>                      <artifactId>maven-war-plugin</artifactId>                      <version>3.2.2</version>                  </plugin>                  <plugin>                      <artifactId>maven-install-plugin</artifactId>                      <version>2.5.2</version>                  </plugin>                  <plugin>                      <artifactId>maven-deploy-plugin</artifactId>                      <version>2.8.2</version>                  </plugin>              </plugins>          </pluginManagement>      </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>    <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>  </web-app>