SpringMVC讲义ppt:第3章 Spring MVC的常用注解
- 格式:pptx
- 大小:3.96 MB
- 文档页数:44
在Java的Spring开发中经常使用一些注解,例如 @XXX 等等,在网上看到收集整理碎片知识,便于懒人计划^=^...过去,Spring使用的Java Bean对象必须在配置文件[一般为application.xml] 中进行配置,然后才能使用,但Spring2.5版之后,引入了配置注解功能,操作更简单,但是不了解的就抽象了,所以有必要了解一下一些注解的知识;一,首选注意,注解,注入需要的JAR包,即有common-annotations.jar 包的支持;二,要使用注解的注入功能需要在Spring配置文件[一般为application.xml]进行必要的配置才能使用注解,注入功能,例如下面;参见/blog/16700301.<beans xmlns="...">2.<!-- 添加注解驱动 -->3.<context:annotation-config/>4.5.<!-- 默认扫描的包路径 -->6.<context:component-scan base-package=".xxx"/>7.8.<!--指定默认扫描的包路径,同时指定不扫描的包,如默认扫描包下的Service不扫描-->9. <!--10.<context:component-scan base-package="xx.xxx.yyy"/>11.<context:exclude-filter type="annotation"expression="xx.xxx.yyy.Service"/>12.</context:component-scan>13. -->14.15.<!-- Spring MVC 必须的配置 -->16.<mvc:annotation-driven/>17.18.<!-- 配置js,css等静态文件直接映射到对应的文件夹,不被DispatcherServlet处理 -->19.<mvc:resources location="/resources/"mapping="/resources/**"/>20.21.<!-- 定义一些视图控制器,完成访问路径到返回视图的映射关系 -->22.<mvc:view-controller path="/"view-name="forward:/logon"/>23.<mvc:view-controller path="/permission/login"view-name="permission/login"/>24.<mvc:view-controller path="/permission/logout"view-name="permission/login"/>25.<!-- ...其他Bean的配置... -->26.</beans>其中<context:annotation-config/>的作用是隐式地向 Spring 容器注册如下四个Bean,这是注解,注入功能的驱动:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor具体解释例如:.如果想使用@Resource 、@PostConstruct、@PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor。
SpringMVC常用注解:1、@Controller在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ,然后再把该Model 返回给对应的View 进行展示。
在SpringMVC 中提供了一个非常简便的定义Controller 的方法,你无需继承特定的类或实现特定的接口,只需使用@Controller 标记一个类是Controller ,然后使用@RequestMapping 和@RequestParam 等一些注解用以定义URL 请求和Controller 方法之间的映射,这样的Controller 就能被外界访问到。
此外Controller 不会直接依赖于HttpServletRequest 和HttpServletResponse 等HttpServlet 对象,它们可以通过Controller 的方法参数灵活的获取到。
@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。
分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。
@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器。
单单使用@Controller 标记在一个类上还不能真正意义上的说它就是SpringMVC 的一个控制器类,因为这个时候Spring 还不认识它。
那么要如何做Spring 才能认识它呢?这个时候就需要我们把这个控制器类交给Spring 来管理。
有两种方式:(1)在SpringMVC 的配置文件中定义MyController 的bean 对象。
(2)在SpringMVC 的配置文件中告诉Spring 该到哪里去找标记为@Controller 的Controller 控制器。
SpringMVC 中常用的注解 spring 从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping ,@RequestParam , @ModelAttribute 等等这样类似的注解。
到目前为止,Spring 的版本虽然发生了很大的变化,但注解的特性却是一直延续下来,并不断扩展,让广大的开发人员的双手变的更轻松起来,这都离不开Annotation 的强大作用,今天我们就一起来看看Spring MVC 4中常用的那些注解吧。
1. @ControllerController 控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将试图呈献给用户。
Spring MVC 使用 @Controller 定义控制器,它还允许自动检测定义在类路径下的组件并自动注册。
如想自动检测生效,需在XML 头文件下引入 spring-context:1 2 3 4 5 678910 11 12 <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.spr /schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:p="/schema/p"xmlns:context="/schema/context " xsi:schemaLocation=" /schema/beans /schema/beans/spring-b eans.xsd /schema/context /schema/context/spring -context.xsd"><context:component-scan base-package="org.springframework.s13 amples.petclinic.web"/><!-- ... --></beans>2. @RequestMapping我们可以 @RequestMapping 注解将类似 “/favsoft ”这样的URL 映射到整个类或特定的处理方法上。
springMVC详解以及注解说明基于注释(Annotation)的配置有越来越流行的趋势,Spring 2.5 顺应这种趋势,提供了完全基于注释配置Bean、装配Bean 的功能,您可以使用基于注释的Spring IoC 替换原来基于XML 的配置。
本文通过实例详细讲述了Spring 2.5 基于注释IoC 功能的使用。
概述注释配置相对于XML 配置具有很多的优势:∙ 它可以充分利用Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。
如使用JPA 注释配置ORM 映射时,我们就不需要指定PO 的属性名、类型等信息,如果关系表字段和PO 属性名、类型都一致,您甚至无需编写任务属性映射信息——因为这些信息都可以通过Java 反射机制获取。
∙ 注释和Java 代码位于一个文件中,而XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和Java 代码放在一起,有助于增强程序的内聚性。
而采用独立的XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
因此在很多情况下,注释配置比XML 配置更受欢迎,注释配置有进一步流行的趋势。
Spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分XML 配置的功能。
在这篇文章里,我们将向您讲述使用注释进行Bean 定义和依赖注入的内容。
Spring2.5的注释Spring 2.5 提供了AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 和RequiredAnnotationBeanPostProcessor这四个主要的关于Annotation 的BeanPostProcessor。
详解springmvc常⽤5种注解⼀、组件型注解:1、@Component 在类定义之前添加@Component注解,他会被spring容器识别,并转为bean。
2、@Repository 对Dao实现类进⾏注解 (特殊的@Component)3、@Service ⽤于对业务逻辑层进⾏注解, (特殊的@Component)4、@Controller ⽤于控制层注解, (特殊的@Component)以上四种注解都是注解在类上的,被注解的类将被spring初始话为⼀个bean,然后统⼀管理。
⼆、请求和参数型注解:1、@RequestMapping:⽤于处理请求地址映射,可以作⽤于类和⽅法上。
●value:定义request请求的映射地址●method:定义地request址请求的⽅式,包括【GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.】默认接受get请求,如果请求⽅式和定义的⽅式不⼀样则请求⽆法成功。
●params:定义request请求中必须包含的参数值。
●headers:定义request请求中必须包含某些指定的请求头,如:RequestMapping(value = "/something", headers = "content-type=text/*")说明请求中必须要包含"text/html", "text/plain"这中类型的Content-type头,才是⼀个匹配的请求。
●consumes:定义请求提交内容的类型。
●produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回@RequestMapping(value="/requestTest.do",params = {"name=sdf"},headers = {"Accept-Encoding=gzip, deflate, br"},method = RequestMethod.GET) public String getIndex(){System.out.println("请求成功");return "index";}上⾯代码表⽰请求的⽅式为GET请求,请求参数必须包含name=sdf这⼀参数,然后请求头中必须有 Accept-Encoding=gzip, deflate, br这个类型头。
@Controller@Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写,你也可以自己指定,如下方法一:@Controllerpublic class TestController {}方法二:@Controller("tmpController")public class TestController {}@RequestMapping1.@RequestMapping用来定义访问的URL,你可以为整个类定义一个@RequestMapping,或者为每个方法指定一个。
把@RequestMapping放在类级别上,这可令它与方法级别上的@RequestMapping注解协同工作,取得缩小选择范围的效果。
例如:@RequestMapping("/test")public class TestController {}则,该类下的所有访问路径都在/test之下。
2.将@RequestMapping用于整个类不是必须的,如果没有配置,所有的方法的访问路径配置将是完全独立的,没有任何关联。
3.完整的参数项为:@RequestMapping(value="",method ={"",""},headers={},params={"",""}),各参数说明如下:value :String[] 设置访问地址method: RequestMethod[]设置访问方式,字符数组,查看RequestMethod 类,包括GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE,常用RequestMethod.GET,RequestMethod.POSTheaders:String[] headers一般结合method = RequestMethod.POST使用params: String[] 访问参数设置,字符数组例如:userId=id4.value的配置还可以采用模版变量的形式,例如:@RequestMapping (value="/owners/{ownerId}", method=RequestMethod.GET),这点将在介绍@PathVariable中详细说明。
SpringMvc中的注解详解下⾯我来介绍⼀下SpringMvc中的常⽤的注解1、在配置DispathServlet的时候,为了能扫描到此类,要在类上加@Controller注解。
2、控制反转要⽤到的注解@Resource,这样就可以直接从IOC容器中获取对象了,如果要起别名就要⾃⼰定义并加⼀个value值。
3、@Override注解的作⽤是重写⽅法,经常⽤在实现接⼝的时候。
4、lombok插件中⽐较⽅便的注解@Data//⾃动⽣成set和get和toString@AllArgsConstructor//⽣成所有参数的构造⽅法@NoArgsConstructor//⽆参构造5、当把包中的类放⼊IOC容器中时要加的注解@Component//@Repository//仓库@Service//服务层@Configuration//配置类@Controller五个选⼀个就可以6、如果想直接返回数据的话,就要加@ResponseBody,不然返回的是重定向的视图解析器。
7、⽤Junit测试⼯具的时候要加@RunWith(SpringJUnit4ClassRunner.class)、@ContextConfiguration(locations = "配置⽂件位置")和⼀个@Test注解,通过handler来测试8、@RequestMapping(value="/list")还有get、put、post、delete等注解都是让映射器找到这个⽅法9、⾃定义注解,⾸先创建⼀个注解类⼀定要实现@interface,然后加两个注解(也就是原始注解,注解⾥的注解),如果要起别名还要加⼀个value属性//@Target(ElementType.TYPE)//放在类名上//@Target(ElementType.METHOD)//⽅法@Target(ElementType.FIELD)//字段变量@Retention(RetentionPolicy.RUNTIME)//项⽬运⾏声明周期内有效最后通过⼀个实例来进⼀步说明:⽤⾃定义注解来实现扫描⼀个包下含有controller注解的有⽅法注解的⽅法public class MVCUtil {/*** 根据包名,扫描包* @param pack* @return*/public static List<String> scanPackage(String pack){List<String> classNames = new ArrayList<>();//类加载器ClassLoader loader = Thread.currentThread().getContextClassLoader();//找到指定包下的资源URL url = loader.getResource(pack.replace(".","/"));//⽤.替换/System.out.println(url);File packDir = new File(url.getPath());File[] files = packDir.listFiles();//资源下的⽂件for (File file : files) {// System.out.println(file.getName());//⽂件名String className = file.getName().substring(0, file.getName().lastIndexOf("."));//获取类名// System.out.println(pack+"."+className);//⽂件名classNames.add(pack+"."+className);}return classNames;}/*** 根据给定的类,查找是否包含@Controller注解* @param classNames* @return*/public static List<Class> scanController(List<String> classNames) throws ClassNotFoundException { List<Class> classList = new ArrayList();for (String className : classNames) {//现在只知道类名, classNameClass clazz = Class.forName(className);//根据Class类型获取类的基础信息boolean isController = clazz.isAnnotationPresent(Controller.class);//System.out.println(className +" is Controller "+isController);if(isController){classList.add(clazz);}}return classList;}/*** * 根据类 Class 扫描⽅法有@RequestMapping* ** * url -- {* * class* * Method* ** * }* @return*/public static Map<String, Mapping> handlerMapping(List<Class> controllers){Map<String,Mapping> handlerMapping = new HashMap();for (Class controller : controllers) {// controller.getAnnotations() 所有注解// controller.getDeclaredFields();// 类直接声明的属性Method[] methods = controller.getDeclaredMethods();// 类声明的⽅法System.out.println("类:"+controller.getCanonicalName());for (Method method : methods) {System.out.println("\t"+method.getName());boolean isRequestMapping = method.isAnnotationPresent(RequestMapping.class);if(isRequestMapping){//获取注解RequestMapping rm = method.getAnnotation(RequestMapping.class);handlerMapping.put(rm.value(),new Mapping(controller,method));}}}return handlerMapping;}public static void main(String[] args) throws ClassNotFoundException {String pack = "com.neuedu.controller";//待扫描的包//1List<String> classNames = scanPackage(pack);//2 扫描ControllerList<Class> classList = scanController(classNames);//3 根据Controller注册UrlMap handlerMappings = handlerMapping(classList);System.out.println(handlerMappings);}}。
springmvc框架常⽤注解详解使⽤注解来构造IoC容器通过@controller标注即可将class定义为⼀个controller类。
为使spring能找到定义为controller的bean,需要在applicationContext.xml配置⽂件中注册<context:component-scan base-package="com.maya"/>。
在base-package指明⼀个包。
如果某个类的头上带有特定的注解【@Component/@Repository/@Service/@Controller】,就会将这个对象作为Bean注册进Spring容器。
<!-- 激活组件扫描功能,⾃动扫描通过注解配置的组件 --><context:component-scan base-package="com.om.*"/>1:@Component@Component是所有受Spring 管理组件的通⽤形式,@Component注解可以放在类的头上,@Component不推荐使⽤。
2:@Controller@Controller对应表现层的Bean,也就是Action。
注:实际上,使⽤@component,也可以起到@Controller同样的作⽤。
使⽤@Controller注解标识UserController之后,就表⽰要把UserController交给Spring容器管理,在Spring容器中会存在⼀个名字为"UserController"的action,这个名字是根据UserController类名来取的。
注意:如果@Controller不指定其value【@Controller】,则默认的bean名字为这个类的类名⾸字母⼩写,如果指定value【@Controller(value="UserController")】或者【@Controller("UserController")】,则使⽤value作为bean的名字。
springMVC详解以及注解说明基于注释(Annotation)的配置有越来越流行的趋势,Spring 2.5 顺应这种趋势,提供了完全基于注释配置 Bean、装配 Bean 的功能,您可以使用基于注释的 Spring IoC 替换原来基于 XML 的配置。
本文通过实例详细讲述了 Spring 2.5 基于注释 IoC 功能的使用。
概述注释配置相对于 XML 配置具有很多的优势:??它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。
如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO 的属性名、类型等信息,如果关系表字段和 PO 属性名、类型都一致,您甚至无需编写任务属性映射信息――因为这些信息都可以通过 Java 反射机制获取。
??注释和 Java 代码位于一个文件中,而 XML 配置采用独立的配置文件,大多数配置信息在程序开发完成后都不会调整,如果配置信息和 Java 代码放在一起,有助于增强程序的内聚性。
而采用独立的 XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。
因此在很多情况下,注释配置比 XML 配置更受欢迎,注释配置有进一步流行的趋势。
Spring 2.5 的一大增强就是引入了很多注释类,现在您已经可以使用注释配置完成大部分 XML 配置的功能。
在这篇文章里,我们将向您讲述使用注释进行 Bean 定义和依赖注入的内容。
Spring2.5的注释Spring 2.5 提供了 AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、 PersistenceAnnotationBeanPostProcessor 和 RequiredAnnotationBeanPostProcessor 这四个主要的关于 Annotation 的BeanPostProcessor。
spring mvc注解(Spring MVC注解)spring mvc注解(Spring MVC注解)@Autowired(not recommended, recommended to use @Resource)?@Autowired can annotate member variables, methods, and constructors to complete automatic assembly work.The @Autowired's annotation positions are different, and they all automatically assemble this property when Spring initializes the bean.To enable @Autowired to work, you also need to include the following Xml code in the configuration file?<bean? Class= / >"org.springframework.beans.factory.annotation.AutowiredAnnotationBea nPostProcessor"?@Autowired can annotate members, variables, methods, and constructors@ComponentIs a generalization of the concept that only represents a component (Bean) that can be applied at any level.@ConstrollerUsually at the control level, but the function is the same as@Component.@PostConstructAnnotation methods are triggered when Boss Bean is created at the start of the Spring container@PreDestroyThe annotation method is triggered when the Spring container is destroyed and destroyed when Boss Bean is executed@QualifierThe XX in @Qualifier ("XXX") is the name of Bean, so when @Autowired and @Qualifier are combined, the auto injection policy changes from byType to byName.@Qualifier's annotation objects are member variables, method entry, and constructor admission.@RepositoryWhy can only be marked on the DAO class? This is because the annotation does not only identify the class as Bean, but it also encapsulates the data access exception thrown in the marked class as a data access exception type for Spring. Spring itself provides a rich and has nothing to do with the data access technology specific data access exceptions for different package structure, abnormal persistence layer framework throws, the framework is independent of the underlying abnormalities.@Resource@Resource's role is equivalent to @Autowired, but @Autowired is automatically injected by byType, and @Resource is automaticallyinjected by default by byName@ScopeBy default, the Bean defined by @Component is singleton, and you can use @Scope annotations to achieve the target if you need to use Bean in other scopes@ServiceUsually at the business level, but the function is currently the same as @Component.@TransactionTransaction notes@Component refers to components, and we can use this annotation to annotate components when they are poorly categorized.@Constroller control layer action/constroller@Service business layer service@Repository persistence layer DAOAnnotation principleStart the spring container and load the configuration fileObjects are created for the two classes of student and personWhen parsed to<context:annotation-config></context:annotation-config>An annotation parser that initiates dependency injectionYou will find within the scope of the bean that is included in the spring administration to see which bean attributes have @Resource annotationsIf the value of the name attribute of the @Resource annotation is "", the name of the attribute being annotated matches the bean of the ID in the spring containerIf the match succeeds, the object corresponding to the ID isassigned to the property; if the match fails, matches are made by type; if the match fails, the error is reportedIf the value of the name attribute of the @Resource annotation isnot ',', the value of the name property matches the bean of the ID inthe spring container, if it matchesSuccess is assigned, and if the match fails, the direct error is reportedExplain:Annotations can only be used in reference types。
SpringMVC常⽤注解常⽤注解1. RequestParam注解1. 作⽤:把请求中的指定名称的参数传递给控制器中的形参赋值 (作⽤于形参列表)2. 属性value:请求参数中的名称required:请求参数中是否必须提供此参数,默认值是true,必须提供@RequestMapping("/useRequestParam")public String useRequestParam(@RequestParam("name")String username,@RequestParam(value="age",required=false)Integer age){System.out.println(username+","+age);return "success";}2. RequestBody注解1. 作⽤:⽤于获取请求体的内容(注意:get⽅法不可以)2. 属性required:是否必须有请求体,默认值是true<form action="springmvc/useRequestBody" method="post">⽤户名称:<input type="text" name="username" ><br/>⽤户密码:<input type="password" name="password" ><br/>⽤户年龄:<input type="text" name="age" ><br/><input type="submit" value="保存"></form>@RequestMapping("/useRequestBody")public String useRequestBody(@RequestBody(required=false) String body){System.out.println(body);return "success";}3. PathVariable注解1. 作⽤:拥有绑定url中的占位符的。
SpringMVC注解详解spring mvc 中有很多的注解,每个注解都有⾃⼰的功能,下⾯我们就对spring mvc中的注解⼀⼀作出介绍。
关于spring的注解还没有总结,请等待后续blog更新。
@controllerorg.springframework.stereotype.Controller注解类型⽤于指⽰当前类是⼀个控制器。
Spring使⽤扫描机制查找应⽤程序中所有基于注解的控制器类,分发器会扫描使⽤该注解类的⽅法,并检测⽅法是否使⽤了@RequestMapping注解,只⽤使⽤了@RequestMapping注解的⽅法才能⽤来处理请求。
为了保证spring能找到控制器,需要完成两件事情:在spring mvc的配置⽂件的头⽂件中引⼊spring-context。
在spring mvc 的配置⽂件中使⽤,该元素的功能是启动包扫描功能,以便注册有@Controller、@Service、@Repository、@Component等注解的类成为spring的bean。
<context:component-scan base-package = "com.chris.controller"/>@RequestMapping该注解类型指⽰spring⽤哪⼀个类或⽅法来处理请求动作,可以⽤于类或⽅法。
@Controller// RequestMapping可以⽤来注释⼀个控制器类,此时,所有⽅法都将映射为相对于类级别的请求,// 表⽰该控制器处理所有的请求都被映射到 user属性所指⽰的路径下@RequestMapping(value="/user")public class UserController{// 映射请求 user/register@RequestMapping(value="/register",method=RequestMethod.GET)public String registerForm() {// 跳转到注册页⾯return "registerForm";}// 映射请求 user/login@RequestMapping("/login")public String login( Model model) {return "loginForm";}}@RequestMapping可以指定⼀些属性value:⽤来映射⼀个请求和⼀个⽅法,是其默认属性,如果在使⽤@RequestMapping时只有这个属性,则可以省略关键字value.method:该属性⽤来指定该⽅法仅仅处理哪些HTTP请求的处理⽅式,例如GET、POST。
springmvc注解总结1、@RequestMapping@RequestMappingRequestMapping是⼀个⽤来处理请求地址映射的注解(将请求映射到对应的控制器⽅法中),可⽤于类或⽅法上。
⽤于类上,表⽰类中的所有响应请求的⽅法都是以该地址作为⽗路径。
RequestMapping请求路径映射,如果标注在某个controller的类级别上,则表明访问此类路径下的⽅法都要加上其配置的路径;最常⽤是标注在⽅法上,表明哪个具体的⽅法来接受处理某次请求。
@Controller@RequestMapping(value="/book")public class BookController {@RequestMapping(value="/title")public String getTitle(){return "title";}@RequestMapping(value="/content")public String getContent(){return "content";}}RequestMapping的属性value:指定请求的实际url(1)普通的具体值。
如前⾯的value="/book"。
(2)含某变量的⼀类值。
@RequestMapping(value="/get/{bookId}")public String getBookById(@PathVariable String bookId,Model model){model.addAttribute("bookId", bookId);return "book";}路径中的bookId可以当变量,@PathVariable注解即提取路径中的变量值。