内容简介:在这里我要讲的是如何使用注解进行开发,与上一个项目相比,我们要改的文件如下:从上面的代码,我们可以看到我们的HelloController不用继承Controller类了。我们使用了注解。为了要使注解有效,我们需要在springmvc.xml配置一下相关的信息。我们分析一下上面的配置和我们上一个的项目,有什么不同。
在这里我要讲的是如何使用注解进行开发,与上一个项目相比,我们要改的文件如下:
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 />
会报错,所以我就改了一下命名空间。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Python基础教程
[挪] Magnus Lie Hetland / 袁国忠 / 人民邮电出版 / 2018-2-1 / CNY 99.00
本书包括Python程序设计的方方面面:首先从Python的安装开始,随后介绍了Python的基础知识和基本概念,包括列表、元组、字符串、字典以及各种语句;然后循序渐进地介绍了一些相对高级的主题,包括抽象、异常、魔法方法、属性、迭代器;此后探讨了如何将Python与数据库、网络、C语言等工具结合使用,从而发挥出Python的强大功能,同时介绍了Python程序测试、打包、发布等知识;最后,作者结合......一起来看看 《Python基础教程》 这本书的介绍吧!