Search code examples
jqueryjspspring-mvcjquery-load

Find JSP page in Spring MVC server to use in load method from jQuery


Currently my Spring MVC server is basically organized like this:

src/main/java                 <-- Java classes containing Controllers, Entities and etc
src/test/java                 <-- For JUnit tests
src/main/webapp/resources     <-- includes CSS, images and all Javascript files
src/main/webapp/WEB-INF/views <-- includes all JSP files

Spring is configured to use this ViewResolver:

<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

The JSP file I'm working on is placed on this path in the Project: MyProject\src\main\webapp\WEB-INF\views\treino\formulario1.jsp

I have developed a JavaScript code inside this jsp (temporally, because it will be moved to resources/js/ later) and I'm calling load() method from jQuery to load another JSP page at the same path as this.

Here are some of the path combinations I've tried but all of them gave me a 404 error in the Browser:

$('#test').load('../WEB-INF/views/treino/formulario2.jsp');
$('#test').load('/MyProject/WEB-INF/views/treino/formulario2.jsp');
$('#test').load('formulario2.jsp');

Just an information, in this same JSP file I can import resources like this:

<script src="../resources/js/bootstrap/bootstrap.min.js"></script>

How can I get the correct path for this JSP?


Solution

  • It looks like to me that you are trying to load JSP from javascript.

    Javascript is executed client side. And JSP on server side. You cannot have Javascript client side code load JSP via relative path like this.

    To have Javascript code load a view, you would need that JS code to make an Ajax call to a controller mapped URL that will serve the JSP (required JSP) as a view.

    For eg. To load the contents from formulario2.jsp

    1. Write a controller mapped to the URL /formulario
    2. The controller /formulario should return the view formulario2.jsp
    3. Javascript should make an Ajax call to /formulario which would return the contents of formulario2.jsp.

    AJax call to /formulario should return formulario2.jsp view.