每次用户未通过身份验证(包括转到基本URL)时,我都尝试将URL重定向到/ 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";
答案 0 :(得分:0)
您需要cookies
才能跟踪用户活动,通常这是每个具有登录功能的网站都必须具备的功能。
答案 1 :(得分:0)
我强烈建议您在项目中添加Spring Security。它会为您做所有的事情;您将不需要管理会话并检查用户是否登录等。SpringSecurity会为您完成此操作。如果未通过身份验证,Spring Security将自动将用户重定向到登录页面。