背景:因为使用Swagger测试需要手动指定传入的参数,但是session和model这种东西基本不可能靠手敲来实现,所以需要把他们从方法的参量表中移走,令辟一条路实现他们。
在控制器中使用构造器传入HttpSession对象:
private final HttpSession session;
public XXXController(HttpSession session) {
this.session = session;
}
之后就可以在这个控制器中的任意类访问session了。
不用Spring MVC的方法传入参数(..., Model model)将某个对象放入model中的方法
用注解"@ModelAttribute()",这里直接放代码,自己看吧。
package controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/user")
@Api("访问用户的API")
public class UserController {
/**
* 访问{ServerRoot}/user/{username},
* 转发至用户详情页,
* 详情页用model传入的用户名在GET {ServerRoot}/users/{username},
* 异步加载用户实体对应JSON对应对象,
* 再由Vue.js绘制至DOM组件
* @param username 地址传入的请求用户名
* @return 需要映射的页面地址到视图解析器
*/
@GetMapping(value = "/{username}")
@ApiOperation(value = "获取用户名为{username}的详细信息")
@ApiImplicitParam(name = "username", dataType = "String", paramType = "path")
public String userInfo(@PathVariable(value = "username") @ModelAttribute(value = "username") String username) {
// 怎么把username传到info页,info页再通过它使用Ajax从UsersController::getUserInfo加载用户信息,model?
return "user/info";
}
}
这里的效果就是把地址传过来的变量username放入model。
注:这个注解有别的用法,但是不再推荐使用。