2

I am using spring 3.2 and I have come with one requirement and can't figure out how to achieve it, first please look for below

  1. We mostly use model in Spring MVC which is use for data binding
  2. @ResponseBody annotation returns the string as http response

So my requirement is I want to use both together in single method base on condition, Here is my code

@RequestMapping(value="userAddEditSubmit.htm", method={RequestMethod.GET, RequestMethod.POST})
    public String userAddEditSubmit(
        @ModelAttribute("user") User user,
        HttpServletRequest request, HttpServletResponse response, HttpSession session,
        Model model
    ) throws Exception {
        try {
            //Here is my logic

            return "redirect:" + url;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

So above is my method which returns specific jsp with model attribute, but now in one condition I have requirement to return String data instead of whole jsp in the same method, what can I do to achieve this? Any help will be highly appreciated.

1 Answer 1

2

You can simply return null from that method when your condition is met and write to the response yourself. Spring assumes that when a method returns null it has handled the response itself.

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

5 Comments

Okay got something and can you say how to write response? by adding model attribute or PrintWriter class or something other?
Just ask Spring to inject a HttpServletResponse instance into your controller method by declaring it as a argument. You can use getWriter or getOutputStream to write to it. Also read the warning in the docs
Ok I try and get back to you.
Hi I had try to return with null it is throwing 404 error. No use
Then you are doing something wrong. Please update your question with your current code. Also try to log org.springframework at DEBUG level and share the log output of the one single request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.