0

I am a beginner of spring boot application. I made login form success when login success redirects to the index page along with session username set in the index page. I don't know how to set and retrieve into index page of the login success. This is what I have tried and have attached below.

UserController

@PostMapping("/login")
    public String login(@ModelAttribute("user") User user ) {
        
        User oauthUser = userService.login(user.getUsername(), user.getPassword());
        System.out.print(oauthUser);
        if(Objects.nonNull(oauthUser)) 
        {   
            
            return "redirect:/";
            HttpSession.setAttribute("users",user.getUsername());
            
        } else {
            return "redirect:/login";
            
        
        }

}

UserService

public class UserService {
    
    @Autowired
    
      private UserRepository repo;
    
    public User login(String username, String password) {
        User user = repo.findByUsernameAndPassword(username, password);
        return user;
    }
}

Index if the login succes only displayed welcome only

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

        <h1>Welcome to Home Page</h1>

</body>
</html>
Pooja S
  • 550
  • 2
  • 9
radu ba
  • 25
  • 5
  • Use jsp expressions to get the "users" attribute like this <℅username = request.getAttribute("users")℅> in your index.jsp file and just do ${username} to render it. I would suggest the use of JSTL tags for forms that help you get the modelAttribute automatically injected into it. So that you get to access the variables directly into the form that you set in the controller. – Aditya Patnaik Jun 06 '21 at 09:55
  • can you write it it is very help ful please – radu ba Jun 06 '21 at 10:03
  • I could have written the answer @raduba but m not 100% sure if it would surely solve ur issue. Can you try adding this expression in ur index.jsp file like this

    <℅=session.getAttribute("users")℅>

    and try?
    – Aditya Patnaik Jun 06 '21 at 10:13
  • ok sir. if i written in HttpSession.setAttribute("users",user.getUsername()); on my controller getting error of Cannot make a static reference to the non-static method setAttribute(String, Object) from the type HttpSession – radu ba Jun 06 '21 at 10:17
  • https://stackoverflow.com/a/18795626/11045279 this should help. – Aditya Patnaik Jun 06 '21 at 10:24

0 Answers0