简体   繁体   中英

Spring 4 - MVC - URL param and static resource path

I have a spring mvc application, in a page I list the "Group" details in a table, fetched from database. The url of every group is set to "/viewgroup/410", where 410 is the groupid which will be loaded from the database and displayed in the viewgroup.jsp page.

<td><a href="viewgroup/${group.groupid}">${group.name}</a></td>

So, the controller method has the

@RequestMapping("/viewgroup/{groupid}") 
public String viewGroup() {
    ...
}

like this. The jsp pages could not load the static resources which I have in the directory structure

+webapp
  +resources
     +css
     +js
     +images
  +views
    +login.jsp

The jsp pages has the below path for image/js/css.

<link href="resources/css/bootstrap.css" rel="stylesheet" media="screen">

I tried adding

@Controller
@RequestMapping("/viewgroup/**")
public class ViewGroupController {
   ...
}

and this in jsp

<link href="viewgroup/resources/css/bootstrap.css" rel="stylesheet" media="screen">

Still the jsp page loads could not load the static resources. How do I provide the resource path of the static resources in jsp pages when I pass params in the url?

The fact that you pass query parameters through any URL of your project does not affect the way it addresses static resources. You need just to include a link to your static resources (as a relative path for example) as follow :

<link href="/resources/css/bootstrap.css" rel="stylesheet" media="screen">

The resolution of such static resources is completely independent of the page you're currently looking at, be it /viewgroup/410 or /foo/bar . That's the reason why you don't need the "viewgroup" at the beginning of your link's href.

But you do need to tell Spring MVC how it should address such static resources. Usually, this is done in the Spring configuration. For example, if you use Spring MVC java config through an WebMvcConfigurer instance, you should override the addResourceHandlers method in such way :

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }


EDIT : My bad, I thought Spring MVC + any view technology (JSP, Thymeleaf, etc etc) would automatically resolve link's href against the root path of the web-app but this is obviously not true to raw HTML which relative link's href are resolved against current path. So in the end, as found by OP, links are only to be resolved against root path if they are processed with the view technology in use (in the example with JSP : <c:url value="/resources/css/bootstrap.css"/> )

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