I am trying to send object of User class to success.jsp. But getting null when trying to retrieve the object in success.jsp.
Code for UserController:
@Controller
@RequestMapping("/user")
public class UserController {
@PostMapping("/login")
public String Register(@Valid @ModelAttribute("user") User user,Errors errors,Model model) {
System.out.println("....done....");
if(errors.hasErrors()) {
return "user";
}
else {
RegisterService.show(user);
model.addAttribute("user",user);
return "redirect:/success";
}
}
}
Code for success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="com.company.models.User" %>
<body>
Registration Successful
<%
User user=(User)request.getAttribute("user");
System.out.println("user=" user);
%>
</body>
CodePudding user response:
It was because I was sending a redirect to success.jsp. So cannot pass data
CodePudding user response:
you can use RedirectAttributes to send data to the page even if you are redirecting.
example:
@PostMapping("/login")
public String Register(@Valid @ModelAttribute("user") User user,Errors errors, RedirectAttributes attributes) {
System.out.println("....done....");
if(errors.hasErrors()) {
return "user";
}
else {
RegisterService.show(user);
attributes.addFlashAttribute("user", user);
return "redirect:/success";
}
}
read the documentation at: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html