package com.fei.controller.admin;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.fei.po.User;
import com.fei.service.UserService;
/**
* Created by zxf on 2019年9月30日
*/
@Controller
@RequestMapping("/admin")
public class LoginController {
@Autowired
private UserService userService;
/**
* 登錄方法
*
* @param username
* @param password
* @param session
* @param attributes
* @return
*/
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password, HttpSession session,
RedirectAttributes attributes) {
User user = userService.login(username, password);
if (user != null) {
user.setPassword(null);
session.setAttribute("user", user);
return "redirect:/admin/index";
} else {
attributes.addFlashAttribute("message", "用戶名或密碼錯誤!");
return "redirect:/admin";
}
}
/**
* 注銷方法
*
* @param session
* @return
*/
@PostMapping("/logout")
public String logout(HttpSession session) {
session.removeAttribute("user");
return "redirect:/admin";
}
/**
* 去登錄頁
*
* @return
*/
@GetMapping
public String toLogin() {
return "admin/login";
}
/**
* 去后台首頁
*
* @return
*/
@GetMapping("/index")
public String toIndex() {
return "admin/index";
}
}
錯誤描述
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:200) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
錯誤分析
錯誤原因:可能是表單的提交方式為默認的get請求,而后台處理該請求的Controller處理的是PostMapping,兩者不一致就會報該錯誤。