0

我刚开始使用 Spring MVC,所以这可能是一个菜鸟错误。

每个请求都会重用 ModelAttribute。如何确保每个 POST 都以干净的对象开头?

我的控制器(MyController.java):

@Controller
public class MyController {

  @RequestMapping(method = RequestMethod.POST)
  public String processChoice(@ModelAttribute("myData") MyData myData, BindingResult bindingResult) {
    System.out.println("POST: myData = " + myData);
    return "redirect:/myview?choice=" + myData.getChoice();
  }

  @RequestMapping(method = RequestMethod.GET)
  public String displayChoice(@RequestParam(required = false) String choice, Model model) {
    System.out.println("GET: Choice = " + choice);
    model.addAttribute("myData", new MyData(choice));
    return "myview";
   }

}

我的观点(myview.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring Tests</title>
  </head>
  <body>
    <form:form modelAttribute="myData" method="POST">
      <form:select path="choice">
        <option></option>
        <option value="one">One</option>
        <option value="two">Two</option>
      </form:select>
      <input type="submit" value="Choose"/>
    </form:form>
    <c:if test="${not empty myData.choice}">Choice = ${myData.choice}</c:if>
    <c:if test="${empty myData.choice}">No choice</c:if>
  </body>
</html>

连续单击“选择”按钮会附加所选值,而不是仅发布当前值:

GET: Choice = null
POST: myData = MyData [choice=two]
GET: Choice = two
POST: myData = MyData [choice=two,one]
GET: Choice = two,one
POST: myData = MyData [choice=two,one,]
GET: Choice = two,one,
POST: myData = MyData [choice=two,one,,one]
GET: Choice = two,one,,one
4

1 回答 1

0

将此添加到您的控制器中:

@ModelAttribute("myData")
public MyData getMyData() {
    return new MyData();
}
于 2013-05-03T11:35:06.620 回答