SpringMVC RESTful practice demo

1. REST is a web service architecture style, not a technology. If an architecture conforms to the REST principles, it is called a RESTful architecture.

The RESTful-style architecture is all about the operation of resources. All resources should be nouns rather than verbs.

Create a resource: POST to 
retrieve a resource: GET to
update a resource: PUT to 
delete a resource: DELETE 

The following is an example to demonstrate how to use HTTP requests to manipulate resources.

GET: /students will return all student information

GET:   /students/101 will return student information with id 101 

POST: /students/101 will create new student information with id 101 

PUT:   /students/101 will update the student information with id 101 

DELETE:   /students/101 will delete the student information with id 101 


2. The pom.xml file is as follows:

<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.example</groupId>
	<artifactId>SpringMVC_RESTful</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVC_RESTful Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.3.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>4.3.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>4.1.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.5.0</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVC_RESTful</finalName>
	</build>
</project>


2. The web.xml file is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
      </init-param>
      <!-- <load-on-startup>1</load-on-startup> -->
</servlet>
 
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>


3. The springmvc-servlet.xml file is as follows:

<?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-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

	<!-- 启用spring mvc 注解 -->
	<context:annotation-config />
	<!-- scan the package and the sub package -->
	<context:component-scan base-package="com.example" />

   <!-- if you use annotation you must configure following setting -->
	<mvc:annotation-driven />
	<!-- 完成请求和注解POJO的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
	<!-- configure the InternalResourceViewResolver 一种试图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		id="internalResourceViewResolver">

		<property name="prefix" value="/WEB-INF/"/>

		<property name="suffix" value=".jsp" />
	</bean>
</beans>


4. Entity class

package com.example.model;

public class Student { private long id; private String name; private String sex; public Student() { } public Student( String name, String sex) { super(); this.name = name; this.sex = sex; } public Student(long id, String name, String sex) { super(); this.id = id; this.name = name; this.sex = sex; } 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 String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }

 

5.DAO

package com.example.dao;

import java.util.List;

import com.example.model.Student;

public interface StudentDao {
	public Student addStudent(Student student);
	public long deleteStudent(Long id);
	public Student queryOneStudent(Long id);
	public Student changeStudent(Student student);
	public List<Student> getStudentList();
}


6.StudentDaoImpl

package com.example.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.example.dao.StudentDao;
import com.example.model.Student;

@Repository("studentDao")
public class StudentDaoImpl implements StudentDao {
	
	private static List<Student> students;
	{
		students = new ArrayList<Student>();
		students.add(new Student(101, "Mike", "male"));
		students.add(new Student(102, "Huang", "male"));
		students.add(new Student(103, "Mao", "female"));
	}

	public Student addStudent(Student student) {
		//student.setId(System.currentTimeMillis());
		students.add(student);
		return student;
	}

	public long deleteStudent(Long id) {
		for (Student student : students) {
			if (student.getId() == id){
				students.remove(student);
				return id;
			}
		}
		return id;
	}

	public Student queryOneStudent(Long id) {
		for (Student student : students) {
			if (student.getId() == id){
				return student;
			}
		}
		return null;
	}

	public Student changeStudent(Student student) {
		for (Student s : students) {
			if (s.getId() == student.getId()){
				return student;
			}
		}
		return null;
	}

	public List<Student> getStudentList() {
		return students;
	}

}


7. Control layer, here will correspond to the HTTP request method, select the method in RequestMethod, and mark the id with @PathVariable annotation.

package com.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.dao.StudentDao;
import com.example.model.Student;


@RestController()
public class StudentController {
	
	@Autowired
	private StudentDao studentDao;
	
	@RequestMapping(value = "/students", method = RequestMethod.GET)
	@ResponseBody
	public List<Student> getStudentList() {
		List<Student> students = studentDao.getStudentList();
		return students;
	}
	
	@RequestMapping(value = "/students/{id}", method = RequestMethod.GET)

	public ResponseEntity<Student>  queryOneStudent(@PathVariable("id") long id) {
		Student student = studentDao.queryOneStudent(id);
		return new ResponseEntity<Student>(student,HttpStatus.OK);
	}
	
	@RequestMapping(value = "/students/{id}", method = RequestMethod.DELETE)
	public ResponseEntity<Long> deleteStudent(@PathVariable("id") long id) {
		long showId = studentDao.deleteStudent(id);
		return new ResponseEntity<Long>(showId,HttpStatus.OK);
	}
	
	@RequestMapping(value = "/students/{id}", method = RequestMethod.POST)
	public ResponseEntity<Student> addStudent(@PathVariable("id") long id) {
		Student student = new Student(id,"rex", "male");
		student = studentDao.addStudent(student);
		return new ResponseEntity<Student>(student,HttpStatus.OK);
	}
	
	@RequestMapping(value = "/students/{id}", method = RequestMethod.PUT)
	public ResponseEntity<Student> changeStudent(@PathVariable("id") long id) {
		Student student = new Student(id,"leona", "female");
		student = studentDao.changeStudent(student);
		return new ResponseEntity<Student>(student,HttpStatus.OK);
	}
	
}

8. Use the extension application POSTMAN of Google browser to test, you can choose the request method very conveniently.





Guess you like

Origin blog.csdn.net/u010857795/article/details/54377196