2

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??

1
  • There is @RequestBody annotation in spring-boot Commented Aug 21, 2019 at 13:07

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sir, can you please refer to the update that I have added.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.