0

I'm new to spring. There is a Controlle called userController. In this controller there is method called signIn. In this method is user entered correct userid and password then page redirect to the same view with session values. Then user can check his profile details. For that i have created a method call account in the userController. In this method i can not get the previously set session values.How can i get it? This is my implementation of two method. this issignIn method

@RequestMapping(value = "/sign_in", method = RequestMethod.POST) public String signIn(@RequestHeader(value = "Accept") String headerAccept,@ModelAttribute User requestParamUser,RedirectAttributes redirectAttrs,HttpSession session) { JSONObject obj = new JSONObject(); try { // Check request parameters are null if ((requestParamUser.getUserId() == null)|| (requestParamUser.getPassword() == null)) { obj.put("loginError", CommonConfig.REQUEST_PARAMETERS_ARE_NULL); redirectAttrs.addFlashAttribute("state", obj); redirectAttrs.addFlashAttribute("user",requestParamUser); return "redirect:/"; } User user = userDAO.findByUserIdAndPassword(requestParamUser.getUserId(),requestParamUser.getPassword()); // Check provide userId and password is correct if (user == null) { obj.put("loginError", CommonConfig.USER_NOT_FOUND); redirectAttrs.addFlashAttribute("state", obj); redirectAttrs.addFlashAttribute("user",requestParamUser); return "redirect:/"; } obj.put("loginSuccess", CommonConfig.LOGIN_SUCCESS); redirectAttrs.addFlashAttribute("state", obj); session.setAttribute("userId",user.getUserId()); session.setAttribute("userName",user.getFirstName()); return "redirect:/"; } catch (Exception e) { System.out.println(CommonConfig.DB_ERROR + " : "+ e.getMessage().toString()); obj.put("loginError", CommonConfig.DB_ERROR); redirectAttrs.addFlashAttribute("state", obj); redirectAttrs.addFlashAttribute("user",requestParamUser); return "redirect:/"; } } 

This is the account method.

@RequestMapping(value="/ac") public String account(@RequestHeader(value = "Accept") String headerAccept,RedirectAttributes redirectAttrs, HttpServletRequest request){ String userId = (String) request.getSession(false).getAttribute("userId"); redirectAttrs.addFlashAttribute("abc",userId); return "account"; } 

in this method i'm trying to test the session veriable to redirectAttrs. That value will show in account view. Problem is in this method. I can not get the userId session veriable.

3
  • You can use spring security to do login and store userInfo, It's better and more safe, If it's acceptable for you i can show you example. Commented Jun 10, 2015 at 5:56
  • @SafwanHijazi plz show me a example. tx Commented Jun 10, 2015 at 6:03
  • please see the example below, and please ask me if you have any error Commented Jun 10, 2015 at 6:21

1 Answer 1

2

First you should add spring security libs, then do the following:

create new class that implements this UserDetailsService like this:

public class UserDetailsServiceImpl implements UserDetailsService and implement loadUserByUsername

@Override public UserDetails loadUserByUsername(String userInfo) throws UsernameNotFoundException { // use userInfo to check user Info then return object from UserDetails class String[] tokens=userInfo.split("@0@"); Collection<GrantedAuthority> authorities= new ArrayList<GrantedAuthority>(); // here you pass the Role so you can use later in your application authorities.add(new SimpleGrantedAuthority ("ROLE_"+tokens[2])); UserDetails userDetails = new User(tokens[0],tokens[1], authorities); return userDetails; } 

Now Add these lines in spring configuration file to define authentication manager:

<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> <property name="userDetailsService" ref="userDetailsService"/> </bean> <bean id="userDetailsService" class="yourPackage.UserDetailsServiceImpl"/> <bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager"> <property name="providers"> <list> <ref bean="daoAuthenticationProvider" /> </list> </property> </bean> <bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder"/> <sec:authentication-manager > <sec:authentication-provider user-service-ref="userDetailsService"> </sec:authentication-provider> </sec:authentication-manager> 

Here you define authentication manager, then you can use in login controller like this:

Authentication authRequest = new UsernamePasswordAuthenticationToken(username+"@0@"+password+"@0@"+response.getOperatorInfo().getRole_name(), password); Authentication result=null; try { result = authenticationManager.authenticate(authRequest); } catch (Exception e) { e.printStackTrace(); } SecurityContextHolder.getContext().setAuthentication(result); 

Finally in other Controller you can take the userInfo like this:

SecurityContextHolder.getContext().getAuthentication().getName() 
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. The constructor GrantedAuthorityImpl(String) is deprecated. What is alternate ?
use this authorities.add(new SimpleGrantedAuthority ("ROLE_"+tokens[2]));
<sec:> namespace and location ? i put it but not working
define it as namespace in xml configuration file like this: xmlns:sec="shttp://www.springframework.org/schema/security"
what is response.getOperatorInfo().getRole_name() ? Is that response is HttpServletResponse ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.