I have a Controller class in a SpringBoot project to have a login functionality. When I enter username and password and press submit, it will call LoginController with method="POST". I want that when I use the Model to add attribute "customer", that "customer" attribute will be added into session through @SessionAttributes("customer") too. Instead it return error
Here is the error
Expected session attribute 'customer'
org.springframework.web.HttpSessionRequiredException: Expected session attribute 'customer'
Here is my code
@Controller
@SessionAttributes("customer")
public class LoginController {
@Autowired
CustomerService customService;
@RequestMapping(method=RequestMethod.GET,value="/login")
public String login() {
return "login";
}
@RequestMapping(method=RequestMethod.POST,value="/login")
public String submitLoginForm(@ModelAttribute Customer customer, Model model) {
model.addAttribute("customer", customService.getCustomer(customer.getUsername(), customer.getPassword()));
return "redirect:/";
}
}```
You've to annoate the getCustomer
method with the @ModelAttribute("customer")
For eg:
@Service
public class CustomerService {
@ModelAttribute("customer")
public Customer getCustomer(String username, String password) {
return new Customer(username, password);
}
}
Model Object
public class Customer {
private String username;
private String password;
public Customer(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
Controller
@Controller
@SessionAttributes("customer")
public class LoginController {
@Autowired
CustomerService customService;
@RequestMapping(method=RequestMethod.GET,value="/login")
public String login() {
return "login";
}
@RequestMapping(method=RequestMethod.POST,value="/login")
public String submitLoginForm(Customer customer, Model model, HttpServletRequest request) {
model.addAttribute("customer", customService.getCustomer(customer.getUsername(), customer.getPassword()));
return "redirect:/";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.