【问题标题】:Getting the value from simple JSP spring MVC page从简单的 JSP spring MVC 页面获取价值
【发布时间】:2023-03-07 15:10:01
【问题描述】:

我通过 MVC 模板创建了 Spring MVC 项目,但我无法从文本输入中获取值。有人可以建议我怎么做吗?带有项目结构的 home.jsp 的源代码可以在下面的屏幕截图中看到。 AdminController 类的代码是:

@Controller
@RequestMapping(value = "/foo")
public class AdminController {

@RequestMapping(value = "/bar")
public String testAction(@RequestParam String fieldName) {
    // yourValue contain the value post from the html form
    return "yourview";
    }
}

当我部署项目时,它从地址 http://localhost:8080/test/ 开始。在哪里将/test/ 更改为其他内容?在点击提交按钮后,浏览器转发到http://localhost:8080/foo/bar 并显示HTTP status 404

【问题讨论】:

    标签: java spring jsp model-view-controller


    【解决方案1】:

    404:

    你的表单映射是绝对的

    <form ... action="/foo/bar">
    

    这就是为什么它会命中 http://localhost:8080/foo/bar 并且您没有部署上下文路径为 /foo 因此是 404 的应用程序。

    要更正此问题,请使用 spring 为您添加上下文路径:

    <spring:url value="/foo/bar" var="form_url" />
    <form ... action="${form_url}" method="POST">
    

    字段名:

    您需要确定要映射到 testAction 参数的请求参数。

    @RequestMapping(value = "/bar", method=RequestMethod.POST)
    public String testAction(@RequestParam(value="fieldName") String fieldName) {
      // yourValue contain the value post from the html form
      return "yourview";
    }
    

    /测试:

    看起来您正在使用 Tomcat 服务器来运行应用程序。这可能在 pom.xml 中配置为使用 /${project.artifactId} (默认)启动应用程序,其中您的工件 ID 为“test”。 (http://mojo.codehaus.org/tomcat-maven-plugin/run-mojo.html#path)。您可以通过配置 maven 插件来提供不同的值:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>tomcat-maven-plugin</artifactId>
        <configuration>
          <path>WHATEVER</path>
        </configuration>
      </plugin>
    

    【讨论】:

      【解决方案2】:

      查看您在此处发布的图片。您的控制器请求映射是 /bar,而您形成的动作被称为 /foo/bar。看看这是不是错误。为spring action方法提供request方法。

      由于您使用 URL localhost:8080/foo/bar 访问应用程序,因此我建议您对其进行一些更改。

      从控制器中移除 RequestMapping 标签。应该是:

      @Controller    
      public class AdminController {
      
          @RequestMapping(value = "bar", method=RequestMethod.POST)
          public String testAction(@RequestParam String fieldName) {
            // yourValue contain the value post from the html form
             return "yourview";
          }
      }
      

      并给出表单动作名称,如 action="bar"。

      【讨论】:

      • thanks... 重定向到其他页面现在可以正常工作:) 但是如何在重定向到其他页面后从 打印文本,这要归功于点击提交按钮?
      • 你在 testAction 方法中得到那个值吗?我想如果您要发布表单,则需要在 POJO 中包含这些字段。
      • 是的,我明白了,但我希望会有一些更好的解决方案,比如我从 JSF 知道的 ManagedBeans 的使用......无论如何 :) 非常感谢 :)跨度>
      猜你喜欢
      • 2017-05-12
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多