Spring MVC 示例

Srping MVC项目结构如下:

一、首先创建一个Dynamic Web Project

二、WebContent/WEB-INF/文件夹下新增 web.xml,配置servlet  

  容器对于web.xml的加载过程是context-param >> listener  >> filter  >> servlet,本例子中只配置了servlet,其余按默认配置。
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC Application</display-name>

    <servlet>
        <servlet-name>HelloWeb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        
        <!-- 用于配置spring mvc的配置文件的位置和名称,对应的是下一步(步骤三)中的springmvc.xml -->
        <!-- 也可以不用配置<init-para>,默认的配置文件为/WEB-INF/[servlet-name]-servlet.xml,此项目中为WEB-INF文件夹下新增HelloWeb-servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/config/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWeb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

二、WebContent/WEB-INF/config文件夹下新增springmvc.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   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-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   
   <!-- spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean -->
   <context:component-scan base-package="com.mousewheel" />
   
   <!-- 视图解析器,用于将控制器中handler的结构解析为实际的物理视图 -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>
</beans>

三、新增Controller,HelloController.java

package com.mousewheel.springmvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController {

    @RequestMapping(method = RequestMethod.GET)
    public void printHello(ModelMap model) {
        model.addAttribute("message", "Spring MVC Framework!");
    }
}

四、新增页面,hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h2>Hello, ${message}</h2>
</body>
</html>

 

运行结果:

 

posted @ 2017-09-17 17:50  鼠标滚轮  阅读(131)  评论(0编辑  收藏  举报