java - spring出错时保留textbox的值

标签 java spring jsp controller

我正在开发一个网络应用程序。在该应用程序中,我有一个页面,其中包含三个基于 id 的搜索选项。如果 ID 错误,我想在搜索文本框中保留 ID,并显示错误消息。我试过了

ModelAndView.addObject("id", value);

这工作正常,现在我想知道是否有更好的方法来做到这一点,因为假设我有一个大表单并且我想保留每个字段的值,而不是使用上述方法。请帮忙!

我正在使用 ID 和名称搜索,这就是为什么我有 try 和 catch block

这是我的jsp文件

    html>
    <head>
        <link rel="stylesheet" type="text/css" href="./css/style.css" />
        <link rel="stylesheet" type="text/css" href="./bootstrap/css/bootstrap.css" />
        <link rel="stylesheet" type="text/css" href="./bootstrap/css/bootstrap.min.css" />
        <link rel="stylesheet" type="text/css" href="./bootstrap/css/bootstrap-responsive.css" />
        <link rel="stylesheet" type="text/css" href="./bootstrap/css/bootstrap-responsive.min.css" />
        <script>
            function redirectToSearchResult(textBoxId){
                window.location.href= document.getElementById(textBoxId).name+'.htm?'+'id='+document.getElementById(textBoxId).value;
            }
        </script>
    </head>
    <body>
        <div class="page-header"></div>

        <div id="searchByBuyer">
            <label id="E_B_I"><h2>Buyer Search<h2></label><br>
            <input type="text" id="S_B_B" class="text-box" name="searchByBuyer" value=${buyerId} ></input>
            <input type="button" id="BuyerSearch" class="btn-custom" value="search" onclick="redirectToSearchResult('S_B_B')"/>
        </div>

        <div id="searchByCategory">
            <label id="E_C_I"><h2>Category Search<h2></label><br>
            <input type="text" id="S_B_C" class="text-box" name="searchByCategory" value=${categoryId} ></input>
            <input type="button" id="CategorySearch" class="btn-custom" value="search" onclick="redirectToSearchResult('S_B_C')"/>
        </div>

        <div id="searchByArticle">
            <label id="E_A_I"><h2>Article Search<h2></label><br>
            <input type="text" id="S_B_I" class="text-box" name="searchByArticle" value=${articleId} ></input>
            <input type="button" id="ArticleSearch" class="btn-custom" value="search" onclick="redirectToSearchResult('S_B_I')"/><br>
        </div>

        <br>
        <label style="color:red; padding-left:45em; padding-top:15em"><h4>${error}</h4></label>
     </body>

</html>

这是我的 Controller

`

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class BuyerController {

    @Autowired
    private BuyerRepo buyerRepo;

    @RequestMapping(value = "/searchByBuyer.htm", method = RequestMethod.GET)
    public ModelAndView searchFields(@RequestParam(value = "id") String buyerId) throws InvalidIdException {
        Buyer buyer = null;
        ModelAndView buyerSearch = new ModelAndView("buyerSearch");
        ModelAndView errorView = ErrorView.getErrorView("buyerId", buyerId, "Enter a valid Buyer id!");

        try {
            buyer = buyerRepo.getBuyer(Long.parseLong(buyerId));

        } catch (NumberFormatException e) {
            buyer = buyerRepo.getBuyer(buyerId);
            if (buyer == null) return errorView;

        } catch (Exception e) {
            buyerSearch = errorView;
        }

        buyerSearch.addObject("buyer", buyer);
        return buyerSearch;
    }

}

`

这是错误和 View 类,用于创建带有参数的错误 View

`

import org.springframework.web.servlet.ModelAndView;

public class ErrorView {

    public static ModelAndView getErrorView(String key, String value, String message) {
        ModelAndView errorView = new ModelAndView("index");
        errorView.addObject("error", message);
        errorView.addObject(key, value);
        return errorView;
    }
}

`

最佳答案

Spring 为 Web 表单提供 JSR 303-Bean-Validation 支持。 这种构建方式比一些自己的实现更容易使用。

您需要:

  • 从表单获取所有值的命令对象。每个字段都可以有 JSR 303-Bean-Validation 注释来指示您想要强制执行的约束
  • 您需要一个具有(至少)两个参数的 Web Controller 方法:@Valid命令对象,BindingResult (BindingResult必须是命令对象后面的参数)
  • 在您的网络 Controller 方法中,您需要检查 BindingResult ,如果失败则需要再次渲染表单
  • 在您的表单中,您需要使用 form:errors显示错误( form:errors 也可以显示特定字段的错误)
  • 您需要一些 spring 配置:<mvc:annotation-driven /> (还有更多可能,但这对于开始来说应该足够了)
  • 您需要一个 JSR 303-Bean-Validation 库,例如:Hibernate Validator(这不是 Hibernate ORM)

但是一个例子可以最好地解释它: http://www.mkyong.com/spring-mvc/spring-3-mvc-and-jsr303-valid-example/

关于java - spring出错时保留textbox的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16557408/

相关文章:

java - Netbeans 无法启动 Tomcat

java - 在java中读取陷入循环的文本文件

java - 如何在 Struts 2 中将 WAR 和 JAR 文件打包成 EAR

java - 当方向改变时,EditTexts 不起作用?

java - 如何找到数组中最大的增量?

java - JHipster 后端 - 社交登录

spring - AppEngine + CloudSQL + hibernate : @Transactional is forbidden

java - 托管在 Heroku 上的 Spring Boot 项目 - Web 进程在启动后 90 秒内无法绑定(bind)到 $PORT

java - 自动下载库更新

Java配置Web应用程序的上下文根