Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

when using redirect in spring mvc its redirecting to null

HI,
I have the following code :

package org.directi.code.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.ObjectMapper;
import org.directi.code.Snippet;
import org.directi.code.SnippetDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {

    @Autowired
    SnippetDao snippetDao;
    @RequestMapping(value = "/")
    public String newSnippet(HttpServletResponse response) throws IOException {
     return "new";
    }

    @RequestMapping(value = "/snippets", method = RequestMethod.POST)
    public String createSnippet(@RequestBody String jsonString) throws IOException {
        Snippet snippet = new ObjectMapper().readValue(jsonString, Snippet.class);
       String uuid =  snippetDao.insertData(snippet);
       return "redirect:/snippets/"+uuid;

    }

    @RequestMapping(value="/snippets/{id}", method=RequestMethod.GET)
    public String showSnippet(@PathVariable String id)
    {
        Snippet snippet = snippetDao.getSnippetById(id);
        return "snippet";

    }
}

Open in new window


The problem is when the redirection happens in createSnippet function it calls the showSnippet function.
And then i see an error and strangely url is directed to :
http://localhost:9999/null
I think there is no problem with snippet.jsp
because if i place it under newSnippet instead of "new" it runs fine.
Something wrong going on with redirection.

What could be the issue.
Thanks
ASKER CERTIFIED SOLUTION
Avatar of gurpsbassi
gurpsbassi
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Rohit Bajaj

ASKER

HI,
I got the issue.
Actually there was a js error.
It was expecting the response header to contains Location attribute.
which i was not passing and so the page was directing to null..

I did the following and it worked :
        response.addHeader("Location", "http://" + request.getHeader("Host") + "/snippets/" + uuid);
So the redirection was happening from inside the javascript code.

Thanks for help...
Ok, please remove my answer as the accepted solution since it will be misleading when people revisit this question.