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>