简单后台登录逻辑实现Controller

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,两者不一致就会报该错误。

posted on 2019-09-30 22:23  行之间  阅读(3290)  评论(0编辑  收藏  举报