美文网首页
Spring 3 MVC hello world example

Spring 3 MVC hello world example

作者: lovePython | 来源:发表于2015-08-19 14:11 被阅读18次

HelloController.java

package com.mkyong.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController { 

    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String printWelcome(ModelMap model) { 
        model.addAttribute("message", "Spring 3 MVC Hello World"); 
        return "hello"; 
    } 
    
    @RequestMapping(value = "/hello/{name:.+}", method = RequestMethod.GET) 
    public ModelAndView hello(@PathVariable("name") String name) { 
        ModelAndView model = new ModelAndView(); 
        model.setViewName("hello"); 
        model.addObject("msg", name); 
        return model; 
    }
}

Spring XML Configuration

spring-web-servlet.xml

<?xml version="1.0" encoding="utf-8"?>

<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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  <context:component-scan base-package="com.mkyong.web"/>  
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    <property name="prefix"> 
      <value>/WEB-INF/views/jsp/</value> 
    </property>  
    <property name="suffix"> 
      <value>.jsp</value> 
    </property> 
  </bean>  
  <mvc:resources mapping="/resources/**" location="/resources/"/>  
  <mvc:annotation-driven/> 
</beans>

web.xml

<?xml version="1.0"?>
<servlet>
    <servlet-name>spring-web</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>spring-web</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

相关文章

网友评论

      本文标题:Spring 3 MVC hello world example

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