jdev
jdev

Reputation: 159

Remove prefix and suffix of page url in spring MVC

I created controller using spring mvc:

@Controller
public class MyController {


@RequestMapping("/")

public String showHome() {

return  “/WEB-INF/pages/home.jsp";

}



@RequestMapping(“/users")
    public String showUser() {
        return "/WEB-INF/pages/users.jsp";
}

}

I want to avoid writing this /WEB-INF/pages in each method and controller, is there any way to write only the name of jsp page (with folder or without), and the application returned the correct page?

Upvotes: 3

Views: 2663

Answers (1)

Safwan Hijazi
Safwan Hijazi

Reputation: 2089

Use Spring MVC InternalResourceViewResolver by adding this in spring configuration file:

<bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

and only return "home" in the controller

In your annotation-driven configuration the InternalResourceViewResolver should be set in the configuration class which extends WebMvcConfigurerAdapter like such:

    @Bean
    public ViewResolver getViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/pages/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

Upvotes: 5

Related Questions