使用SpringMVC实现RESTful风格
SpringMVC
1、SpringMVC
是Spring体系的轻量级Web MVC框架,用于替代传统的J2EE Servlet,简化web应用开发
2、SpringMVC
的核心是Controller控制器,用于处理请求,产生响应
3、SpringMVC
基于Spring IOC容器运行,所有对象被IOC容器管理,提高了程序的健壮性与稳定性
RESTful
1、REST(Representational State Transfer,表述性状态传递)以URL表示要访问的资源
2、GET/POST/PUT/DELETE对应查询、新增、更新、删除操作
3、RESTful风格指响应只返回数据,通常是以JSON形式体现
例子
引入依赖 pom.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.3.RELEASE</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.54</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>compile</scope> </dependency>
|
配置文件 web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13
| <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </init-param> </servlet>
<servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
|
配置文件 applicationContext.xml
1 2 3 4 5 6 7 8
| <beans ...> <context:component-scan base-package="..."/> <mvc:annotation-driven/> <mvc:default-servlet-handler/> </beans>
|
实体类 Employee
1 2 3 4 5 6 7 8 9 10 11 12
| public class Employee { private String name; private int age; private String department;
public Employee(String name, int age, String department) { this.name = name; this.age = age; this.department = department; } }
|
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import com.alibaba.fastjson.JSON;
@Controller
public class RestfulController { @GetMapping("/emp/list/{DEPT}") @ResponseBody public String list(@PathVariable("DEPT") String department) { List<Employee> list = new ArrayList<Employee>(); if (department.equals("RESEARCH")) { list.add(new Employee("JAMES", 38, "RESEARCH")); list.add(new Employee("ANDY", 23, "RESEARCH")); list.add(new Employee("SMITH", 31, "RESEARCH")); } return JSON.toJSONString(list); } }
|
request:
localhost:8080/emp/list/RESEARCH
response:
1 2 3
| [{"age":38,"department":"RESEARCH","name":"JAMES"}, {"age":23,"department":"RESEARCH","name":"ANDY"}, {"age":31,"department":"RESEARCH","name":"SMITH"}]
|