java 创建名为“HomeController”的Bean时出错:查找方法解析失败

a2mppw5e  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(149)

我在Spring MVC Controller中尝试使用@HttpSession时遇到了一些问题。我想用session将电子邮件的第一个字母从登录页面剪切到主页。为了避免在加载第一个主页时session为null,我使用了if条件,但它给出了以下错误:
创建名为“HomeController”的Bean时出错:查找方法解析失败

@Controller
@RequestMapping("/")
public class HomeController {
    @GetMapping
    @Transactional
    public String Default(@SessionAttribute("email") String email,ModelMap modelMap,HttpSession httpSession) {
        if(httpSession.getAttribute("email") != null) {
            String email =(String) httpSession.getAttribute("email");
            String chacracter = email.substring(0, 1);
            modelMap.addAttribute("chacracter ", chacracter );
        }
        return "home";
    }
}
kq0g1dla

kq0g1dla1#

请注意,为了能够将HttpSession对象直接注入到Controller方法中,如您的示例所示-只要HttpServletRequest对象已经被注入到Controller中,这就可以工作。

@Controller 
@RequestMapping("/") 
public class HomeController {

    @Autowired
    private HttpServletRequest request;

    @GetMapping
    @Transactional
    public String Default(@SessionAttribute("email") String email,ModelMap modelMap,HttpSession httpSession) {
        if(httpSession.getAttribute("email") != null) {
            String email =(String) httpSession.getAttribute("email");
            String chacracter = email.substring(0, 1);
            modelMap.addAttribute("chacracter ", chacracter );
        }
        return "home";
    }
}

相关问题