简体   繁体   English

在Spring带注释的控制器中手动处理错误验证

[英]Manually handle error validation in Spring annotated controller

I'm trying to update a Spring controller to use annotations for a relatively simple 'change password' page. 我正在尝试更新一个Spring控制器以在相对简单的“更改密码”页面上使用注释。 The only fields on the page are 'password' and 'confirm password'. 页面上的唯一字段是“密码”和“确认密码”。 When the form is submitted, it calls to a webservice to do the actual changing of the password. 提交表单后,它会调用Web服务来实际更改密码。 That webservice may return a InvalidPasswordException based upon password rules run within that service. 该Web服务可能会根据在该服务中运行的密码规则返回InvalidPasswordException。 So I want to catch the exception, then add an error message to the view to show up next to the 'password' field. 因此,我想捕获异常,然后将错误消息添加到视图以显示在“密码”字段旁边。 The velocity code is already written using #springShowErrors, so I want to add the error in a way that in can be read in by that tag. 速度代码已经使用#springShowErrors编写,因此我想以该标签可以读取的方式添加错误。

Here is my controller: 这是我的控制器:

@Controller
@RequestMapping("/edit-password.ep")

public class EditPasswordFormControllerImpl {

@Autowired
private CustomerService customerService;
@Autowired
private CustomerSessionService customerSessionService;

@RequestMapping(method = RequestMethod.POST)
protected ModelAndView onSubmit(@ModelAttribute("editPasswordFormBean") EditPasswordFormBeanImpl editPasswordFormBean, BindingResult errors, HttpServletRequest request) throws EpWebException {

    String nextView = "redirect:/manage-account.ep";

    final CustomerSession customerSession = (CustomerSession) request.getSession().getAttribute(WebConstants.CUSTOMER_SESSION);
    final Customer customer = customerSession.getShopper().getCustomer();

    try {
        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustomerId(customer.getUserId());
        customerInfo.setPassword(editPasswordFormBean.getPassword());

        UpdateAccountServiceRequest updateRequest = new UpdateAccountServiceRequest();
        updateRequest.setClientId(CLIENT_ID);
        updateRequest.setCustomerInfo(customerInfo);

        //this is the webservice call that could throw InvalidPasswordException
        customerService.updateUserAccount(updateRequest);

    } catch (InvalidPasswordException e) {

        // This is where I'm not sure what to do.
        errors.addError(new ObjectError("password", e.getMessage()));
        nextView = "edit-password.ep";

    } catch (ServiceException e) {
        throw new EpWebException("Caught an exception while calling webservice for updating user", e);
    }

    return new ModelAndView(nextView);
}

@RequestMapping(method = RequestMethod.GET)
protected String setupForm(ModelMap model) {
    EditPasswordFormBean editPasswordFormBean = new EditPasswordFormBeanImpl();
    model.addAttribute("editPasswordFormBean", editPasswordFormBean);
    return "account/edit-password";
}
}

And here is a snippet of my velocity template: 这是我的速度模板的片段:

<fieldset>
<legend>#springMessage("editPassword.editPasswordTitle")</legend>
<table border="0" cellspacing="0" cellpadding="3">
    <colgroup>
        <col width="150">
        <col width="*">
    </colgroup>
    <tr>
        <td colspan="2">
            <br />
            <strong>#springMessage("editPassword.changePassword")</strong>
        </td>
    </tr>
    <tr>
        <td align="right">#springMessage("editPassword.password")</td>
        <td>
            #springFormPasswordInput("editPasswordFormBean.password" "maxlength='100'")
            #springShowErrors("<br>" "req")
        </td>
    </tr>
    <tr>
        <td align="right">#springMessage("editPassword.confirmPassword")</td>
        <td>
            #springFormPasswordInput("editPasswordFormBean.confirmPassword" "maxlength='100'")
            #springShowErrors("<br>" "req")
        </td>
    </tr>
</table>
</fieldset>

I'm not quite sure what I should do when I catch the exception. 我不太确定遇到异常时应该怎么做。 What I currently have doesn't work. 我目前所拥有的不起作用。 It returns to the edit-password page, but no error displays. 它返回到编辑密码页面,但是没有错误显示。 I've read about HandleExceptionResolver, but even if I use that, I'm still not sure how to get the error to display on the view. 我已经阅读了有关HandleExceptionResolver的信息,但是即使我使用了它,我仍然不确定如何使错误显示在视图上。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

Jeff, its just a guess, if you see the controller you have the RequestMapping("/edit-password.ep"), so when there is an error scenario your next view is "edit-password.ep", so it will come to this controller and it will be consdiered as a get request to the controller. 杰夫,这只是一个猜测,如果您看到控制器具有RequestMapping(“ / edit-password.ep”),那么当出现错误情况时,您的下一个视图是“ edit-password.ep”,因此它将出现到此控制器,它将被视为对控制器的获取请求。 But in your GET mapping method you are always creating a new EditPasswordBean and sending back to the back. 但是,在您的GET映射方法中,您始终会创建一个新的EditPasswordBean并将其发送回。 If you run the server in debug mode and keep a break point in setUpForm method you will why the errors have been swallowed. 如果以调试模式运行服务器,并在setUpForm方法中保留断点,则说明为什么错误会被吞没。 Try to give specific mappings for get and post to avoid such issues. 尝试为get和post提供特定的映射,以避免此类问题。 Ideally you should a Validator defined and it should be registered in your initBinder method. 理想情况下,您应该定义一个验证器,并且应该在您的initBinder方法中注册它。 Check out this link http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html Hope it helps. 查看此链接http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM