Skip to main content

[Spring] Spring MVC Configuration - How to set up Spring MVC in IntelliJ

 Setting up Spring MVC configuration in IntelliJ was really such a pain in the ass. I've tried out all of the methods that were floating around the Internet, and have finally found the easiest way to figure it out. There are quite some extensive amount of steps to go through, but as you'll see, it's not that complicated after all.


Setting up Spring MVC configuration in IntelliJ

One thing to note, I'm using IntelliJ IDEA 2022.1 - be aware to use version 2021 or above if you are using Java 17. More info about it here.

1. Ceate a new project from Java Enterprise, and select Web application for the template, and Tomcat for the Application server. This step will already configure the basic template and the server for you.


2. Move the webapp folder to the root directory of the project.


3. Add Spring MVC framework to the project. To do this, right-click on the project, select Add Frameworks Support, and you'll see a window pop up like the image below.
Select Spring MVC and click on OK. 


After the framework has been added to the project successfully, the overall project directory should look like this.


4. Add the Spring artifacts to war exploded. Click on File - Project structure - Artifacts - name:war exploded, and double click on each of the available elements on the right side. 


After double clicking on the elements, the elements should have been moved to the left side.


5. Change web.xml file. Go to <servlet-mapping> section and change *.form into /.


After the change, it should look like this:


6. Change dispatcher-servlet.xml file. As mentioned in the comments, we need to enable component scanning and annotations. Also, define the view by adding the bean with prefix and suffix defined as the screenshot below.


7. Add a 'view' directory to WEB-INF.



8. Go to File - Project Structure - Modules - Web, and refactor the web resource directory by double clicking on the red directory and changing it to the correct address. 


After changing it to the correct address, the directory should no more be shown in red.



And that was it! Now let's test if it is set up all correctly.


Testing the configuration

1. Make a controller. Here, I've named it demo controller, with a simple request mapping to the main-menu page.


2. Make main-menu.jsp in the view folder inside WEB-INF that we have created in the previous steps for the set up.


3. Run the app on Tomcat. After the successful build, the following page should pop up. 

If you're seeing this page, congrats! You've successfully set up Spring MVC configuration in IntelliJ.


Comments

Popular posts from this blog

IntelliJ IDEA Error: Cannot determine path to 'tools.jar' library for 17

[Spring] Spring Inversion of Control(IoC) through XML Configuration