简体   繁体   中英

How to call a Spring MVC controller in jsp

I'd like to include a jsp page for exemple

<ui:include src="/WEB-INF/jsp/header.jsp" />

but my header.jsp have variables and I need a controller to initialise theses variables, is there a way to call a controller and include the controller method jsp in an other jsp ?

For exemple;

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true"%>
<%@attribute name="footer" fragment="true"%>
<html>
<body>
    <div id="pageheader">
        //include my header controller
        <ui:include src="/WEB-INF/jsp/header.jsp" />
    </div>
    <div id="body">
        <jsp:doBody />
    </div>
    <div id="pagefooter">
        //include my footer controller
    </div>
</body>
</html>

header.jsp

Header
${test}

my header method

public String header(Map<String, Object> model){
    model.put("test", "test");
    return "header";
}

But the controller is not used and ${test} is empty

I think, if you call an MVC controller from an MVC view, your application will brake common MVC principles. Your code will be hard to debug, hard to test and hard to understand by others.

It, probably, would be a better idea to prepare model attributes for all parts of your view (the main part of the page, header and footer) in one controller. The model that you pass to a JSP view is available in included custom JSP tags and JSPs.

You can use a @ModelAttribute annotated method to supply attributes to a few controller methods at once.

You could use JSP tags instead of JSP pages to define your header and footer (at least that's how I do it in my application).

First of all, your JSP should not "call" directly to any controller.

Secondly, I see you're using Spring framework, and in Spring, from any controller to JSP, there is only 1 model object being passed to the JSP. Therefore if in the header you need to initialise another model, you have to call the URL to the controller instead of calling the header.jsp.

The ther answers already explained that the model should be populated by an controller. ... If you need the same model variables in all pages, for example in the header or footer, the a common way is to enrich the model in a single HandlerInterceptor, instead of every controller method.

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