You are here: Home / Topics / Map your Controller with the jsp file (Views) in Spring MVC

Map your Controller with the jsp file (Views) in Spring MVC

Filed under: Spring on 2023-08-27 17:24:05

In previous spring topic, we were returning a string from our methods which were written in our controller.

In this topic, we are going to see how to map url with the view


Note: all the views will be stores in WEB-INF folder. You can store anywhere but it is recommended that you store all the views in WEB-INF folder.


Now you have a view (shop.jsp) in your WEB-INF folder. and you want to map this with /shop url.


go to your Shop.java controller find the url and remove @ResponseBody annoation from the method.

Return the path of this view as a string....


Code.

package first.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class Shop {

// @ResponseBody
@RequestMapping("/shop")
public String visitShop() {
 return "/WEB-INF/shop.jsp";
}
}

 


Restart your server and type /first/shop after the default url you will see that your shop.jsp page is loaded in the browser.

but this is not a good practice, we should not write our code with hard coding. Suppose we want to move our all views to a different location. in that condition, it will be very hard to change the hard coded url in all the methods. For resolving this problem we have come accross ViewResolver.

In next topic, we are going the watch this......

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others.