嗨,我是Spring的新手,我在使用两个不同的控制器在两个页面之间传递数据时遇到了问题。我想知道如何处理这种情况。在我的index.html中,我有一个按钮,应该将我重定向到传递一些数据的新页面。当我单击按钮时,它会将我重定向到step2页面,但我没有对象。我怎么解决这个问题? GET方法是否正确?我是否必须使用该表单只是为了在页面和控制器之间传递一些数据?以下是我所拥有的。
的index.html
<form th:action="@{/step2}" method="GET">
<input type="hidden" th:value="${mapSelectedServices}" name="mapSelectedServices"/>
<input type="hidden" th:value="${user}" name="loggedUser"/>
<div class="form-group d-flex align-items-center justify-content-between">
<button type="submit" class="btn btn-danger btn-rounded ml-auto" >SEE PRICES
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</div>
</form>
Step2Controller
@RequestMapping(value="step2", method = RequestMethod.GET)
public ModelAndView step2(ModelAndView modelAndView, @ModelAttribute("user") User user,
@ModelAttribute("mapSelectedServices") HashMap<String,List<ServiceOffered>> mapSelectedServices,
BindingResult bindingResult){
modelAndView.addObject("user", user);
modelAndView.addObject("mapSelectedServices", mapSelectedServices);
modelAndView.setViewName("step2");
return modelAndView;
}
对不起所有的问题,但我是春天开发的新手。
HTML页面:
<form th:action="@{/step2}" method="POST">
<input type="hidden" th:value="${mapSelectedServices}" name="mapSelectedServices"/>
<input type="hidden" th:value="${user}" name="loggedUser"/>
<div class="form-group d-flex align-items-center justify-content-between">
<button type="submit" class="btn btn-danger btn-rounded ml-auto" >SEE PRICES
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</div>
</form>
控制器方法:
public ModelAndView goToPgae2(@ModelAttribute ModelClass aClass)
{
ModelAndView mv=new ModelAndView("SecondHtlmPageName");//setting view name here
mv.addAttribute("aClass",aClass);
return mv;
}
具有从一个页面传递到另一个页面的特定变量的模型类:
class ModelClass {
public Stirng mapSelectedServices; //use appropriate data type.
public String loggedUser;
//create getters and setters
}
第二页
<div>${aClass.loggedUser}</div>
DONE。
这样你就可以进入第二页。如果你想重定向到第二页并且模型属性应该可用,那么你需要使用flashattribute
。