当前位置: 首页 > 知识库问答 >
问题:

BindingResult和bean名称xxx的普通目标对象都不能用作请求属性

严宸
2023-03-14

“bean名称'login command'的BindingResult和普通目标对象都不能作为请求属性使用”

这是我新项目的第一个控制器,我在处理xml时遇到了一些问题。我想那都解决了,但如果什么都没看到,我想问题可能就在那里。奇怪的是,所有这些代码几乎都是直接从我的另一个项目复制的,而且它工作得很好。

而且,如果这一点重要的话,我正在运行glassfish。提前道谢!

编辑:网页是/morencore/login.jsp。我试着转到login.html,假设这会带来它,但似乎只有转到login.jsp时才起作用。我相信我尝试更改我的控制器以映射到jsp,但这不起作用。

<form:form method="post" modelAttribute="loginCommand">

    <form:errors cssClass="error" element="p" />

    <table border="0">
        <tr>
            <td align="right">Username:</td>
            <td><form:input path="userName" /> <form:errors path="userName" cssClass="error" /></td>
        </tr>
        <tr>
            <td align="right">Password:</td>
            <td><form:password path="password" /> <form:errors path="password" cssClass="error" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" id="submit" name="submit" value="Log In" disabled="disabled"></td>
        </tr>
    </table>

</form:form>
@Controller
@ControllerAdvice
@RequestMapping("/login.html")
public class LoginController {

    protected final Logger logger = LogManager.getLogger(getClass());

    @Autowired
    protected LoginValidator loginValidator;

    @RequestMapping(method= RequestMethod.GET)
    protected String initializeForm(@ModelAttribute("loginCommand")LoginCommand loginCommand,
                                    BindingResult result,
                                    ModelMap model)
    {
        logger.info("INITIALIZING LOGIN FORM");
        model.addAttribute("loginCommand", new LoginCommand());
        return "login";
    }

    @InitBinder("loginCommand")
    protected void initBinder(ServletRequestDataBinder binder) throws Exception
    {
        binder.addValidators(loginValidator);
    }

    @RequestMapping(method=RequestMethod.POST)
    protected String onSubmit(@ModelAttribute("loginCommand")LoginCommand loginCommand,
                              BindingResult result,
                              HttpServletRequest request) throws Exception
    {
        logger.info("validating login input");
        loginValidator.validate(loginCommand, result);

        if (result.hasErrors())
        {
            result.reject("login.failure");
            return "login";
        }
        UserDao userDao = new UserDao();
        User user = userDao.by_name(loginCommand.getUserName());
        if (user == null
                || !user.getName().equals(loginCommand.getUserName())
                || !user.getPassword().equals(loginCommand.getPassword()))
        {
            result.reject("login.failure");
            return "login";
        }
        return "redirect:main.html";
    }
}

下面是我的LoginCommand类:

@XmlRootElement
public class LoginCommand
{
    private String userName;
    private String password;

    /** blah blah blah getters and setters*/
}

下面是请求的完整堆栈跟踪:

Neither BindingResult nor plain target object for bean name 'loginCommand' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'loginCommand' available as request attribute
        at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:142)
        at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
        at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
        at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
        at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
        at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
        at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
        at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
        at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
        at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
        at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
        at org.apache.jsp.login_jsp._jspx_meth_form_input_0(login_jsp.java:233)
        at org.apache.jsp.login_jsp._jspService(login_jsp.java:126)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:338)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)

共有1个答案

鄢承运
2023-03-14

在其他事情中,似乎您的映射需要修改。这是我会尝试的。有很多调整,所以不能保证它是否会完全工作,但它应该让你在正确的方向。

@Controller
public class LoginController {

    protected final Logger logger = LogManager.getLogger(getClass());  //look at SLF4J instead.  Then you're not tied to a specific logger and you use a facade.

    @Autowired //may want to use constructor wiring instead on these
    private LoginValidator loginValidator;

    @Autowired
    private UserDao userDao; //this should be wired and not simply instantiated - Spring won't know about it otherwise

    @Autowired
    private LoginValidator loginValidator;

    @GetMapping("/login")
    public String initializeForm(Model model) {
        logger.info("INITIALIZING LOGIN FORM");
        model.addAttribute("loginCommand", new LoginCommand());
        return "login";
    }

    @PostMapping("/loginPost")
    public String onSubmit(@ModelAttribute("loginCommand") LoginCommand loginCommand,
                            BindingResult result) throws Exception {

        logger.info("validating login input");
        loginValidator.validate(loginCommand, result);

        if (result.hasErrors()) {
            result.reject("login.failure");
            return "login";
        }

        User user = userDao.by_name(loginCommand.getUserName());
        if (user == null
                || !user.getName().equals(loginCommand.getUserName())
                || !user.getPassword().equals(loginCommand.getPassword())) { //you should really refactor this and move it outside of your controller.  Just keep routing code in your controller, not logic

            result.reject("login.failure");
            return "login";
        }
        return "main"; //you should return just "main" or redirect:/main depending on what you're trying to do - you want the JSP to be processed.  Leaving off the extension allows you to change frameworks without changing the server-side code and allows the page to be compiled.  You could switch to Thymeleaf, for example, and not touch any of this code.
    }
}

向窗体中添加操作:

<form:errors cssClass="error" element="p" />

<table border="0">
    <tr>
        <td align="right">Username:</td>
        <td><form:input path="userName" /> <form:errors path="userName" cssClass="error" /></td>
    </tr>
    <tr>
        <td align="right">Password:</td>
        <td><form:password path="password" /> <form:errors path="password" cssClass="error" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center"><input type="submit" id="submit" name="submit" value="Log In"></td>
    </tr>
</table>

对于下一个阅读代码的开发人员,我会将logincommand重命名为更接近实际的东西--比如userdetailsadapter或类似的东西。我假设logincommand将从Spring Security实现userdetails(如果您正在使用)。

您可能还想考虑更新userDAO,使方法称为findoNebyusername而不是by_name。命名约定可以帮助您以后使用Spring存储库。

最后,看看龙目岛项目。这样你就不用头疼了。

 类似资料: