SpringMVC基础Demo—创建RESTService

来源:互联网 发布:淘宝贷款利息是多少 编辑:程序博客网 时间:2024/06/06 08:08

这里通过注解方式创建restservcie,通过简单的增删改查,对rest进行初步的学习。

一、所使用到的tools:

JDK 1.8: 下载地址:
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
eclipse:Version: Luna Service Release 2 (4.4.2) 下载地址:
https://www.eclipse.org/downloads/
Tomcate:Apache Tomcat v7.0 下载地址:
https://tomcat.apache.org/download-70.cgi
maven: Apache Maven 3.3.9 下载地址:
http://maven.apache.org/download.cgi
SpringRELEASE: 4.2.4.RELEASE 下载地址:
http://repo.Spring.io/release/org/Springframework/Spring/

二、项目结构目录:
这里写图片描述

三、如何创建:
1、创建一个maven webapp项目
这里写图片描述

2、maven中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.hzfstudy.springmvc</groupId>  <artifactId>springmvc_rest</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>springmvc_rest Maven Webapp</name>  <url>http://maven.apache.org</url>  <properties>        <springframework.version>4.2.4.RELEASE</springframework.version>        <jackson.version>2.5.3</jackson.version>    </properties>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>    <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-webmvc</artifactId>            <version>${springframework.version}</version>        </dependency>        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-tx</artifactId>            <version>${springframework.version}</version>        </dependency>        <dependency>            <groupId>com.fasterxml.jackson.core</groupId>            <artifactId>jackson-databind</artifactId>            <version>${jackson.version}</version>        </dependency>        <dependency>            <groupId>javax.servlet</groupId>            <artifactId>javax.servlet-api</artifactId>            <version>3.1.0</version>        </dependency>  </dependencies>  <build>  <pluginManagement>            <plugins>                <plugin>                    <groupId>org.apache.maven.plugins</groupId>                    <artifactId>maven-war-plugin</artifactId>                    <version>2.4</version>                    <configuration>                        <warSourceDirectory>src/main/webapp</warSourceDirectory>                        <warName>springmvc_rest</warName>                        <failOnMissingWebXml>false</failOnMissingWebXml>                    </configuration>                </plugin>            </plugins>        </pluginManagement>    <finalName>springmvc_rest</finalName>  </build></project>

3、通过注解方式构建springmvc框架:
<1>、CORSFilter.java

package com.hzfstudy.springmvc.configuration;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletResponse;public class CORSFilter implements Filter {    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {        System.out.println("Filtering on...........................................................");        HttpServletResponse response = (HttpServletResponse) res;        response.setHeader("Access-Control-Allow-Origin", "*");        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");        response.setHeader("Access-Control-Max-Age", "3600");        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");        chain.doFilter(req, res);    }    public void init(FilterConfig filterConfig) {}    public void destroy() {}}

<2>、HelloRestConfiguration .java

package com.hzfstudy.springmvc.configuration;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration@EnableWebMvc@ComponentScan(basePackages = "com.hzfstudy.springmvc")public class HelloRestConfiguration {}

<3>、HelloRestInitializer .java

package com.hzfstudy.springmvc.configuration;import javax.servlet.Filter;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;public class HelloRestInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {    @Override    protected Class<?>[] getRootConfigClasses() {        return new Class[] { HelloRestConfiguration.class };    }    @Override    protected Class<?>[] getServletConfigClasses() {        return null;    }    @Override    protected String[] getServletMappings() {        return new String[] { "/" };    }    @Override    protected Filter[] getServletFilters() {        Filter [] singleton = { new CORSFilter()};        return singleton;    }}

4、创建model层:
Student .java

