Spring MVC Annotation & Convention Over Configuration

Spring MVC Annotation & Convention Over Configuration

Spring MVC在使用annotation进行配置controller时候要注意:两种urlmapping的模式不能同时使用,如果使用annotation就不能再配置urlmapping了。

<action>-servlet.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p" 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">

 <!-- 对com.founder.action包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
 <context:component-scan base-package="com.founder.action"/>
 
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
 
<!--把请求的URL映射到Controller的name上面 -->
 <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/> 
  
 <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀-->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="viewClass">
   <value>org.springframework.web.servlet.view.JstlView</value>
  </property>
  <property name="prefix">
     <value>/jsp/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>

</beans>


package com.founder.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;


@Controller
@RequestMapping
public class HelloController{
 @RequestMapping
 public String world(){
  String name = "Eric";
  System.out.println("name is = " + name);
  return "hello";
 }
 
 @RequestMapping
 public String test() {
  String name = "test";
  System.out.println("name is = " + name);
  return "test";
 }
 
}

你可能感兴趣的:(Spring MVC Annotation & Convention Over Configuration)