Spring controller example


      Click here to attend Spring Framework 4.x and certification course with a discount


package nl.kameroom.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import nl.kameroom.user.ChangePass;
import nl.kameroom.user.UserManager;
import nl.kameroom.util.LocaleMessageSource;
import nl.kameroom.util.ValidationComparator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PasswordResetController {

	private UserManager userManager;
	private Validator validator;
	private LocaleMessageSource messageSource;
	private AuthenticationManager authenticationManager;	
	
	@Autowired
	public void setUserManager(UserManager um) {
		userManager = um;
	}
	
	@Autowired
	public void setValidator(Validator v) {
		validator = v;
	}
	
	@Autowired
	public void setLocaleMessageSource(LocaleMessageSource ms) {
		messageSource = ms;
	}
	
	@Autowired
	@Qualifier("authenticationManager")
	public void setAuthenticationManager(AuthenticationManager autm) {
		authenticationManager = autm;
	}
	
	@RequestMapping(value="/reset.k", method=RequestMethod.POST)
	public @ResponseBody String remindPass(@RequestParam("newpass") String newpass,
	@RequestParam("confirmpass") String confirmpass, 
	@RequestParam("email") String email, 
	@RequestParam("k") String key, 
	ModelMap model, HttpServletRequest request) throws Exception 
	{					
		String keyinDB = userManager.getReminderUserPassKey(email);
		if(keyinDB.equals(key)) {
		//change user's password with the new one
		boolean r = userManager.changeUserPassword(email, newpass);
		if(r == true) {
			
			//Spring Security Auto Login
			try {
				// Must be called from request filtered by Spring Security,
				// otherwise SecurityContextHolder is not updated
				UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, newpass);
				token.setDetails(new WebAuthenticationDetails(request));
				Authentication authentication = authenticationManager.authenticate(token);
				SecurityContextHolder.getContext().setAuthentication(authentication);
				return "success";
			} catch (Exception e) {
				SecurityContextHolder.getContext().setAuthentication(null);
				return "fail";
			}
			
		}
		else
			return "fail";
		}else {
			return "fail";		
		}	
	}	
	
	@RequestMapping(value="/profile/changepassword.k", method=RequestMethod.POST)
	public @ResponseBody String[] changePass(
	@RequestParam("oldpass") String oldpass,		
	@RequestParam("newpass") String newpass,
	@RequestParam("confirmpass") String confirmpass, Authentication auth,
	ModelMap model, HttpServletRequest request) throws Exception 
	{					
		
		ChangePass cp = new ChangePass();
		cp.setOldPass(oldpass);
		cp.setNewPass(newpass);
		cp.setConfirmPass(confirmpass);
		
		Set<ConstraintViolation<ChangePass>> constraintViolations = validator.validate(cp);
		String[] messages = new String[constraintViolations.size()];
		ArrayList<String> mList = new ArrayList<String>();
		
		for (int i = 0; i < constraintViolations.toArray().length; i++) {
			ConstraintViolation constraintViolation = (ConstraintViolation)constraintViolations.toArray()[i];
			mList.add(constraintViolation.getMessage());
		}
		
		if(mList.size()>0){
		Collections.sort(mList, new ValidationComparator());
		for (int i = 0; i < mList.size(); i++) {
			messages[i] = messageSource.getMessage(mList.get(i).substring(mList.get(i).indexOf(".") + 1), request);

		}
		}
		
		boolean r = userManager.changeUserOldPassword(auth.getName(), newpass, oldpass);
		if(r == true)
		return new String [] {"success"};
		else {
			if(messages.length == 0)
			return new String [] { messageSource.getMessage("pass.wrong",request)};	
			else
			return messages;	
		}

	}	
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s