spring boot – displaying object data from controller in JSP

Tags: , ,



I have a User class, two JSP and one controller. I want to register a user, store their details in a database (H2) and display user’s name after registration.

This is my home.jsp

<form action="addUser">
    <label>Name: </label><input type="text" name="name"/>
    <label>Id: </label><input type="number" name="id"/>
    <input type="submit" />
</form>

This is my controller –

package com.example.demo;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @Autowired
    UserRepo usrrepoobj;
    
    @RequestMapping("/")
    public String home()
    {
        return "home.jsp";
    }
    
    @RequestMapping("addUser")
    public ModelAndView addUser(@RequestParam int id, User usr)
    {
        usrrepoobj.save(usr);
        User obj = usrrepoobj.findById(id).orElse(null);
        ModelAndView mv = new ModelAndView();
        mv.addObject(obj);
        mv.setViewName("afterRegister.jsp");
        
        //EVEN THIS DOESNT WORK
//      usrrepoobj.save(usr);
//      User obj = usr;
//      ModelAndView mv = new ModelAndView();
//      mv.addObject(obj);
//      mv.setViewName("afterRegister.jsp");
        //EVEN THIS DOESNT WORK
        
        return mv;
    }
    
}

This is my afterRegister.jsp

Registered as ${obj.name}

The object gets added to the database. What am I doing wrong when it comes to displaying the data in the next JSP?

Answer

Make the below change in controller:

usrrepoobj.save(usr);
        User obj = usrrepoobj.findById(id).orElse(null);
        ModelAndView mv = new ModelAndView();
        mv.addObject("object",obj); //change this
        mv.setViewName("afterRegister.jsp");

In afterRegister.jsp –

Registered as ${object.name}


Source: stackoverflow