请看下面我的方法。该代码显示了单击登录按钮时发生的功能。
loginBtn.addListener(new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
// Getting the helper for working with spring context
// found here https://vaadin.com/wiki/-/wiki/Main/Spring%20Integration
SpringContextHelper helper = new SpringContextHelper(getApplication());
// Get the providerManagerBean
ProviderManager authenticationManager = (ProviderManager)helper
.getBean("authenticationManager");
// Get entered data for name and password
String name = usernameEntered;
String password = passwordEntered;
// Validation
if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
getWindow().showNotification("Username or password cannot be empty",
Notification.TYPE_ERROR_MESSAGE);
} else {
try {
// Security functionality goes here
UsernamePasswordAuthenticationToken token =
new UsernamePasswordAuthenticationToken(name, password);
Authentication authentication = authenticationManager.authenticate(token);
// Set the authentication info to context
SecurityContextHolder.getContext().setAuthentication(authentication);
// During the authentification the AppUser instance was set as
// details, for more info about the user
AppUser user = (AppUser) authentication.getDetails();
if (user != null) {
// Switch the view after succesfull login
getApplication().getMainWindow().setContent(new ComboBoxUserStartsWith());
}
} catch (AuthenticationException e) {
// Display error occured during logining
getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
}
}
}
});