美文网首页
Spring MVC hello world annotatio

Spring MVC hello world annotatio

作者: lovePython | 来源:发表于2015-08-19 09:41 被阅读22次

HelloWorldController.java

package com.mkyong.common.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/welcome")
public class HelloWorldController{  
    @RequestMapping(method = RequestMethod.GET) 
    public ModelAndView helloWorld(){       
        ModelAndView model = new ModelAndView("HelloWorldPage");        
        model.addObject("msg", "hello world");      
        return model;   
    }
}

Spring XML Configuration

/WEB-INF/spring-mvc-config.xml

<beans xmlns="http://www.springframework.org/schema/beans"  
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
             xmlns:context="http://www.springframework.org/schema/context"   
             xsi:schemaLocation="http://www.springframework.org/schema/beans    
                                               http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
                                               http://www.springframework.org/schema/context    
                                               http://www.springframework.org/schema/context/spring-context-2.5.xsd">   
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">      
        <property name="prefix">            
            <value>/WEB-INF/pages/</value>      
        </property>     
       <property name="suffix">         
           <value>.jsp</value>      
        </property> 
    </bean>     
    <context:component-scan base-package="com.mkyong.common.controller" />
</beans>

6. web.xml

web.xml

<?xml version="1.0"?>
<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 Web MVC Application</display-name>
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
</web-app>

先看web.xml,在web.xml中配置了一个servlet(DispatcherServlet),这个servlet的参数是spring配置文件的位置,就这样结束了。

相关文章

网友评论

      本文标题:Spring MVC hello world annotatio

      本文链接:https://www.haomeiwen.com/subject/xmcgqttx.html