How to handle addressing to static pages in Spring MVC

别等时光非礼了梦想. 提交于 2019-11-30 14:38:22

I just have found a great solution for it, to handle static pages we can use <mvc:view-controller> in servlet, sample code is here and here, it works with Tiles as well just make sure you have a definition for each path in your tiles.xml file.

 <mvc:view-controller path="/index" />
 <mvc:view-controller path="/"  view-name="index"/>

The way you have done it should work, but creating a new Mapper function for each static page is not a good idea. What you can do is in your controller

@RequestMapping("/page/{viewName}.htm")
public String index(@PathVariable(value="viewName") String viewName, Model model){
    if(isValidView(viewName)){
        model.addAttribute("viewName", viewName);
        return "page";
    }

    return null;
}

But you have to make sure the viewName is valid otherwise it would be security issue.

Also read this article

edit

isValidView function would can go either same class or BaseController class or a service call to check againts DB. Checking that file exists is not a good idea not because is takes resources but because the Path can be different on production server.

If the body of static page is just HTML you can load the content in DB and just do

<jsp:include page="/WEB-INF/pages/header.jsp"/>
${htmlContent}
<jsp:include page="/WEB-INF/pages/footer.jsp"/>

OR if you want to keep the body dynamic.

for tiles.xml you can have

<definition name="pageLayout" extends="baseLayout">
    <put-attribute name="title" value="HELERE"/>
      <put-attribute name="body" value="/WEB-INF/page.jpg"/>
</definition>

for page.jsp

<jsp:include page="/WEB-INF/pages/header.jsp"/>
<jsp:include page="/WEB-INF/pages/page/${viewName}.jsp"/>
<jsp:include page="/WEB-INF/pages/footer.jsp"/>

Well you could always load everything on the baseLayout page and create a higher level. What i mean is something like the following :

<div id=header> <tiles:insertAttribute name="header" /></div>
<div id=header> <tiles:insertAttribute name="menu" /></div> <iframe id='dynFrame' contenteditable="true"></iframe>' <div id=footer> <tiles:insertAttribute name="footer" /></div>

Now you can load content to this iframe from menu clicks with a simple script that says : loadPage(pageLink); And for the content of the function could be : $("#dynFrame").attr("src",pageLink);
The menu clicks can pass urls to the loadPage function and you would have only one copy of any static page you want to load.

I hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!