如何将Html输入值(Html表单)传递给java控制器? - Spring MVC

时间:2017-06-03 12:18:29

标签: spring spring-mvc

我想在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>

1 个答案:

答案 0 :(得分:3)

使用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:

中更改表单的动作URL
<form action="/authenticate">

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

<url-pattern>/url-pattern>