`
阅读更多
二话不说,直接进入主题!

代码[size=x-small][/size]
package cn.u6.contoller;

import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import cn.u6.contoller.bean.UserBean;
import cn.u6.exception.MVCException;
import cn.u6.model.User;
import cn.u6.service.UserService;
import cn.u6.validator.UserValidator;

@Controller
@SessionAttributes("user")
public class UserController {

protected static Logger logger = Logger
.getLogger("cn.u6.contoller.UserController");

@Resource(name = "userService")
private UserService userService;

/**
* 登录
*/

@RequestMapping(value = "/user/login.do", method = RequestMethod.POST)

public String login(@ModelAttribute("user")UserBean user, BindingResult result,
SessionStatus status, Model model) throws Exception {
logger.debug("Received request to edit existing person");

// 验证用户输入信息
new UserValidator().validate(user, result);
try {
if (result.hasErrors()) {
return "redirect:/";
} else {
int id = userService.login(user.getUserName(), user
.getUserName(), user.getPassword());
switch (id) {
case -1:
model.addAttribute("message", "用户名错误!");
return "login";
case -2:
model.addAttribute("message", "密码错误!");
return "login";
default:
status.setComplete();
model.addAttribute("user", user);
// Session
// session
return "main";
}
}
} catch (UncategorizedSQLException e) {
logger.info("数据库连接出错:" + e.getMessage());
throw new SQLException("数据库连接出错:" + e.getMessage());
} catch (SQLException e) {
logger.info("数据库查询出错:" + e.getMessage());
throw new SQLException("数据库查询出错:" + e.getMessage());
} catch (NumberFormatException e) {
logger.info("数据转换出错:" + e.getMessage());
throw new NumberFormatException("数据转换出错:" + e.getMessage());
} catch (Exception e) {
logger.info("系统出错:" + e.toString() + " ----" + e.getMessage());
throw new MVCException("系统出错:" + e.getMessage());
}
}
}

这种情况下会运行之后发现以下错误:
Session attribute 'user' required - not found in session.

解决方法:
/**
* 登录
*/

@RequestMapping(value = "/user/login.do", method = RequestMethod.POST)
@ModelAttribute("user")
public String login(UserBean user, BindingResult result,
SessionStatus status, Model model) throws Exception
将这句话放到方法上面之后问题解决,本人在这个问题上花了一个上午...各位看客有什么其他的建议或方法可以评论评论~
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics