【发布时间】:2013-12-27 04:13:30
【问题描述】:
我的 Spring 控制器如下所示:
@Controller
@RequestMapping(value = "calc")
public class CalcController {
protected final Log logger = LogFactory.getLog(getClass());
@Autowired
private MyService myService;
@RequestMapping(method = RequestMethod.GET)
public String showCalcPage(
@ModelAttribute("myModel") MyModel myModel,
Model model, HttpServletRequest request) {
// assemble page
return "calc";
}
@RequestMapping(method = RequestMethod.POST)
public String showResultsPage(
@ModelAttribute("myModel") MyModel myModel,
BindingResult result, Model model,
final RedirectAttributes redirectAttributes,
HttpServletRequest request) {
myService.evaluate(myModel);
redirectAttributes.addFlashAttribute("myModel", myModel);
model.addAttribute("myModel", myModel);
return "redirect:calc/results";
}
@RequestMapping(value = "/results")
public String showResultsPage(ModelMap model,
@ModelAttribute("myModel") final MyModel myModel,
final BindingResult bindingResult) {
// assemble page
return "results";
}
}
我有一个包含 GET 和 POST 的 URL calc 的映射以及另一个用于 calc/results 的映射。
这对我来说非常有效,但每当我尝试直接访问 calc/results 时,页面仍然呈现。
因此我对其RequestMethod 进行了POST 限制,例如:
@RequestMapping(value = "/results", method = RequestMethod.POST)
public String showResultsPage(ModelMap model,
@ModelAttribute("myModel") final MyModel myModel,
final BindingResult bindingResult) {
// assemble page
return "results";
}
这通过抛出 405 消除了对映射的直接查看,但是当我从 calc 提交表单时,错误仍然存在。
我该如何合并这两种情况?
我实际上只想要两个像下面这样的控制器来实现 POST 和页面限制,但它在我的部分不起作用(我将它诊断为 jsp 的不同映射)。
@Controller
@RequestMapping(value = "calc")
public class CalcController {
protected final Log logger = LogFactory.getLog(getClass());
@Autowired
private MyService myService;
@RequestMapping(method = RequestMethod.GET)
public String showCalcPage(
@ModelAttribute("myModel") MyModel myModel,
Model model, HttpServletRequest request) {
// assemble page
return "calc";
}
@RequestMapping(value = "/results", method = RequestMethod.POST)
public String showResultsPage(
@ModelAttribute("myModel") MyModel myModel,
BindingResult result, Model model,
final RedirectAttributes redirectAttributes,
HttpServletRequest request) {
// assemble page
myService.evaluate(myModel);
model.addAttribute("myModel", myModel);
return "redirect:results";
}
}
【问题讨论】:
-
在您的表单中,您应该将方法提及为
POST。 -
@TejaKantamneni,是的,我的 jsp 表单中有一个
method="POST"属性加上一个action="calc"以映射到我的控制器。 -
action 应该是
calc/results,对吗?如果是,它应该可以工作,尝试使用 firbug 查看 http 交换,看看是什么问题 -
它现在抛出一个
HTTP 500。 -
这可能是一个不同的问题。可能的应用程序异常。
标签: java spring view controller http-status-code-405