每次用户未通过身份验证(包括转到基本网址(时,我都试图将网址重定向到/login。 例如本地主机:8080 -> 本地主机:8080/登录。任何帮助不胜感激!
这是我的登录控制器
public class LoginController {
@Autowired
LoginService service;
/*
* Map /login to this method
* localhost:8080/spring-mvc/login
* spring-mvc -> dispatcher (todo-servlet.xml)
* dispatcher detects login url
* dispatcher use view resolver to find .jsp file based on String. In this case, login
* view resolver locates login.jsp and shows the content to user via http
*/
@RequestMapping(value = "/test")
@ResponseBody
public String test() {
return "Hello, world!";
}
@RequestMapping(value ="/")
public String returnLogin() {
return "redirect:/loginPage";
}
@RequestMapping(value = "/login", method= RequestMethod.GET)
public String loginPage() {
return "login";
}
@RequestMapping(value = "/login", method= RequestMethod.POST)
has an addition function where it allows a collection of attributes
public String handleLogin(@RequestParam String name, @RequestParam String password, ModelMap model) {
if (service.validateUser(name, password)) {
model.addAttribute("name", name);
model.addAttribute("passWelcome", password);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(new Date());
model.addAttribute("date", date);
}
else {
model.put("errorMessage","Invalid credentials");
return loginPage();
}
return "welcome";
您需要cookies
才能跟踪用户活动,这通常是每个具有登录功能的网站必须具备的。
我强烈建议您在项目中添加Spring Security。它会为你做这一切;您无需管理会话并检查用户是否登录等。Spring 安全将为您完成。如果用户未经过身份验证,Spring 安全性将自动将用户重定向到登录页面。