简体   繁体   中英

Single page application with Spring MVC

I'm trying to build a single page web application using Spring MVC, relying on native Spring MVC controllers (with model and views) and common rest controllers that return JSON information.

I want to briefly explain you what i'm doing with a simple example:

  1. if the user click on the home page button inside the menu, an Ajax method is called and it sends a GET HTTP request to my server that handles the request with a Spring MVC controller, returning the rendered html file of the home page, coming from a JSP file containing JSTL and Spring tags.
  2. Once the Ajax method receives the content of the homepage it changes the content of the main div inside my html body with this new one. In the end what the user has, is the homepage without refreshing the page (sorry for the game of words).

The only problem is that if a user writes inside the browser the url of the GET HTTP request that the Ajax method uses to get the homepage content, right now what happens is that he will load the homepage content inside the browser(and of course i don't want him to be able to send this get http request manually).

I really hope to have explained myself with this example and I would like to ask you if you have any suggestions to give me in this direction in order to solve this problem! I know that using a framework such as React or Angular, things would be much much easier but i still have to learn one! This will be the first upgrade I'll do in the future to this webapp.

Thank you very much for your help!

You have to use @RestController and not @Controller(or your could do @Controller for the class and @ResponseBody for the single method).Therefore your return method should be a ResponseEntity. According with the flow of your code, you can set the HttpStatus.OK or HttpStatus.INTERNAL_SERVER_ERROR.

Try to authenticate all your HTTP call from JavaScript to your API (for example with a token like JSON Web Token). If the token is not present or incorrect, return a 401 HTTP Status(Unauthorized).

There is a lot of good tutorial like this one: http://www.baeldung.com/spring-security-oauth-jwt

You just have to add an Http Header to your ajax call with the token returned by the authentication.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM