今晚的主要任务是对项目中已经做出来的注册和登陆界面添加后台。
我们看LoginUser的Controller
@RequestMapping("/user" )
@Controller
public class LoginUserController extends BaseController {
@Resource
private LoginUserService userService ;
@RequestMapping(value = "regist" , method = RequestMethod.GET)
public ModelAndView regist(ModelAndView modelAndView) {
return JspLocation(modelAndView, "regist" );
这里的是首先mapping映射一下,然后声明是控制器。注入Service,声明get方法。
@RequestMapping(value = "regist" , method = RequestMethod.POST)
public ModelAndView regist(ModelAndView modelAndView,
@Valid @ModelAttribute LoginUser user, BindingResult bindResult) {
if (bindResult.hasErrors()) {
modelAndView.setViewName( "/user/regist");
return modelAndView;
}
userService.save(user);
modelAndView.setViewName( "redirect:/userCenter/index");
return modelAndView;
}
这边插入一下Spring的知识
SpringMVC 文档提到了 @SessionAttributes annotation,和 @ModelAttribute 配合使用可以往 Session 中存或者从 Session 中取指定属性名的具体对象。
,@SessionAttributes 是用来在 controller 内部共享 model 属性的。从文档自带的例子来看,标注成 @SessionAttributes 属性的对象,会一直保留在 Session 或者其他会话存储中,直到 SessionStatus 被显式 setComplete()。
controller的代码如下:
@Controller
@SessionAttributes("currentUser")
public class GreetingController{
@RequestMapping
public void hello(@ModelAttribute("currentUser") User user){
//user.sayHello()
}
}
使用这种方案,还需要在 SpringMVC 配置文件的 ViewResolver 定义处,加上 p:allowSessionOverride="true",这样如果你对 User 对象做了修改,SpringMVC 就会在渲染 View 的同时覆写 Session 中的相关属性。
http://blog.csdn.net/li_xiao_ming/article/details/8349115 一篇文档讲解。
http://exceptioneye.iteye.com/blog/1305040
@RequestMapping(value = "confirmRegist" )
public @ResponseBody RegistJson confirmRegist(String email,String username){
if (userService .getUserByName(username) != null ){
return new RegistJson("用户名已经存在");
}
if (userService .getUserByEmail(email) != null ){
return new RegistJson("邮箱已经注册");
}
return new RegistJson();
}
这里返回一个Json如果数据库中已经存在。
@RequestMapping(value = "login" , method = RequestMethod.GET)
public String login() {
return JspLocation("login" ); //初始化的时候,通过get访问
}
@RequestMapping(value = "login" , method = RequestMethod.POST)
public String login(@Valid LoginUser user, BindingResult bindResult) {
UsernamePasswordToken token = new UsernamePasswordToken(user.username ,
user. password);
Subject subject = SecurityUtils. getSubject();
subject.login(token);
return redirect(UserCenterController.controllerMap, "/index.do");
}