SpringMVC_总结_03_SpringMVC相关注解

一、前言

在前面的小节中,我们配置了注解驱动和自动扫描包,然后就可以使用SpringMVC相关注解了。

二、@Controller

@Controller用来修饰类,源码如下:

package org.springframework.stereotype;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    String value() default "";
}

(1)被@Component修饰,说明此注解用来标识一个bean。

(2)用来说明被修饰的类为控制器类。

三、@RequestMapping

1.属性详解

@RequestMapping注解用来修饰类或方法,源码如下:

package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String[] value() default {};

    RequestMethod[] method() default {};

    String[] params() default {};

    String[] headers() default {};

    String[] consumes() default {};

    String[] produces() default {};
}

(1) value

value属性用将请求URL(如"/hello") 映射到整个类或特定的处理方法上。

value属性是RequestMapping的默认属性,也就是说  @RequestMapping( value = "/hello")   可以写成 @RequestMapping("/hello") 。

(2)method

method 属性用来指定如下请求方式:GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.

2.注解简化

@RequestMapping(value= "/hello",Method=RequestMethod.GET ) 可简写成 @GetMapping("/hello")

类似注解还有:

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
  • @PatchMapping

四、参数Bean

Spring 会为如下类型的参数自动注入其bean对象。

见:https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-arguments

五、方法参数

可用如下注解用来修饰请求参数。

1.@RequestParam

可通过RequestParam来接收请求参数

@Controller
@RequestMapping("/pets")
public class EditPetForm {

    // ...

    @GetMapping
    public String setupForm(@RequestParam("petId") int petId, Model model) {
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }

    // ...

}


[email protected]

通过此注解可以获取请求头相关信息。

例如,一个请求头为:

Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300

则可以通过如下方式获取请求头信息

@GetMapping("/demo")
public void handle(
        @RequestHeader("Accept-Encoding") String encoding,
        @RequestHeader("Keep-Alive") long keepAlive) {
    //...
}

3.@CookieValue

获取cookie

@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) {
    //...
}

[email protected]PathVariable 

可通过@PathVariable 来接收路径变量

@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {

    @GetMapping("/pets/{petId}")
    public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
        // ...
    }
}

[email protected]ModelAttribute

标注在方法参数上的@ModelAttribute说明了该方法参数的值将由model中取得。如果model中找不到,那么该参数会先被实例化,然后被添加到model中。在model中存在以后,请求中所有名称匹配的参数都会填充到该参数中。

@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute Pet pet) { }

以上面的代码为例,这个Pet类型的实例可能来自哪里呢?有几种可能:

  • 它可能因为@SessionAttributes标注的使用已经存在于model中
  • 它可能因为在同个控制器中使用了@ModelAttribute方法已经存在于model中——正如上一小节所叙述的
  • 它可能是由URI模板变量和类型转换中取得的(下面会详细讲解)
  • 它可能是调用了自身的默认构造器被实例化出来的

原文地址:https://www.cnblogs.com/shirui/p/9575707.html

时间: 2024-08-01 17:41:20

SpringMVC_总结_03_SpringMVC相关注解的相关文章

Spring bean依赖注入、bean的装配及相关注解

依赖注入 Spring主要提供以下两种方法用于依赖注入 基于属性Setter方法注入 基于构造方法注入 Setter方法注入 例子: public class Communication { private Messaging messaging; /* * DI via Setter */ public void setMessaging(Messaging messaging){ this.messaging = messaging; } public void communicate(){

session中持久化对象的相关状态转换和相关注解的使用

session的merge()方法可将程序对脱管对象所做的修改保存到数据库,但merge()于update()方法的最大区别:merge()方法不会持久化给定的对象,只返回对象的副本,该副本处于持久化状态,使用mergen()方法来保存程序对脱管对象所做的修改时,如果session中存在相同持久化标识的持久化对象,merge()方法里提供的对象状态将覆盖原有的持久化实例. 在session中使用LockOptions对象锁 News n = Session.get(News.class,pk,L

Spring注解:Enable相关注解

@EnableXXX:可以用于取代xml配置中的一些配置,被该注解所标注的类,其中被@Bean标注的方法,一般就用于返回和EnableXXX的XXX相关的Bean,Bean中一般有XXX相关的注解 同时,更高级的,Spring中一般还有一个XXXConfigurer的接口,在注解为@EnableXXX的类中,实现该接口,重写接口中方法(XXXRegistrar xxxRegistror),可以达到更强大的注册功能

JPA相关注解

JPA注解 一.基本注解 1.表相关 @Entity   仅仅要加了这个注解就具备了表和实体的映射关系,表名就是实体名 @Table(name="表名")    一般和实体注解一起使用映射表名 2.属性相关 @Column(name="id",length=11,nullable=false)   实体属性和表字段映射(字段和属性同样能够不须要此注解)属性unique.nullable.length @GeneratedValue(strategy=Generati

springmvc4 相关注解的详细讲解

[email protected] Controller控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将试图呈献给用户.Spring MVC 使用 @Controller 定义控制器,它还允许自动检测定义在类路径下的组件并自动注册.如想自动检测生效,需在xml头文件下引入 spring-context: <?xml version="1.0" encoding="UTF-8"?> <beans xml

Spring MVC 相关注解

@InitBinder 类型转换,一般用于时间转换或者数据类型转换. 页面上时间传递字符串,DB中是datetime 例: 1 private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 2 3 @InitBinder 4 public void dataBinder(WebDataBinder dataBinder) { 5 dataBinder.registerCustomEditor(Date

[email&#160;protected]相关注解总结

下面来介绍如何使用@Condition [html] view plain copy public class TestCondition implements Condition { /** * 只有返回true,才会启用配置 */ public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { return true; } } @Conditional(TestCondition.class

Hibernate @IdClass @EmbeddedID相关注解

Hibernate Annotations Mapping composite primary keys and foreign keys to composite primary keys: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#d0e2177 引用Composite primary keys use a embedded class as the primary key repres

Spring中@相关注解的意义

1.@controller 控制器(注入服务) 用于标注控制层,相当于struts中的action层 2.@service 服务(注入dao) 用于标注服务层,主要用来进行业务的逻辑处理 3.@repository(实现dao访问) 用于标注数据访问层,也可以说用于标注数据访问组件,即DAO组件. 4.@component (把普通pojo实例化到spring容器中,相当于配置文件中的 <bean id="" class=""/>) 泛指各种组件,就是说