How to redirect to an external url from spring mvc controller? - spring

This is my code inside the controller class. When the user enters localhost:8080/url, it retrieves the original long url let's say www.google.com saved in the database and then i want it to redirect to www.google.com but instead it redirects to localhost:8080/www.google.com and thus gives en error 500.
#RequestMapping(value="/{url}", method = RequestMethod.GET)
public RedirectView getLongURl(#PathVariable("url") String url) {
String original = database.getLongUrl(UrlShortener.decode(url));
RedirectView redirectview = new RedirectView();
redirectview.setUrl(original);
return redirectview;
}

You should return a ModelAndView
#RequestMapping(value="/{url}", method = RequestMethod.GET)
public ModelAndView method(#PathVariable("url") String url) {
String original = database.getLongUrl(UrlShortener.decode(url));
return new ModelAndView("redirect:" + original);
}
You do not have the option to redirect your request to an outside domain/host like google.com using the RedirectView. As it's name says, it redirects your request to an "another view" in your application.
Refer the docs for more on RedirectView

Related

Spring WebFlux + thymeleaf: Post request redirect Get page returns the 303 see other status

I just used SpringBoot + WebFlux + thymeleaf to write the controller.
#RequestMapping(value = "/create", method = RequestMethod.GET)
public String createCityForm(Model model) {
model.addAttribute("city", new City());
model.addAttribute("action", "create");
return CITY_FORM_PATH_NAME;
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String postCity(#ModelAttribute City city) {
cityService.saveCity(city);
return REDIRECT_TO_CITY_URL;
}
I witre thymeleaf page to receive the form, and redirect/return the get method page, But the browser give the 303 see other status.
Also, the delete resources also doesn't work.
The SEE_OTHER status is actually the default status of the RedirectView when invoked without explicitly specifying the HTTP code (like the ThymeleafReactiveViewResolver does).
If you want to override this status, return the RedirectView directly instead of letting Thymeleaf do it when it matches the redirect: pattern in the view name:
#RequestMapping(value = "/create", method = RequestMethod.GET)
public RedirectView createCityForm(Model model) {
model.addAttribute("city", new City());
model.addAttribute("action", "create");
return new RedirectView("/target_url", HttpStatus.MOVED_PERMANENTLY);
}

Spring Boot - redirect to a different controller method

I am creating a very basic application with SpringBoot and Thymeleaf. In the controller I have 2 methods as follows:
Method1 - This method displays all the data from the database:
#RequestMapping("/showData")
public String showData(Model model)
{
model.addAttribute("Data", dataRepo.findAll());
return "show_data";
}
Method2 - This method adds data to the database:
#RequestMapping(value = "/addData", method = RequestMethod.POST)
public String addData(#Valid Data data, BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "add_data";
}
model.addAttribute("data", data);
investmentTypeRepo.save(data);
return "add_data.html";
}
HTML files are present corresponding to these methods i.e. show_data.html and add_data.html.
Once the addData method completes, I want to display all the data from the database. However, the above redirects the code to the static add_data.html page and the newly added data is not displayed. I need to somehow invoke the showData method on the controller so I need to redirect the user to the /showData URL. Is this possible? If so, how can this be done?
Try this:
#RequestMapping(value = "/addData", method = RequestMethod.POST)
public String addData(#Valid Data data, BindingResult bindingResult, Model model) {
//your code
return "redirect:/showData";
}
sparrow's solution did not work for me. It just rendered the text "redirect:/"
I was able to get it working by adding HttpServletResponse httpResponse to the controller method header.
Then in the code, adding httpResponse.sendRedirect("/"); into the method.
Example:
#RequestMapping("/test")
public String test(#RequestParam("testValue") String testValue, HttpServletResponse httpResponse) throws Exception {
if(testValue == null) {
httpResponse.sendRedirect("/");
return null;
}
return "<h1>success: " + testValue + "</h1>";
}
Below Solution worked for me.
getAllCategory() method displays the data and createCategory() method add data to the database. Using return "redirect:categories";, will redirect to the getAllCategory() method.
#GetMapping("/categories")
public String getAllCategory(Model model) {
model.addAttribute("categories",categoryRepo.findAll());
return "index";
}
#PostMapping("/categories")
public String createCategory(#Valid Category category) {
categoryRepo.save(category);
return "redirect:categories";
}
OR using ajax jQuery also it is possible.
You should return a http status code 3xx from your addData request and put the redirct url in the response.

