基于注解的 Spring MVC与基于xml的配置(参考Spring MVC入门级实例-基于xml的配置)大部分都一样,下面来比较一下
1.web.xml 与基于xml的配置一样
2.springMVC-servlet.xml与基于xml的配置一样
3.applicationContext.xml配置如下
<!-- 启动注解驱动的Spring MVC功能,注册请求url和注解POJO类方法的映射-->
<mvc:annotation-driven />
<!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean -->
<context:component-scan base-package="com.ldh.mvc"/>
<!--通过url中的method参数指定要执行的controller方法-->
<bean id="methodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName">
<value>method</value>
</property>
<property name="defaultMethodName">
<value>view</value>
</property>
</bean>
可以看到这里启动了"context:component-scan"配置,去掉了url与controller的映射关系,因为url与controller的映射关系会在注解里指定
4.controller文件
@org.springframework.stereotype.Controller
@RequestMapping("/index.html")
public class IndexController implements Controller{
@RequestMapping
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
System.out.println("Hello index=================");
Map<String,String> resultMap = new HashMap<String,String>();
resultMap.put("message", "欢迎来到首页");
return new ModelAndView("/index", resultMap);
}
}
方法上的RequestMapping注解一定要指定,不要找不到要执行的controller方法
@Controller
@RequestMapping("/user/operation.html")
public class InternalPathController extends MultiActionController{
@RequestMapping(params="method=update")
public ModelAndView update(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String,String> resultMap = new HashMap<String,String>();
resultMap.put("message", "消息更新成功");
return new ModelAndView("/page/update", resultMap);
}
@RequestMapping(params="method=delete")
public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String,String> resultMap = new HashMap<String,String>();
resultMap.put("message", "消息删除成功");
return new ModelAndView("/page/delete", resultMap);
}
}
5.访问路径通与基于xml的配置一样