问题描述
我有这个html弹簧形式:
I have this html spring form:
<form:form action="addVacancy" modelAttribute="myVacancy">
<form:label path="name">name</form:label>
<form:input path="name" ></form:input>
<form:errors path="name" cssClass="error" />
<br>
<form:label path="description">description</form:label>
<form:input path="description" id="nameInput"></form:input>
<form:errors path="description" cssClass="error" />
<br>
<form:label path="date">date</form:label>
<input type="date" name="date" />
<form:errors path="date" cssClass="error" />
<br>
<input type="submit" value="add" />
</form:form>
我通过这种方法处理此表格:
I handle this form by this method:
@RequestMapping("/addVacancy")
public ModelAndView addVacancy(@ModelAttribute("myVacancy") @Valid Vacancy vacancy,BindingResult result, Model model,RedirectAttributes redirectAttributes){
if(result.hasErrors()){
model.addAttribute("message","validation error");
return new ModelAndView("vacancyDetailsAdd");
}
vacancyService.add(vacancy);
ModelAndView mv = new ModelAndView("redirect:goToVacancyDetails");
mv.addObject("idVacancy", vacancy.getId());
redirectAttributes.addAttribute("message", "added correctly at "+ new Date());
return mv;
}
如何提出相同的请求,该请求是在提交表单后获得的.这必须通过MockMvc来完成.
How to make the same request, which is obtained after submitting the form. This must be done by means of MockMvc.
@Test
public void testMethod(){
MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/addVacancy");
//what must I write here?
ResultActions result = mockMvc.perform(request);
}
我很困惑.
推荐答案
当浏览器需要提交表单时,通常会将表单<input>
字段序列化为url编码的参数.因此,当您要模拟HttpServletRequest
时,需要将那些相同的参数添加到请求中.
When a browser needs to submit a form, it typically serializes the form <input>
fields as url-encoded parameters. Therefore, when you want to mock an HttpServletRequest
, you need to add those same parameters to the request.
request.param("name", "some value")
.param("description", "description value")
.param("date", "some acceptable representation of date");
DispatcherServlet
将使用这些参数来创建一个Vacancy
实例,并将其作为参数传递给您的处理程序方法.
The DispatcherServlet
will use these parameters to create a Vacancy
instance to pass as an argument to your handler method.
这篇关于如何使用MockMvc传递ModelAttrubute参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!