1. 程式人生 > >Spring MVC中使用Swagger生成API文件和完整專案示例Demo,swagger-server-api

Spring MVC中使用Swagger生成API文件和完整專案示例Demo,swagger-server-api

package cn.fansunion.swagger.serverapi.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

/**
 * 小雷FansUnion-一個有創業和投資經驗的資深程式設計師-全球最大中文IT社群CSDN知名博主-排名第119
 * 部落格:http://blog.csdn.net/fansunion
 *
 */
@Api(value = "user", description = "使用者管理", produces = MediaType.APPLICATION_JSON_VALUE)
@Controller
@RequestMapping("user")
public class UserController {

	// 列出某個類目的所有規格
	@ApiOperation(value = "獲得使用者列表", notes = "列表資訊", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public Result<User> list(
			@ApiParam(value = "分類ID", required = true) @RequestParam Long categoryId,
			@ApiParam(value = "分類ID", required = true) @RequestParam Long categoryId2,
			@ApiParam(value = "token", required = true) @RequestParam String token) {
		Result<User> result = new Result<User>();
		User user = new User();
		result.setData(user);
		return result;
	}

	@ApiOperation(value = "新增使用者", notes = "獲取商品資訊(用於資料同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	// @RequestBody只能有1個
	// 使用了@RequestBody,不能在攔截器中,獲得流中的資料,再json轉換,攔截器中,也不清楚資料的型別,無法轉換成java物件
	// 只能手動呼叫方法
	public Result<String> add(@RequestBody User user) {
		String u = findUser(user);
		System.out.println(u);
		return null;
	}

	@ApiOperation(value = "update使用者", notes = "獲取商品資訊(用於資料同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	public Result<String> update(User user) {
		String u = findUser(user);
		System.out.println(u);
		return null;
	}

	private String findUser(User user) {
		String token = user.getToken();
		return token;
	}
}