userformcontroller.java
来自「Java的框架」· Java 代码 · 共 440 行
JAVA
440 行
package mcaps.core.user.webapp.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mcap.core.base.webapp.controller.BaseFormController;
import mcap.core.base.webapp.util.RequestUtil;
import mcap.core.config.Config;
import mcap.core.user.model.PasswordControl;
import mcap.core.user.model.Role;
import mcap.core.user.model.User;
import mcap.core.user.service.PasswordControlManager;
import mcap.core.user.service.RoleManager;
import mcap.core.user.service.UserExistsException;
import mcap.core.user.util.NameConstants;
import mcap.core.util.PasswordUtil;
import org.acegisecurity.providers.dao.UserCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
/**
* Implementation of BaseFormController that interacts with the UserManager to
* handle request to retrieve/persist User info to data store.
*/
public class UserFormController extends BaseFormController {
private RoleManager roleManager;
private UserCache userCache;
// private AuthenticationManager authenticationManager;
// private String parameter;
// private RememberMeServices rememberMeServices;
private PasswordControlManager passwordControlManager;
/**
* Returns the authenticationManager.
* @return AuthenticationManager
*/
// public AuthenticationManager getAuthenticationManager () {
// return authenticationManager;
// }
/**
* Sets the authenticationManager.
* @param authenticationManager The authenticationManager to set.
*/
// public void setAuthenticationManager (
// AuthenticationManager authenticationManager) {
// this.authenticationManager = authenticationManager;
// }
/**
* Returns the userCache.
* @return UserCache
*/
public UserCache getUserCache () {
return userCache;
}
/**
* Sets the userCache.
* @param userCache The userCache to set.
*/
public void setUserCache (UserCache userCache) {
this.userCache = userCache;
}
/**
* Returns the roleManager.
* @return RoleManager
*/
public RoleManager getRoleManager () {
return roleManager;
}
/**
* Sets the roleManager.
* @param roleManager The roleManager to set.
*/
public void setRoleManager (RoleManager roleManager) {
this.roleManager = roleManager;
}
/**
* Sets the parameter.
* @param parameter The parameter to set.
*/
// public void setParameter (String parameter) {
// this.parameter = parameter;
// }
/**
* Sets the rememberMeServices.
* @param rememberMeServices The rememberMeServices to set.
*/
// public void setRememberMeServices (RememberMeServices rememberMeServices) {
// this.rememberMeServices = rememberMeServices;
// }
/**
* Returns the passwordControlManager.
* @return PasswordControlManager
*/
public PasswordControlManager getPasswordControlManager () {
return passwordControlManager;
}
/**
* Sets the passwordControlManager.
* @param passwordControlManager The passwordControlManager to set.
*/
public void setPasswordControlManager (
PasswordControlManager passwordControlManager) {
this.passwordControlManager = passwordControlManager;
}
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/**
* First to be called.
*/
public ModelAndView processFormSubmission (HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
// if the request is "Cancel"
if (request.getParameter ("cancel") != null) {
if (!StringUtils.equals (request.getParameter ("from"), "list")) {
return new ModelAndView (getCancelView ());
}
else {
return new ModelAndView (getSuccessView ());
}
}
return super.processFormSubmission (request, response, command, errors);
}
/**
* Next to be called if processFormSubmission method called the
* super.processFormSubmission
*/
public ModelAndView onSubmit (HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
User user = (User) command;
Locale locale = request.getLocale ();
if (request.getParameter ("delete") != null) {
// request to delete user.
this.getUserManager ().removeUser (user.getUsername ());
saveMessage (request, getText ("user.deleted", user.getFullName (),
locale));
// delete the password control record.
if (this.passwordControlManager != null) {
this.passwordControlManager.removePasswordControl (user.getUsername ());
}
return new ModelAndView (getSuccessView ());
}
else {
boolean passwordChange = false;
Config config = Config.getInstance();
// if password need to be encrypted.
if ("true".equals (request.getParameter ("encryptPass"))) {
String algorithm = config.getValue(NameConstants.ENC_ALGORITHM);
Integer keySize = new Integer (config.getValue(NameConstants.ENC_KEY_SIZE));
if (algorithm == null) { // should only happen for test case
algorithm = "SHA";
}
user.setPassword (PasswordUtil.encodePassword (user.getPassword (),
user.getUsername (), algorithm, keySize));
passwordChange = true;
// if updating own profile, check if password is valid. Not recycled.
if (request.getRequestURI ().indexOf ("editProfile") > -1
&& this.passwordControlManager != null) {
if (!this.passwordControlManager.isPasswordValid (
user.getUsername (), user.getPassword ())) {
errors.rejectValue ("password", "errors.password.recycle");
// redisplay the unencrypted passwords
user.setPassword (user.getConfirmPassword ());
return showForm (request, response, errors);
}
}
}
String[] userRoles = request.getParameterValues ("userRoles");
if (userRoles != null) {
// for some reason, Spring seems to hang on to the roles in
// the User object, even though isSessionForm() == false
user.getRoles ().clear ();
for (int i = 0; i < userRoles.length; i++) {
String roleName = userRoles[i];
user.addRole (roleManager.getRole (roleName));
}
}
else {
user.getRoles ().clear ();
}
// try saving the user information.
try {
this.getUserManager ().saveUser (user);
}
catch (UserExistsException e) {
errors.rejectValue ("username", "errors.existing.user", new Object[] {
user.getUsername (), user.getEmail () }, "duplicate user");
// redisplay the unencrypted passwords
user.setPassword (user.getConfirmPassword ());
if (StringUtils.equals (request.getParameter ("method"), "Add"))
user.setVersion(null);
return showForm (request, response, errors);
}
// if is password change. Need to update Acegi of the changes
//if (passwordChange
// && user.getUsername ().equals (request.getRemoteUser ())) {
// change the cache
this.getUserCache ().removeUserFromCache (user.getUsername ());
// Authentication newUser = new UsernamePasswordAuthenticationToken (user
// .getUsername (), user.getPassword ());
//
// ((UsernamePasswordAuthenticationToken) newUser)
// .setDetails (new WebAuthenticationDetails (request));
//
// // reauthenticate the user.
// try {
// newUser = this.getAuthenticationManager ().authenticate (newUser);
// }
// catch (AuthenticationException e) {
// // ignore error.... i think may need to handle this.
// }
//
// SecureContextImpl newSecureContext = new SecureContextImpl ();
// newSecureContext.setAuthentication (newUser);
// ContextHolder.setContext (newSecureContext);
//
// // need to change the remember me cookie if
// // check if remember me service is activated.
// if (useRememberMe (request)) {
// HttpServletRequest newRequest = null;
// if (parameter != null && parameter.length () > 0) {
// HashMap map = new HashMap ();
// map.put (parameter, "true");
// newRequest = new ParameterHttpServletRequest (request, map, true);
// }
// else {
// newRequest = request;
// }
// rememberMeServices.loginSuccess (newRequest, response, newUser);
// }
//}
// replace the User Object in session.
if (user.getUsername ().equals (request.getRemoteUser ()))
request.getSession ().setAttribute (NameConstants.USER_KEY, user);
// update password control.
if (this.passwordControlManager != null) {
if (StringUtils.equals (request.getParameter ("method"), "Add")) {
// new user added, add a new record.
PasswordControl control = new PasswordControl ();
control.setUsername (user.getUsername ());
control.setNeedPasswordChange (true);
this.passwordControlManager.savePasswordControl (control);
}
else if (passwordChange
&& StringUtils.isBlank (request.getParameter ("from"))) {
// edit profile.
PasswordControl control = this.passwordControlManager
.getPasswordControl (user.getUsername ());
List passwordHistory = null;
if (control == null) {
control = new PasswordControl ();
control.setUsername (user.getUsername ());
passwordHistory = new ArrayList ();
control.setPasswordHistory (passwordHistory);
}
else {
passwordHistory = control.getPasswordHistory ();
}
control.setLastModifiedDate (new Date ());
control.setNeedPasswordChange (false);
passwordHistory.add (user.getPassword ());
this.passwordControlManager.savePasswordControl (control);
}
else if (passwordChange
&& StringUtils.equals (request.getParameter ("from"), "list")) {
PasswordControl control = this.passwordControlManager
.getPasswordControl (user.getUsername ());
if (control == null) {
control = new PasswordControl ();
control.setUsername (user.getUsername ());
}
control.setNeedPasswordChange (true);
this.passwordControlManager.savePasswordControl (control);
}
}
if (!StringUtils.equals (request.getParameter ("from"), "list")) {
// from the profile update.
// HttpSession session = request.getSession ();
// session.setAttribute (NameConstants.USER_KEY, user);
saveMessage (request, getText ("user.saved", user.getFullName (),
locale));
// return to main Menu
return new ModelAndView (new RedirectView ("mainPage.action"));
}
else {
if (StringUtils.isBlank (request.getParameter ("version"))) {
saveMessage (request, getText ("user.added", user.getFullName (),
locale));
// Send an account information e-mail
message.setSubject (getText ("signup.email.subject", locale));
sendUserMessage (user, getText ("newuser.email.message", user
.getFullName (), locale), RequestUtil.getAppURL (request));
return new ModelAndView (new RedirectView ("listUsers.action"));
}
else {
// updated by admin.
saveMessage (request, getText ("user.updated.byAdmin", user
.getFullName (), locale));
return new ModelAndView (new RedirectView ("listUsers.action"));
}
}
}
}
/**
* calling in case of validation errors, to show the form view again.
*/
protected ModelAndView showForm (HttpServletRequest request,
HttpServletResponse response, BindException errors) throws Exception {
if (request.getRequestURI ().indexOf ("editProfile") > -1
&& (errors.getErrorCount () == 0)) {
// if URL is "editProfile" - make sure it's the current user
// reject if "list" parameter passed in
if ( (request.getParameter ("username") != null)
|| (request.getParameter ("from") != null)) {
response.sendError (HttpServletResponse.SC_FORBIDDEN);
return null;
}
}
// prevent ordinary users from calling a GET on editUser.html
// unless a bind error exists.
if ( (request.getRequestURI ().indexOf ("editUser") > -1)
&& (!request.isUserInRole (NameConstants.ADMIN_ROLE)
&& (errors.getErrorCount () == 0) && (request.getRemoteUser () != null))) {
response.sendError (HttpServletResponse.SC_FORBIDDEN);
return null;
}
return super.showForm (request, response, errors);
}
/**
* Retrieve a backing object for the current form from the given request.
*/
protected Object formBackingObject (HttpServletRequest request)
throws Exception {
String username = request.getParameter ("username");
User user = null;
if (request.getRequestURI ().indexOf ("editProfile") > -1) {
user = this.getUserManager ().getUser (getUser (request).getUsername ());
}
else if (!StringUtils.isBlank (username)
&& !"".equals (request.getParameter ("version"))) {
user = this.getUserManager ().getUser (username);
}
else {
user = new User ();
user.addRole (new Role (NameConstants.USER_ROLE));
user.setEnabled(true);
}
user.setConfirmPassword (user.getPassword ());
return user;
}
protected void onBind (HttpServletRequest request, Object command)
throws Exception {
// if the user is being deleted, turn off validation
if (request.getParameter ("delete") != null) {
super.setValidateOnBinding (false);
}
else {
super.setValidateOnBinding (true);
}
}
// private boolean useRememberMe (HttpServletRequest request) {
//
// AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl
// ();
// SecurityContext ctx = SecurityContextHolder.getContext ();
//
// Authentication auth = ctx.getAuthentication ();
//
// return resolver.isRememberMe (auth);
// }
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?