Alternative of @ModelAttribute annotation in Spring

Like in Spring we have httpServeletRequest.getParameter("key") as an alternative to @RequestParam("key"), do we have any alternative to @ModelAttribute("key") ?

model.addAttribute("student",new Student());
...
...
@RequestMapping("/processStudentForm")
public String processTheForm(
    @ModelAttribute("student") Student student
) 
{       
    ...
}

Do we have something like?

public String processTheForm(
     Model model
) 
{       
    Student student = model.getAtribute("key");
    ...
}

Update 1

    @RequestMapping("/showStudentForm")
    public String showTheForm(Model model) {
        model.addAttribute("key",new Student());
        return "studentForm";
    }
<form:form action='processStudentForm' modelAttribute='key' method='post'> 
        ... 
</form:form> 

I am binding the form values into student object. How to access this model attribute through request object??

Upvotes: 2

Views: 1217

Answers (1)

Manoj Krishna
Manoj Krishna

Reputation: 800

The student Model Object cannot be accessed directly though the request object but you can access this in different ways from the request object .By Default spring does lot of work under the hood its uses FormHttpMessageConverter to convert it to a model map on a application/x-www-form-urlencoded request you can refer the docs.

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/FormHttpMessageConverter.html

You can do the same what spring does internally.I tried this its working but you can do it in multiple ways refer the stack overflow post for other answers

       Map map = httpServletRequest.getParameterMap().entrySet()
            .stream().collect(Collectors.toMap(e -> e.getKey(), e -> Arrays.stream(e.getValue()).findFirst().get()));
       Student student = new ObjectMapper().convertValue(map, Student.class);

Getting request payload from POST request in Java servlet

But its always a good practice to use the default implementation.

Upvotes: 2

Related Questions