第4节 一个要求携带cookies信息访问的get接口开发
/**
* 这是一个需要携带cookies信息才能访问的get请求
*/
@RequestMapping(value = "get/with/cookies", method = RequestMethod.GET)
public String getWithCookies(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return "no cookies with get method";
}
for (Cookie cookie : cookies) {
if (cookie.getName().equals("login") && cookie.getValue().equals("true")) {
return "这是一个需要携带cookies信息才能访问的get请求";
}
}
return "cookies info wrong";
}
启动springboot后访问“http://localhost:8080/get/with/cookies”
第一次访问没有cookies信息,第二次携带cookie信息
第5节 需要携带参数的get请求的两种开发方式
方法一:
/**
* 开发一个需要携带参数才能访问的get请求
* 第一种实现方式:url:key=value&key=value
* 我们来模拟获取商品列表
*/
@RequestMapping(value = "/get/with/param", method = RequestMethod.GET)
public Map<String, Integer> getList(@RequestParam Integer start,
@RequestParam Integer end) {
Map<String, Integer> myLsit = new HashMap<String, Integer>();
myLsit.put("鞋子", 400);
myLsit.put("方便面", 5);
myLsit.put("口红", 300);
return myLsit;
}
方法二:
/**
* 开发一个需要携带参数才能访问的get请求
* 第二种实现方式:url:url:port/get/with/param/10/20
* 我们来模拟获取商品列表
*/
@RequestMapping(value = "/get/with/param/{start}/{end}", method = RequestMethod.GET)
public Map<String, Integer> getMyList(@PathVariable Integer start,
@PathVariable Integer end) {
Map<String, Integer> myLsit = new HashMap<String, Integer>();
myLsit.put("鞋子", 400);
myLsit.put("方便面", 5);
myLsit.put("口红", 300);
return myLsit;
}
扩展---一个携带参数和cookie才能访问的get方法
/**
* 开发一个需要携带参数和cookies才能访问的get请求
* 我们来模拟用户使用用户名和密码登录
*/
@RequestMapping(value = "/get/with/paramAndCookie", method = RequestMethod.GET)
public String login(HttpServletRequest request,
@RequestParam String name,
@RequestParam String password) {
Cookie[] cookies = request.getCookies();
if (cookies == null) {
return "请配置cookie信息";
}
for (Cookie cookie : cookies) {
if (cookie.getName().equals("login") & cookie.getValue().equals("true")) {
if (name.equals("zhangsan") && password.equals("123456")) {
return "zhangsan 登录成功";
} else if (name.equals("zhangsan") && !password.equals("123456")) {
return "密码错误请重试";
} else {
return "请注册再登录";
}
}
}
return "请注册再登录";
}
重启springboot后访问该接口