我在Spring MVC 3上有一个包含两种不同形式(有两个不同的提交)的页面,我遇到了@ModelAttribute方法的问题.当我在同一个控制器上有两个时,它们并不总是被执行,使模型为NULL.
代码:
@Controller
@RequestMapping(value = "/session/admin/permission/{userId}")
public class PermissionController {
@Autowired
private UserManager userManager;
@ModelAttribute("passwordValidation")
private PasswordValidation getPasswordModel(){
return new PasswordValidation();
}
@ModelAttribute("user")
private User getUserModel(@PathVariable("userId") String userId){
//This is not executed
return userManager.getUser(userId);
}
@ModelAttribute("permissionsAvailable")
private PermissionsAvailable getPermissionsModel(@ModelAttribute("user") User user) {
return new PermissionsAvailable();
}
@RequestMapping(method = RequestMethod.GET)
public String adminPermission(){
return "/security/permission";
}
@RequestMapping(method = RequestMethod.POST, params="changeRoles")
public String modifyPermission(@ModelAttribute("permissionsAvailable") PermissionsAvailable permissions,
HttpServletRequest request, @ModelAttribute("user") User user,
final RedirectAttributes redirectAttributes){
//Modify something
}
@RequestMapping(method = RequestMethod.POST, …Run Code Online (Sandbox Code Playgroud) 我需要将一个模型属性从控制器传递给HTML.我的应用程序使用HTML5,thymeleaf和springboot.
我使用下面的代码片段:
$(document).ready(function() {
var modelAttributeValue = '${modelAttribute}';
}
Run Code Online (Sandbox Code Playgroud)
我的控制器的代码片段:
model.addAttribute("modelAttribute", "viewEmployee")
Run Code Online (Sandbox Code Playgroud)
但是我无法在HTML中获得分配给model属性的值.
请指教.
先感谢您.
我正在为一个简单的控制器编写测试。
控制器检查模型属性“ADDED_OBJECT”是否存在,并在缺少模型属性时返回成功页面和错误页面。测试错误路径没问题,但不知道如何触发成功路径,通常在成功的POST(Post/Redirect/Get)模式后执行。是否可以将 modelattribute 添加到 mockMvc 调用?
控制器:
@GetMapping("/added")
public String addedContract(Model model) {
if (!model.containsAttribute(ADDED_OBJECT)) {
return ERROR_400;
}
return "added";
}
Run Code Online (Sandbox Code Playgroud)
测试:
@Test
public void added() throws Exception {
mockMvc.perform(get("/added"))
.andExpect(status().isOk())
.andExpect(content().string(not(containsString("400"))));
}
Run Code Online (Sandbox Code Playgroud)
谢谢
JSP:
<form:form commandName="editWeather" method="post" action="../edit">
<!-- Input fields -->
<input type="submit" value="Submit">
</form:form>
Run Code Online (Sandbox Code Playgroud)
这就是我在Spring中获得模型的方式:
@ModelAttribute("DONTGIVEADAMN") Weather weather
Run Code Online (Sandbox Code Playgroud)
我仍然可以使用weather它来做我的操作,它工作得很好,例如:
weatherService.editWeather(weather);
Run Code Online (Sandbox Code Playgroud)
我的问题是......为什么这样做?