How to get the value has been set from GET method? How to pass the value to POST method? Should I declare global variable?
EDIT: What I want is doing something on GET method and display a textbox on jsp if setdisplayBox = true. When the user POST the form, the setdisplayBox should be true too and return the same jsp without redirect
#RequestMapping(method = RequestMethod.GET)
public String getSuccess(ModelMap model, #ModelAttribute("user") User user, HttpServletRequest request)
{
String boxDisplay = "True";
user.setdisplayBox(boxDisplay);
return "success";
}
#RequestMapping(method = RequestMethod.POST)
public String resetPassword(HttpServletRequest request, ModelMap model, #ModelAttribute("user") User user, ModelMap modelMap)
{
user.setdisplayBox(user.getdisplayBox()); //how to get value has been set above?
return "success";
}
Set a global variable for the user.
private User userAccount;
#RequestMapping(method = RequestMethod.GET)
public String getSuccess(ModelMap model, #ModelAttribute("user") User user, HttpServletRequest request)
{
String boxDisplay = "True";
user.setdisplayBox(boxDisplay);
userAccount = user; //load user in to global var
return "success";
}
#RequestMapping(method = RequestMethod.POST)
public String resetPassword(HttpServletRequest request, ModelMap model, #ModelAttribute("user") User user, ModelMap modelMap)
{
user.setdisplayBox(userAccount.getdisplayBox());
userAccount = null; //reset it to something to make sure you are loading it to another user later.
return "success";
}
Related
hi i have a problem with my project (small blog site) that i can't handle for a while
that's my LoginController
'''
#Controller
#SessionAttributes("currentUser")
public class LoginController {
#Autowired
UserService userService;
#ModelAttribute("currentUser")
public User setUpUserForm() {
return new User();
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public String showLoginPage() {
return "loginsite";
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public String userLogin(#ModelAttribute("currentUser") User user,ModelMap model,#RequestParam String login,#RequestParam String password) {
if(userService.checkUserLoginData(login, password)==true) {
user=userService.getUserByLogin(login);
System.out.println("Logged in user");
System.out.println("ID:"+user.getUserId());
System.out.println("Login:"+user.getLogin());
System.out.println("Password:"+user.getPassword());
System.out.println("Email:"+user.getEmail());
return "welcomesite";
}else {
model.put("message", "Check your login and password ! ");
return "loginsite";
}
}
}
'''
that's my UserController
'''
#Controller
public class UserController {
#Autowired
UserService userService;
#RequestMapping(value="/",method = RequestMethod.GET)
public String posts() {
return "redirect:/posts";
}
#RequestMapping(value="/createaccount",method = RequestMethod.GET)
public String showRegisterPage() {
return "registrationpage";
}
#RequestMapping(value="/createaccount",method = RequestMethod.POST)
public String createAccount(ModelMap model,#RequestParam String login,#RequestParam String password,#RequestParam String email) {
userService.addUser(new User(login,password,email));
return "redirect:/login";
}
#RequestMapping(value="/login/accountsettings",method = RequestMethod.GET)
public String showAccountSettings(#SessionAttribute("currentUser") User user) {
System.out.println("amil"+user.getEmail());
return "userSettings";
}
#RequestMapping(params="update",value="/login/accountsettings",method = RequestMethod.POST)
public String updateAccountSettings(#SessionAttribute("currentUser") User user,#RequestParam String login,#RequestParam String password,#RequestParam String email) {
user=userService.updateUser(new User(login,password,email));
return "redirect:/login";
}
#RequestMapping(params="delete",value="/login/accountsettings",method = RequestMethod.POST)
public String deleteAccount(#RequestParam String login) {
userService.deleteUser(login);
return "redirect:/posts";
}
'''
i would like to pass user data after logging in to next pages for ex /login/accountsettings or even to have user id to add post with his id as a creator of this post. After logging in everythink is okay i have complete user data but when im tring to get them in /login/accountsettings User is empty(full of null values).what am I doing wrong?
output:
enter image description here
or I have a question, is there another better way to transfer user data until logging out?
Thanks for help!
My Controller:
#Controller
#RequestMapping("/registration")
public class RegisterController {
#RequestMapping("")
public String register() {
return "register";
}
#RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView registerUser(#RequestParam("emailsignup") String email,
#RequestParam("firstname") String firstName,
#RequestParam("lastname") String lastName,
#RequestParam("passwordsignup") String password) throws SQLException, ClassNotFoundException {
ModelAndView modelAndView = new ModelAndView();
.... SQL code that inserts if it can
}
My register.jsp is just a regular form, I had this code working prior but it was mapping to "/" and was messing up my other mapping. When the POST form is clicked (if successful) I want it to return the user to /profile, if non successful to stay on /registration... how can I do this?
You can use, HttpRedirectAttributes like this:
#RequestMapping(value = "", method = RequestMethod.POST)
public ModelAndView registerUser(#RequestParam("emailsignup") String email,
#RequestParam("firstname") String firstName,
#RequestParam("lastname") String lastName,
#RequestParam("passwordsignup") String password,
RedirectAttributes redirect) throws SQLException, ClassNotFoundException {
redirect.addFlashAttribute("emailsignup", emailsignup);
redirect.addFlashAttribute("firstname", emailsignup);
// Next
// Or redirect.addFlashAttribute("profile", profileObject)
return modelAndView.setViewName("redirect:/profile");
}
Then in your jsp recover properties like this:
<label>${emailsignup} </label>
or
<label>${profileObject.emailsignup}</label>
What is the proper way to handle editing objects in Spring MVC. Let's say I have user object:
public class User {
private Integer id;
private String firstName;
private String lastName;
//Lets assume here are next 10 fields...
//getters and setters
}
Now in my controller I have GET and POST for url: user/edit/{id}
#RequestMapping(value = "/user/edit/{user_id}", method = RequestMethod.GET)
public String editUser(#PathVariable Long user_id, Model model) {
model.addAttribute("userForm", userService.getUserByID(user_id));
return "/panels/user/editUser";
}
#RequestMapping(value = "/user/edit/{user_id}", method = RequestMethod.POST)
public String editUser(#Valid #ModelAttribute("userForm") User userForm,
BindingResult result, #PathVariable String user_id, Model model) {
if(result.hasErrors()) {
User user = userService.getById(user_id);
user.updateFields(userForm);
}
userService.update(user);
}
Now the question is do I really need to get my user from database in POST method and update every field one by one in some update method or is there better way for that?
I am thinking about using #PathVariable for User and get User from database with converter and then in some way inject parameters from POST method into that object automatically. Something like this:
#RequestMapping(value = "/user/edit/{user}", method = RequestMethod.POST)
public String editUser(#Valid #PathVariable("user") User userForm,
BindingResult result, Model model)
But when I try this I got error with BindingResults:
java.lang.IllegalStateException: An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the #RequestBody or the #RequestPart arguments
Is there any easy way to create controller to handle objects editing or do I need to copy fields which could change one by one??
By the way, I can't use SessionAttributes because it causes problems for multiple tabs.
I believe you are sending "userForm" as a model attribute. If so try with following pattern,
#RequestMapping(value = "/user/edit/{user_id}", method = RequestMethod.POST)
public String editUser(#PathVariable String user_id, #Valid #ModelAttribute("userForm") User userForm,
BindingResult result, Model model)
Thanks
You keep user id in a input hidden inside your edit form.
#RequestMapping(value = "/user/edit", method = RequestMethod.POST)
public String editUser(#Valid #ModelAttribute("userForm") User userForm,
BindingResult result,Model model){
if(result.hasErrors()){
User user = userService.getById(userForm.getId());
user.updateFields(userForm);
}
userService.update(user);
return "redirect:.......";
}
My project is java spring mvc. I want data list for front end with specific employee.
My controller is
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String setUp(Model model, HttpServletRequest request, #ModelAttribute employeedetail employeedetail) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String empNumer = auth.getName();
employeedetail employee = employeeServices.getEmployee(empNumer);
request.getSession().setAttribute("userId", employee.getEmpNumer());
return "home";
}
In here I got log in user number so I want get list of detail of employee as a array list.
I have following controller which is serving different requests. I am wondering if the way that I create ModelAndView is correct? I am creating one object in each method. Is there any better approach?
#RequestMapping(method = RequestMethod.GET)
public ModelAndView showNames() {
...
ModelAndView model = new ModelAndView("names");
model.addObject ....
return model;
}
#RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
public ModelAndView showNameDetails(#PathVariable String name) {
...
ModelAndView model = new ModelAndView("name");
model.addObject ...
return model;
}
#RequestMapping(value = "/name/{name}/{item}", method = RequestMethod.GET)
public ModelAndView showItemsOfName(#PathVariable String name,
#PathVariable String item) {
...
ModelAndView model = new ModelAndView("item");
model.addObject ....
return model;
}
You can ask Spring to inject the Model for you, and then return the view name from the method, e.g.
#RequestMapping(method = RequestMethod.GET)
public String showNames(Model model) {
...
model.addObject ....
return "names";
}
#RequestMapping(value = "/name/{name}", method = RequestMethod.GET)
public String showNameDetails(#PathVariable String name, Model model) {
...
model.addObject ...
return "name";
}
#RequestMapping(value = "/name/{name}/{item}", method = RequestMethod.GET)
public String showItemsOfName(#PathVariable String name,
#PathVariable String item, Model model) {
...
model.addObject ....
return "item";
}
It's a bit cleaner, and less code.