Spring MVC 03 - Create your first spring mvc program using eclipse

1. Let's look at the final effect first. Enter http://localhost:8080/FirstSpringMVCPro/welcome.html in the browser address bar, and the result is as follows:


2. It takes 4 steps to achieve the above results. Next, we will explain them one by one.

2.1 Modify the web.xml file, the modified content is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>FirstSpringMVCPro</display-name>
  <servlet>
 <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>spring-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

2.2 Create the spring-dispatcher-servlet.xml file in the WEB-INF folder with the following contents:

<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  <bean id="HandlerMapping" 
    class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

  <bean name="/welcome.html" class="com.haha.HelloController"/>

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

2.3 Create a new class HelloController.java in the src directory and extend the AbstractController class (org.springframework.web.servlet.mvc.AbstractController). In the handleRequestInternal method, enter the following:

ModelAndView modelandview = new ModelAndView("HelloPage");
   modelandview.addObject("welcomeMessage","Hi, this is first spring mvc application");
   return modelandview;

2.4 Create a new jsp file HelloPage.jsp in the WEB-INF directory, the content of the file is:

<html>
  <body>
    <h1>First Spring MVC Application Demo</h1>
    <h2>${welcomeMessage}</h2>
  </body>
</html>

Finally, put the project into the tomcat server to run, and enter http://localhost:8080/FirstSpringMVCPro/welcome.html in the browser to get the expected result


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326091112&siteId=291194637