Skip to main content

Create a Spring MVC web app in Eclipse


I take http://o7planning.org/web/fe/default/en/document/8108/spring-mvc-tutorial-for-beginners site as a reference for this blog post.

First create a maven project. (Be in the Spring mode to do this)
                                      File -> New -> Maven Project

Select the "Use default Workspace location" option and click Next.

Under the "Select an Archetype" window, in "Filter" text field, type the word "webapp". Then from the listed set, select maven-archetype-webapp and click Next.

Here you can specify a Group ID and an Artifact ID for the project and click on Finish to finish creating the basic structure of the project.

Now you are ready to go with the implementation stuff.

If you want to change the JRE for the project, right click on the "JRE System Library" folder and select "Properties". Here, the "Execution Environment" and the "Alternate JRE" options could be changed to the required JRE.

To convert this maven project to a Spring project, do the following.
     Right click on the project folder in the "Package Explorer" Window on to the left of the IDE -> Spring Tools -> Add Spring Project Nature
(If you can't see the Spring Tools option, just click the down arrow at the very bottom of the dropdown menu. It is at the very bottom of the list. :))

Create a new folder called "java" under src/main.

Then you need to change the project pom.xml to include the required dependencies.
Include these dependencies in this pom.xml file.

<!-- Servlet Library -->
       <dependency>
           <groupId>javax.servlet</groupId>
           <artifactId>javax.servlet-api</artifactId>
           <version>3.1.0</version>
           <scope>provided</scope>
       </dependency>
       <!-- Spring dependencies -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>4.1.4.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-web</artifactId>
           <version>4.1.4.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-webmvc</artifactId>
           <version>4.1.4.RELEASE</version>
       </dependency>

Then edit the web.xml file

  id="WebApp_ID" version="3.0">
  
  <display-name><PUT-YOUR-DISPLAY-NAME-HERE></display-name>
  
  <servlet>
      <servlet-name><PUT-YOUR-SERVLET-NAME-HERE></servlet-name>
      <servlet-class>
          org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>   
  
  <servlet-mapping>
      <servlet-name><PUT-YOUR-SERVLET-NAME-HERE></servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
   <!-- Other XML Configuration -->
  <!-- Load by Spring ContextLoaderListener -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/<ROOT-CONTEXT-NAME>.xml</param-value>
  </context-param>
  
   <!-- Spring ContextLoaderListener -->
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
</web-app>

Now create a file named <SERVLET-NAME>-servlet.xml under the /WEB-INF directory and put the following code in it.

<?xml version="1.0" encoding="UTF-8"?>
  <context:component-scan base-package="<YOUR-BASE-PACKAGE-NAME>say com.tutorials.controller as in this example" />
  
  <context:annotation-config />
  
  <bean
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      
      <property name="prefix">
          <value>/WEB-INF/view/</value>
      </property>
      
      <property name="suffix">
          <value>.jsp</value>
      </property>       
      
  </bean>
  
</beans>

Then create another file named <ROOT-CONTEXT-NAME>.xml and put the following code in it.

<?xml version="1.0" encoding="UTF-8"?>
 <!-- Empty -->
</beans>

Create a new folder named "view" under the /WEB-INF directory. This folder will contain the views (.jsp files) that will be used in our web application.

Now you can write a controller for the sample application as follows. Create a new file called HelloWorldController.java in a new package created under src/main/java/ called say"com.tutorials.controller".

package com.tutrials.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
   @RequestMapping("/hello")
   public String hello(Model model) {
        
       model.addAttribute("greeting", "Hello Spring MVC");
        
       return "helloworld";
        
   }
}

Now it's time to write the view.

Create a new file named helloworld.jsp under the view folder created inside the /WEB-INF folder.
Put the following code in it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring4 MVC -HelloWorld</title>
</head>
<body>
   <h1>${greeting}</h1>
</body>
</html>

Now before running the application that we just created, we need to build the project using maven. For that, right click on the project and select Run As -> Maven Install.

The build will be successful if the project was created successfully with correct dependencies an all.

Now you need to setup the run configurations.
Go to Run -> Run Configurations.
Then right click on Maven Build -> New.
Enter the requested parameters under the Main tab.

As the goal specify "install". Now you can run the maven build for the project by selecting that configuration by name.
Remember not to lose the MANIFEST.MF file in the project structure. You can either disable it.

Now run the project on the server. (WildFly in my case) you can access the view through the request mapping specified in the controller on localhost.

We are done now. Cheers! Happy coding with Spring. :)



Comments

Popular posts from this blog

How to connect my database instance with elastic beanstalk instance in AWS?

If you have deployed your web application in Elastic Beanstalk in AWS and now you need to connect a database to this instance, and your database is actually residing in a different instance, how can you actually connect them? It's easy with Elastic Beanstalk. I will explain an example scenario that I used for connecting my elastic beanstalk web application with another instance containing my MongoDB database. By looking at this, you can customize as per your need. Don't worry. This is easy. :) The only things you need here are the details about the 1. Database name that you need to connect to. Ex:- "myDB" 2. Port at which the database instance is listening. EX:- In the case of MongoDB, the listening port is 27017 3. Host name of your database instance. EX:- Like localhost, in this case, it will be the Public DNS of your database instance 4. The password of your database if exists. First these details need to be set as environment variables in Elastic Be

How to import the Public Certificate of one WSO2 product to the trust store of another?

To demonstrate this point, I will use the 2 products WSO2 API Manager 2.1.0 (referred as APIM from here onwards) and WSO2 Enterprise Integrator 6.1.1 (referred as EI from here onwards). When using EI as the Business Process Server during configuration of Workflows in APIM, one step to perform is to import the public certificate of EI to the truststore of APIM [1]. So now let's see how this can be done. Step 1: Go to <EI_HOME>/repository/resources/security/ folder and execute the following keytool command. This command is used to export the public certificate of EI as a certificate file called wso2carbon.cer. Since the default keystore in EI is wso2carbon.jks, we have specified it as the keystore and the default alias is wso2carbon. Provide wso2carbon as the keystore password when prompted as it is the default password. After executing the above command from within the security folder in EI, you will see that a file with the name of wso2carbon.cer is created