Simple background login logic implementation 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";
    }

}

wrong description

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]

Error Analysis

Cause: The form may be presented in a way to get the default request, and background processing the request Controller dealing PostMapping, they do not agree it will report the error.

Guess you like

Origin www.cnblogs.com/zxfei/p/11614363.html