package com.hzfstudy.springmvc.model;public class Student {    private long id;    private String name;    private int age;    private double grade;    public  Student(){        id=0;    }    public  Student(long id, String name, int age, double grade){        this.id = id;        this.name = name;        this.age = age;        this.grade = grade;    }    public long getId() {        return id;    }    public void setId(long id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public double getGrade() {        return grade;    }    public void setGrade(double grade) {        this.grade = grade;    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + (int) (id ^ (id >>> 32));        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Student other = (Student) obj;        if (id != other.id)            return false;        return true;    }    @Override    public String toString() {        return "User [id=" + id + ", name=" + name + ", age=" + age                + ", grade=" + grade + "]";    }}

5、业务逻辑层:
StudentService .java

package com.hzfstudy.springmvc.service;import java.util.List;import com.hzfstudy.springmvc.model.Student;public interface StudentService {    Student findById(long id);    Student findByName(String name);    void saveStudent(Student Student);    void updateStudent(Student Student);    void deleteStudentById(long id);    List<Student> findAllStudents();     void deleteAllStudents();    public boolean isStudentExist(Student Student);}

StudentServiceImpl .java

package com.hzfstudy.springmvc.service;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.concurrent.atomic.AtomicLong;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;import com.hzfstudy.springmvc.model.Student;@Service("StudentService")@Transactionalpublic class StudentServiceImpl implements StudentService{    private static final AtomicLong counter = new AtomicLong();    private static List<Student> Students;    static{        Students= populateDummyStudents();    }    public List<Student> findAllStudents() {        return Students;    }    public Student findById(long id) {        for(Student Student : Students){            if(Student.getId() == id){                return Student;            }        }        return null;    }    public Student findByName(String name) {        for(Student Student : Students){            if(Student.getName().equalsIgnoreCase(name)){                return Student;            }        }        return null;    }    public void saveStudent(Student Student) {        Student.setId(counter.incrementAndGet());        Students.add(Student);    }    public void updateStudent(Student Student) {        int index = Students.indexOf(Student);        Students.set(index, Student);    }    public void deleteStudentById(long id) {        for (Iterator<Student> iterator = Students.iterator(); iterator.hasNext(); ) {            Student Student = iterator.next();            if (Student.getId() == id) {                iterator.remove();            }        }    }    public boolean isStudentExist(Student Student) {        return findByName(Student.getName())!=null;    }    public void deleteAllStudents(){        Students.clear();    }    private static List<Student> populateDummyStudents(){        List<Student> Students = new ArrayList<Student>();        Students.add(new Student(counter.incrementAndGet(),"stu1",11, 70));        Students.add(new Student(counter.incrementAndGet(),"stu2",22, 80));        Students.add(new Student(counter.incrementAndGet(),"stu3",33, 90));        Students.add(new Student(counter.incrementAndGet(),"stu4",44, 98));        Students.add(new Student(counter.incrementAndGet(),"stu5",55, 99));        Students.add(new Student(counter.incrementAndGet(),"stu6",66, 77));        return Students;    }}

6、最后剩下控制层:

HelloRestController .java

package com.hzfstudy.springmvc.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.util.UriComponentsBuilder;import com.hzfstudy.springmvc.model.Student;import com.hzfstudy.springmvc.service.StudentService;@RestControllerpublic class HelloRestController {    @Autowired    StudentService StudentService;    //查询所有学生信息    @RequestMapping(value = "/Student/", method = RequestMethod.GET)    public ResponseEntity<List<Student>> listAllStudents() {        List<Student> Students = StudentService.findAllStudents();        if (Students.isEmpty()) {            return new ResponseEntity<List<Student>>(HttpStatus.NO_CONTENT);        }        return new ResponseEntity<List<Student>>(Students, HttpStatus.OK);    }    //按条件id查询学生信息    @RequestMapping(value = "/Student/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)    public ResponseEntity<Student> getStudent(@PathVariable("id") long id) {        System.out.println("Fetching Student with id " + id);        Student Student = StudentService.findById(id);        if (Student == null) {            System.out.println("Student with id " + id + " not found");            return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);        }        return new ResponseEntity<Student>(Student, HttpStatus.OK);    }    //增加学生信息    @RequestMapping(value = "/Student/", method = RequestMethod.POST)    public ResponseEntity<Void> createStudent(@RequestBody Student Student,            UriComponentsBuilder ucBuilder) {        System.out.println("Creating Student " + Student.getName());        if (StudentService.isStudentExist(Student)) {            System.out.println("A Student with name " + Student.getName()                    + " already exist");            return new ResponseEntity<Void>(HttpStatus.CONFLICT);        }        StudentService.saveStudent(Student);        HttpHeaders headers = new HttpHeaders();        headers.setLocation(ucBuilder.path("/Student/{id}")                .buildAndExpand(Student.getId()).toUri());        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);    }    //更新学生信息    @RequestMapping(value = "/Student/{id}", method = RequestMethod.PUT)    public ResponseEntity<Student> updateStudent(@PathVariable("id") long id,            @RequestBody Student Student) {        System.out.println("Updating Student " + id);        Student currentStudent = StudentService.findById(id);        if (currentStudent == null) {            System.out.println("Student with id " + id + " not found");            return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);        }        currentStudent.setName(Student.getName());        currentStudent.setAge(Student.getAge());        currentStudent.setGrade(Student.getGrade());        StudentService.updateStudent(currentStudent);        return new ResponseEntity<Student>(currentStudent, HttpStatus.OK);    }    //按条件id删除学生信息    @RequestMapping(value = "/Student/{id}", method = RequestMethod.DELETE)    public ResponseEntity<Student> deleteStudent(@PathVariable("id") long id) {        System.out.println("Fetching & Deleting Student with id " + id);        Student Student = StudentService.findById(id);        if (Student == null) {            System.out.println("Unable to delete. Student with id " + id                    + " not found");            return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);        }        StudentService.deleteStudentById(id);        return new ResponseEntity<Student>(HttpStatus.NO_CONTENT);    }    // 删除所有学生信息    @RequestMapping(value = "/Student/", method = RequestMethod.DELETE)    public ResponseEntity<Student> deleteAllStudents() {        System.out.println("Deleting All Students");        StudentService.deleteAllStudents();        return new ResponseEntity<Student>(HttpStatus.NO_CONTENT);    }}

至此,Demo就创建完毕了,代码比较简单,框架搭起来就只剩下增删改查实现了。下面主要看下它是如何通过rest的方式进行增删改查的。
这里通过Postman进行操作:
POSTMAN下载

(1)、GET操作:查询所有学生的信息:

这里写图片描述

按调条件查id询学生信息:

这里写图片描述

若不符合条件则查询内容为空:

这里写图片描述

(2)、POST操作:增加学生信息:

这里写图片描述

再次查询:

这里写图片描述

增加成功,因为id在类中设定为自增的 所以不用指定id

(3)、PUT操作:更新学生信息:

这里写图片描述

这里更新刚才新增加的学生信息,更新完毕后再次查询:

这里写图片描述

更新成功。

(4)、DELETE操作:删除学生信息:
按条件id删除学生信息:
这里写图片描述

删除刚才新增的学生信息:
再次查询:
这里写图片描述

信息已经不存在,说明删除成功。

删除所有学生信息:
这里写图片描述

再次查询所有学生信息:
这里写图片描述

已经不存在,说明删除成功。

以上就是关于rest的简单认识。

0 0
原创粉丝点击