logincontroller.java_简单后台登录逻辑实现Controller

这是一个关于如何使用Spring MVC实现后台登录逻辑的示例。`LoginController`类包含了登录和注销的方法,通过`UserService`进行用户验证。当用户名或密码错误时,会返回错误信息。错误分析部分指出,如果请求方式与Controller处理方法不匹配,如GET请求尝试访问POST映射的方法,会导致HttpRequestMethodNotSupportedException。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值