Unable to access redirectAttributes while redirecting to controller action with Paramerters

In Spring MVC,
When the return value contains redirect: prefix, the viewResolver recognizes this as a special indication that a redirect is needed. The rest of the view name will be treated as the redirect URL. And the client will send a new request to this redirect URL.
We can write a handler method like this to handle the redirect:
#RequestMapping(value="/foo", method = RequestMethod.POST )
public String foo(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", "I am message");
return "redirect:/bar";
}
Now we can access this redirectAttribute in bar() like this
#RequestMapping(value="/bar", method = RequestMethod.GET )
public String bar(HttpServletRequest request, HttpServletResponse response, Model model) {
String error = (String) model.asMap().get("message");
}
Normally we can access this the redirectAttribute inside bar() method, But when I specify a URL as parameterised url in return statement like this below
return "redirect:/bar?x=1&y=2";
I am unable to access the redirectAttributes
I further Inspected network in chrome and I found that while using un-parameterised url in return statement jsessionid remains same after redirect, but it does changes while using parameterised urls.
Can anyone please tell me why is this happening or am I going wrong somewhere?
If you want to access the value of paramater x and y in your redirect controller you need to get Parameter from request.
#RequestMapping(value="/bar", method = RequestMethod.GET )
public String bar(HttpServletRequest request, HttpServletResponse response, Model model) {
System.out.println(request.getParameter("y"));
return null;
}

Is it possible to change URL when returning ModelAndView from WEB-INF?

I'm using Spring MVC and I'm wondering is it possible to change URL when I return ModelAndView (the view is situated at the WEB-INF folder, so redirecting to it is not working) from the controller? I mean when I return it the URL is the previous one, and its obvious because dispatcher is working, not the redirecting.
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView authenticate(#RequestParam("login") String login, #RequestParam("password") String password) {
ModelAndView modelAndView = new ModelAndView();
User user = userDao.getUserByLogin(login);
if (user != null && user.getPassword().equals(password)) {
modelAndView.addObject("user", user);
modelAndView.setViewName("home");
}
return modelAndView;
}
So my home model is in WEB-INF folder, so return redirect:/home will not work for it. Yes, I can redirect it with return home, but in that case the URL will not change.
Use redirect:/url to some other method and return the view.
When redirecting the model attributes won't available in new method so to get that in redirected method set it in RedirectFlashAttributes.
Hope it helps.

Spring MVC + GWT : Redirect Issue

I am using Spring annotated MVC framework in an app which I am developing.
Following is the issue I am facing:
I have Controller which does a redirect, after a POST:
#RequestMapping(value = "/emdm-viewer-redirect.do", method = RequestMethod.POST)
public ModelAndView getMetricKeysAndRedirect(#RequestParam Object jsonObject, Model model)
{
ModelAndView modelAndView = new ModelAndView("redirect:/mdm-viewer.do");
.....
.....
....//make some service calls and populate value1
...
modelAndView.addobject("param1", value1);
return modelAndView;
}
I have another controller which is mapped to URL mdm-viewer.do (The redirect URL mentioned above):
#RequestMapping(value = "/mdm-viewer.do", method = RequestMethod.GET)
public String getMDMViewer(Model model) {
return "mdmViewer"; //returns a mdmViewer.jsp
}
Please note that the mdmviewer.jsp is a GWT entrypoint which is in classpath.
I have my firebug window open which tells me that a GET request was made for mdm-viewer.do, but it gives me a blank response. In fact, it does not redirect to the new jsp and stays on the same page from where the POST request was made.
However, if I copy the firebug URL and open it in a new window of my browser, I see the expected results.
Any ideas what I am doing wrong here? Tried to google it a lot, but can't find a similar issue anywhere.
Eventually, I returned a ModelAndView back from the POST method using a
#ResponseBody
And in my GWT Module, I used the response.getText() output to do a
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
JSONObject jsonObject = (JSONObject) JSONParser.parse(response.getText());
String viewName = jsonObject.get("viewName").isString().stringValue();
JSONObject jsonParams = jsonObject.get("model").isObject();
Set<String> chartKeys = jsonParams.keySet();
String redirectURL = viewName + "?";
for (String keyString : chartKeys) {
redirectURL = redirectURL + keyString + "=" + jsonParams.get(keyString).isString().stringValue() + "&";
}
Window.open(GWT.getHostPageBaseURL() + redirectURL, "_self", "");
}
}

Resources