首页 > 代码库 > SpringMvc的xml配置与annotation配置的例子的区别

SpringMvc的xml配置与annotation配置的例子的区别

1.导入jar包时,要在xml配置基础上加 spring-aop-4.2.2.RELEASE.jar (注解的时候需要)

2.编写controller的时候要annotation需要做相关配置即红色部分,而xml就是要实现controller的接口

(a)annotation配置时

package com.spring.hello;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
@Controller
public class HelloController {
  @RequestMapping("/hello")
  public ModelAndView hello(HttpServletRequest req,HttpServletResponse resp)
  {   
        ModelAndView mv=new ModelAndView();
        mv.addObject("msg", "第一个annotation");
        mv.setViewName("Hello");
        return mv;
  }
}

  

(b)xml配置时
package com.spring.hello;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloController implements Controller{

@Override
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
// TODO Auto-generated method stub
ModelAndView mv=new ModelAndView();
mv.addObject("msg", "第一个SpringMvc");
mv.setViewName("Hello");
return mv;
}

}

3.在SpringMvc文件annotation不需要

<!--  配置hanlderMapping  -->
	<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
	<!--  配置 handlerAdapter-->
	<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
	

但是要把

<!--  配置请求和处理器	-->
	<bean  name="/hello.do" class="com.spring.hello.HelloController"></bean>

  修改成

	<!--  配置请求和处理器	-->
	<context:component-scan base-package="com.spring.hello"></context:component-scan>

  

SpringMvc的xml配置与annotation配置的例子的区别