springmvc restful api && swagger生成api文档

媒体类型(xml或json)

spring mvc 配置restful视图解析器ContentNegotiatingViewResolver,这个解析器可以根据扩展名的不同返回不同形式的结果,默认是xml格式(也可以通过重载WebMvcConfigurerAdapter的configureContentNegotiation方法进行设定),如果使用.json为url扩展,则返回json格式,但是controller层不能指定produces,否则无法识别url

@Configuration
@EnableWebMvc // 开启spring mvc配置
@ComponentScan("springmvc.base.controller")
public class Webconfig implements WebMvcConfigurer {
	@Bean
	public ViewResolver cnViewResolver() {// 定义一个视图解析器
		return new ContentNegotiatingViewResolver();
	}
	@Override// 配置默认媒体格式
	public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		configurer.defaultContentType(MediaType.APPLICATION_JSON);
	}
}

restfull api 一般会使用五种方法

新增:post
删除:delete
读取:get
更新:put(全参数)和patch(部分更新)

@RestController
@RequestMapping("/students") // 一般使用资源的复数
public class DemoRestController {
	private static Student s = new Student();
	@PostMapping // 新增
	public ResponseEntity<Student> save(@RequestParam(required = true) String name,
			@RequestParam(required = true) Integer age) {
		s.setId(1);
		s.setName(name);
		s.setAge(age);
		HttpHeaders headers = new HttpHeaders();
		URI location = URI.create("http://localhost:8080/students/" + s.getId());
		headers.setLocation(location);
		return new ResponseEntity<Student>(s, headers, HttpStatus.CREATED);
	}

	@DeleteMapping(value = "/{id}") // 删除
	public ResponseEntity<Student> delete(@PathVariable(required = true) Integer id) {
		return new ResponseEntity<Student>(s, HttpStatus.OK);
	}

	@GetMapping(value = "/{id}") // 获取
	public ResponseEntity<Student> query(@PathVariable(required = true) Integer id) {
		return new ResponseEntity<Student>(s, HttpStatus.OK);
	}

	@PutMapping(value = "/{id}") // 修改
	public ResponseEntity<Student> update(@PathVariable(required = true) Integer id,
			@RequestParam(required = true) String name, @RequestParam(required = true) Integer age) {
		s.setName(name);
		s.setAge(age);
		return new ResponseEntity<Student>(s, HttpStatus.OK);
	}
}

状态码

分类 分类描述
1** 信息,服务器收到请求,需要请求者继续执行操作
2** 成功,操作被成功接收并处理
3** 重定向,需要进一步的操作以完成请求
4** 客户端错误,请求包含语法错误或无法完成请求
5** 服务器错误,服务器在处理请求的过程中发生了错误

swagger生成api接口

依赖:

		<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-version}</version>
        </dependency> 

配置:

@Configuration
@EnableWebMvc // 开启spring mvc配置
@ComponentScan("springmvc.base.controller")
public class Webconfig implements WebMvcConfigurer {
	//Swagger2配置
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2).enable(true).apiInfo(apiInfo()).select()
				.apis(RequestHandlerSelectors.basePackage("springmvc.base.controller")).paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("学生信息").description("学生信息api")
				.termsOfServiceUrl("http://localhost:8080/student").version("1.0").build();
	}
	@Bean
	public ViewResolver cnViewResolver() {// 定义一个视图解析器
		return new ContentNegotiatingViewResolver();
	}
	@Override// 配置默认媒体格式
	public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
		configurer.defaultContentType(MediaType.APPLICATION_JSON);
	}
	/**
	 * 定义静态资源映射
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// swagger2
		registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}
}

controller层写法:

//swagger一般都是用value来改变api文档中的描述,swagger可以读取springmvc注解的部分信息,比如@RequestParam(required = true)的必选参数信息
@Api(tags="students")//tags可以修改接口最外层名称
@RestController
@RequestMapping("/students") // 一般使用资源的复数
public class DemoRestController {
	private static Student s = new Student();

	@ApiOperation(value = "存储学生")
	@ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") })
	@PostMapping // 新增
	public ResponseEntity<Student> save(//@ApiParam会覆盖@RequestParam中的required = true,所以需要重新定义
			@ApiParam(required = true, value = "名称") @RequestParam(required = true) String name,
			@ApiParam(required = true, value = "年龄") @RequestParam(required = true) Integer age) {
		s.setId(1);
		s.setName(name);
		s.setAge(age);
		HttpHeaders headers = new HttpHeaders();
		URI location = URI.create("http://localhost:8080/students/" + s.getId());
		headers.setLocation(location);
		return new ResponseEntity<Student>(s, headers, HttpStatus.CREATED);
	}

	@ApiOperation(value = "删除学生")
	@DeleteMapping(value = "/{id}") // 删除
	public ResponseEntity<Student> delete(@PathVariable(required = true) Integer id) {
		return new ResponseEntity<Student>(s, HttpStatus.OK);
	}

	@GetMapping(value = "/{id}") // 获取
	public ResponseEntity<Student> query(@PathVariable(required = true) Integer id) {
		return new ResponseEntity<Student>(s, HttpStatus.OK);
	}

	@PutMapping(value = "/{id}") // 修改
	public ResponseEntity<Student> update(@PathVariable(required = true) Integer id,
			@ApiParam(required = true, value = "名称") @RequestParam(required = true) String name,
			@ApiParam(required = true, value = "年龄") @RequestParam(required = true) Integer age) {
		s.setName(name);
		s.setAge(age);
		return new ResponseEntity<Student>(s, HttpStatus.OK);
	}
}

访问http://localhost:8080/springmvc/swagger-ui.html 可以得到如下界面
在这里插入图片描述

遇见的问题:

swagger的高版本中要求@PathVariable有name属性,低版本的spring只有value属性,所以这里使用相对较高的版本,不过高版本中springmvc的WebMvcConfigurerAdapter 已经废弃,在替代方案中只有WebMvcConfigurer能顺利读出swagger配置WebMvcConfigurationSupport不行
springmvc相关参考springmvc配置

发布了36 篇原创文章 · 获赞 5 · 访问量 5352

猜你喜欢

转载自blog.csdn.net/weixin_43060721/article/details/87923781