从JSP获取隐藏值的不同方法

时间:2017-05-27 15:50:31

标签: javascript java spring jsp spring-mvc

您好我需要在我的控制器中获取表单中的一个隐藏值。我怎么才能得到它。请在下面找到我的代码。我需要在我的控制器中获取隐藏值的值

@RequestMapping("/submitAdmissionForm.html",method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(@RequestParam("studentName") String name, @RequestParam("studentHobby") String hobby) {

    ModelAndView model = new ModelAndView("AdmissionSuccess");
    model.addObject("msg","Details submitted by you:: Name: "+name+ ", Hobby: " + hobby);

    return model;
}

`

JSP页面

<html>
<body>
	<h1> STUDENT ADMISSION FORM FOR ENGINEERING COURSES</h1>

	<form action="/submitAdmissionForm.html" method="post">
		<p>
			Student's Name : <input type="text" name="studentName" />
		</p>
		<p>
			Student's Hobby : <input type="text" name="studentHobby" />
		</p>
			<input type="hidden" id="Student" value="Sree" />
		<input type="submit" value="Submit this form by clicking here" />
	</form>
 
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您的隐藏字段没有name属性,因此无法提交。

您可以执行以下操作。

一个。替换此

<input type="hidden" id="Student" value="Sree" />

<input type="hidden" id="Student" name="Student" value="Sree" />

B中。在控制器方法中添加一个新参数:

@RequestParam("Student") String hiddenStudent

它将包含该隐藏字段的提交值。

答案 1 :(得分:0)

只需要在输入中添加name属性,这与Spring(更干净)的方式相同:

//Send to form
@GetMapping("/StudentForm")
public String studentForm(Model model) {

   model.addAttribute("student", new Student());

    return "student-form";
}

Jsp页面:

<form:form method="POST" modelAttribute="student" action="/submitAdmissionForm.html">
    <table>
        <tr>
            <td>Name: <form:input path="studentName" /></td>
        </tr>
        <tr>
            <td>Hobby: <form:input path="studentHobby" /></td>
        </tr>
        <tr>//for example there another student property but it will be hidden
            <td><form:hidden path="studentNickname" value="${Sree}" /></td>
        </tr>
        <tr>
            <td><input type="submit" /></td>
        </tr>
    </table>
</form:form>

Spring Controller:

@PostMapping("/submitAdmissionForm.html")
public String submitAdmissionForm(@ModelAttribute("student") Student student, Model model) {
      if(studen != null) {
           model.addObject("msg","Details submitted by you:: Name:"+student.getName()+ ", Hobby: " + student.getHobby() + "Nickname :" + student.getNickname());
      }
    return "success-form";
}