【问题标题】:spring process POST data - annotate the right controllerspring 处理 POST 数据 - 注释正确的控制器
【发布时间】:2013-03-07 16:17:07
【问题描述】:

我在配置 spring MVC 以在正确的控制器中处理表单 POST 数据时遇到问题。我有一个 add 操作,它将向数据库添加一条新记录。

提交表单后,我收到 404 错误 (http://localhost:8084/lyricsBase/song/submit.html),所以我想我在提交表单时出错了。

这是我的控制器代码:

public class SongController extends MultiActionController {

    [...]
    @RequestMapping(value = "/song/submit.html", method = RequestMethod.POST)
    public ModelAndView submit(@RequestParam("song") Song song) throws Exception {
        HashMap model = new HashMap();
        model.put("song", song);
        // or do something better here...
        return new ModelAndView("t.edit", model);
    }

这是视图表单标签:

<form:form method="POST" commandName="song" action="submit.html">

我的应用程序代码可在github 上找到。以下是重要文件:the form viewcontroller(该类是一个多控制器,因为我不想为每个操作创建单独的文件)和servlet configuration

不知道这是否重要,但我正在为视图层使用图块(tiles.xml 中使用了逻辑视图名称)。

此外,我并不完全了解 Spring 路由的工作原理。到目前为止,我在servlet xml中定义了一个映射,但不知道这是否是一个好方法......

【问题讨论】:

  • 请将相关代码sn-ps添加到您的问题中。
  • @KeesdeKooter 重要代码 sn-ps 添加。
  • 如果您使用 @RequestMapping 注解映射您的请求,则无需在您的 servlet.xml 中映射它。
  • 在浏览器调试工具中检查提交表单时调用的 url。是 /song/submit.html 吗?

标签: java forms spring request


【解决方案1】:

歌曲的发布价值是多少?我不确定 Spring 是否将发布的数据转录或反序列化为对象/实体。 你可以尝试改变;

@RequestMapping(value = "/song/submit.html", method = RequestMethod.POST)
public ModelAndView submit(@RequestParam("song") Song song) throws Exception {

进入

@RequestMapping(value = "/song/submit.html", method = RequestMethod.POST)
public ModelAndView submit(@RequestParam("song") String song) throws Exception {

看看有没有收到。

另一种方式,是从请求对象中读取参数;

@RequestMapping(value = "/song/submit.html", method = RequestMethod.POST)
public ModelAndView submit(HttpServletRequest request) throws Exception {

Object song = request.getParameter("song");

Gl!

【讨论】:

    【解决方案2】:

    如果您的应用程序 URL 是:

    http://localhost:8084/lyricsBase/song/submit.html
    

    请求映射应该是这样的(删除映射中的第一个'/'):

    @RequestMapping(value = "song/submit.html", method = RequestMethod.POST)
    public ModelAndView submit(@ModelAttribute("song") Song song) throws Exception {
    }
    

    jsp中的form标签应该是:

    <form:form method="POST" commandName="song" action="song/submit.html">
    

    【讨论】:

      【解决方案3】:

      试试这个,把@RequestParam("song")改成@RequestBody

      【讨论】:

        猜你喜欢
        • 2017-02-24
        • 1970-01-01
        • 2016-01-27
        • 1970-01-01
        • 2020-09-26
        • 1970-01-01
        • 2011-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多