Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a static html without redirect in Spring

So I'd like to return an HTML page without sending a redirect. The reason being is using a redirect changes the URL in the browser, and I can't redirect someone to the login if they aren't logged in. What's the most straight forward way to do this? Seems like it should be simple without using jsp or other server side view technologies.

like image 297
chubbsondubs Avatar asked Jun 05 '14 22:06

chubbsondubs


People also ask

How do I return an HTML page?

The Best Answer is. Using @ResponseBody returns return "login"; as a String object. Any object you return will be attached as payload in the HTTP body as JSON. This is why you are getting just login in the response.

How display static HTML file in spring boot MVC application?

Just put index. html in src/main/resources/static/ folder and static html is done!

How do I redirect one HTML page to another in spring boot?

Try a URL http://localhost:8080/HelloWeb/index and you should see the following result if everything is fine with your Spring Web Application. Click the "Redirect Page" button to submit the form and to get the final redirected page.


2 Answers

You can use forward.

Example:

say /static/myWebpage.html is your static html page

This code will return the content of myWebpage.html without changing the url

@Controller
@RequestMapping("/path")
public class TestingController {
    @RequestMapping("/page")
    public String someOtherPage(HttpServletRequest request, HttpServletResponse response) {
        return "forward:/static/myWebpage.html";
    }
}

Again your url would be "localhost/path/page" but you will be viewing "localhost/static/myWebPage.html"

like image 117
ug_ Avatar answered Oct 01 '22 06:10

ug_


The answer given above is correct for most Spring configurations. Other times you'll just get a Content-Type: text/plain webpage with the forwarding information as the text. You must explicitly pass the forwarding information to a ModelAndView.

@Controller
@RequestMapping("/path")
public class TestingController {
    @RequestMapping("/page")
    public ModelAndView someOtherPage(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("forward:/static/myWebpage.html");
    }
}
like image 36
Yserbius Avatar answered Oct 01 '22 08:10

Yserbius