【问题标题】:How to Pass Html Input value(Html Form) to java controller ? - Spring MVC如何将 Html 输入值(Html 表单)传递给 java 控制器? - 弹簧MVC
【发布时间】:2017-11-04 17:53:48
【问题描述】:

我想在 Spring MVC 中使用普通 Html 标签而不是 Spring Html 标签 但我无法使用简单的 html 标签获取 Controller 的输入值。

以下是我的代码:-

控制器:

@Controller
public class LoginService {

    @RequestMapping(value = "/authenticate", method = RequestMethod.GET)
    public String authenticateUser(Model model,@ModelAttribute("userName") String userName, 
            @ModelAttribute("password") String password) {
        System.out.println("coming in controller    " +userName +" : "+ password);  
        model.addAttribute("message", "Hello Spring MVC Framework!");
        return "success";
    }

JSP:

<body>
<h2>${message}</h2>
<form action="authenticate.htm">
    <table>
        <caption>
            <h3>Enter Your Login Credentials</h3>
        </caption>
        <tr>
            <td>User Name</td>
            <td><input type="text" id="userName"></input></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input type="password" id="password"></input></td>
        </tr>
        <tr rowspan="2">
            <td><input type="submit"></input></td>
        </tr>
    </table>
</form>

web.xml

   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>*.htm</url-pattern>
   </servlet-mapping>

【问题讨论】:

    标签: spring spring-mvc


    【解决方案1】:

    使用RequestParam 代替ModelAttribute

    @RequestMapping(value = "/authenticate", method = RequestMethod.GET)
        public String authenticateUser(@RequestParam("userName") String userName, @RequestParam("password") String password ,Model model) {
            System.out.println("coming in controller    " +userName +" : "+ password);  
            model.addAttribute("message", "Hello Spring MVC Framework!");
            return "success";
        }
    

    你必须在jsp中更改表单的action url:

    <form action="/authenticate">
    

    使用以下行更新您的 web.xml:

    <url-pattern>/url-pattern>
    

    【讨论】:

    • 我正在获取 Http 404“HTTP 状态 400 - 所需的字符串参数 'userName' 不存在”并且描述是“客户端发送的请求在语法上不正确(所需的字符串参数 'userName' 不存在现在)。”
    • 清除浏览器缓存并尝试更新代码
    • 我清除了缓存并再次运行项目而没有更改表单操作..但它显示相同的异常
    • 如果我修改了表单操作,它们当前的 servlet 映射将不起作用......对吗?
    • 请将“名称”设置为所有输入类型文本并使用它。示例:
    猜你喜欢
    • 1970-01-01
    • 2018-12-01
    • 2012-11-24
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多