在这里我要讲的是如何使用注解进行开发,与上一个项目相比,我们要改的文件如下:
HelloController.java
springmvc-servlet.xml
复制代码
HelloController.java
package com.xgc.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HelloController{
@RequestMapping("/hello")
public ModelAndView hello(HttpServletRequest req, HttpServletResponse res) {
ModelAndView mv=new ModelAndView();
mv.addObject("msg","hello annotation");
mv.setViewName("hello");
return mv;
}
}
复制代码
从上面的代码,我们可以看到我们的HelloController不用继承Controller类了。我们使用了注解。为了要使注解有效,我们需要在springmvc.xml配置一下相关的信息。
springmvc.xml
<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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tool
http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven />
<context:component-scan base-package="com.xgc.controller" />
</beans>
复制代码
我们分析一下上面的配置和我们上一个的项目,有什么不同。
可以看到我们的handler mapping和handler adapter都不用配置了。取而代之的是我们用了下面的两段代码
<mvc:annotation-driven />
<context:component-scan base-package="com.xgc.controller" />
复制代码
第一句代码的意思是,自动注册DefaultAnnotationHandlerMapping
与AnnotationMethodHandlerAdapter
两个bean。即自动帮我们配置了handler mapping和handler。这就是为什么我们可以不用配置这两个bean的原因了。
第二句代码的意思是,扫描指定包下面的controller,所有使用了注解的类都要放在这个类下面,不然就会报错。
注:要注意的是,在这个springmvc.xml中的命名空间与上一个项目的命名空间有一点不同,因为在原先的命名空间中,<mvc:annotation-driven />
会报错,所以我就改了一下命名空间。
测试
在配置好了之后,我们当然要看看能不能成功运行啦
输入 http://localhost:8080/02springweb_annotation/hello.do, 我们就可以看到下面的效果了