采用注解的当时实现LoginController控制层处理类,请求路径/login,用户服务类CoustomerService,登录成功后界面为index.jsp,登录失败提示msg并停留在login.jsp
时间: 2023-06-26 11:03:25 浏览: 46
好的,下面是一个基于注解的 LoginController 示例代码:
```java
@Controller
public class LoginController {
@Autowired
private CustomerService customerService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Model model) {
boolean isValidUser = customerService.authenticate(username, password);
if (isValidUser) {
model.addAttribute("username", username);
return "index";
} else {
model.addAttribute("msg", "Invalid username or password");
return "login";
}
}
}
```
在上面的代码中,我们使用了@Controller注解将LoginController声明为一个控制器类。我们还使用@Autowired将CustomerService自动装配到LoginController中。@RequestMapping注解指定了请求路径为“/login”,并且我们使用了RequestMethod.POST方法来接受POST请求。
在login()方法中,我们使用@RequestParam注解将传递过来的username和password参数绑定到方法的参数中。我们使用customerService.authenticate()方法来验证用户是否合法,如果合法,我们将username添加到模型中,并返回“index”视图。如果不合法,我们将“Invalid username or password”消息添加到模型中,并返回“login”视图。
在这个例子中,我们使用了Model来传递数据到视图中。在index.jsp视图中,我们可以通过${username}来获取用户名,而在login.jsp视图中,我们可以通过${msg}来获取错误消息。