Spring 三、Spring-MVC及其常用注解

创建MVC步骤

导入Spring MVC包

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${sping-version}</version>
</dependency>

在web.xml配置

<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
          <param-name>contextConfigLocation</param-name>
      	    <!--  加载配置文件 -->
          <param-value>classpath:spring-mvc.xml</param-value>
      </init-param>
      <!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

在resources中创建spring-mvc.xml

<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
 		http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--扫描-->
<!--如果spring已经有扫描所有的包,下面这句可以省略-->
<context:component-scan base-package="com.werner.controller"/>
<!-- 开启springmvc注解 -->
<mvc:annotation-driven/>
                                                            
                                                            
<!--不要处理静态资源-->
<mvc:default-servlet-handler/>
<!-- 推荐 不要处理资源文件 -->                                                           
<mvc:resources mapping="/images/**" location="/WEB-INF/img"/>
<mvc:resources mapping="/js/**" location="/WEB-INF/js"/>
<mvc:resources mapping="/css/**" location="/WEB-INF/css"/>
<mvc:resources mapping="/view/**" location="/WEB-INF/view"/>
                                                            
                                                            <

<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      id="internalResourceViewResolver">
  <!-- 前缀 -->
  <property name="prefix" value="/WEB-INF/jsp/" />
  <!-- 后缀 -->
  <property name="suffix" value=".jsp" />
</bean>

MVC注解部分

一、@Controller

作用

负责注册一个bean 到spring 上下文中

栗子

@Controller  
public class UserController{
}  

二、@RequestMapping(重点)

作用

这个注解主要作用其实就是一个路径.专业名字叫关系映射.他一般用于 Controller 的类与某个方法中

栗子

使用到类或者方法上

@Controller
@RequestMapping("/account")
public class AccountController {
  	//  访问地址  /account/login
    @RequestMapping("/login")
    public String login() {
        return "登录";
    }
}

参数说明

参数 说明
String[] value() **(重点)**指定请求的实际地址,指定的地址可以是URI Template 模式 等同path
RequestMethod[] method() **(重点)**指定请求的method类型, RequestMethod.GET、RequestMethod.POST、RequestMethod.PUT、RequestMethod.DELETE等;
String[]consumes 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
String[] produces 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
String[] params() **(掌握)**指定限制请求参数的条件。支持简单的表达式。就是请求地址上的key=value
String[] headers() 指定request中必须包含某些指定的header值,才能让该方法处理请求;

三、@RequestBody

作用

该注解用于读取Request请求的body部分数据(get请求没有请求体,所以不能使用)

栗子

@Controller
@RequestMapping("/body")
public class RequestBodyController {
    @RequestMapping(value = "/test1", method = RequestMethod.POST)
    public String method1(@RequestBody String name) {
        System.out.println(name);
        return "请求体参数";
    }
}

属性

参数 说明
boolean required() 是否必须有请求体。默认值是:true。当取值为 true 时,

四、@ResponseBody

作用

该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后

五、@RequestParam

作用

在处理方法入参处使用 @RequestParam 可以把请求参数传递给请求方法

集成fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>

配置转化器

<!-- 设置配置方案 -->
  <mvc:annotation-driven>
        <!-- 消息转化器  -->
        <mvc:message-converters register-defaults="false">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <!-- 加入支持的媒体类型:返回contentType -->
                <property name="supportedMediaTypes">
                    <list>
                        <!-- 这里顺序不能反,一定先写text/html,不然IE下会出现下载提示 -->
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json;charset=UTF-8</value>
                    </list>
                </property>
                <property name="fastJsonConfig">
                    <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
                        <property name="features">
                            <list>
                                <value>AllowArbitraryCommas</value>
                                <value>AllowUnQuotedFieldNames</value>
                                <value>DisableCircularReferenceDetect</value>
                            </list>
                        </property>
                        <!--配置特定的日期格式-->
                        <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

引用fastjson之后

@Controller
public class ResponseBodyController {
    @RequestMapping("/body")
    @ResponseBody
    public Shop testResponseBody() {
        Shop shop = new Shop();
        shop.setShopId(1);
        shop.setName("娃娃");
        shop.setTitle("白天么么哒,晚上怕怕怕");
        return shop;
    }
}

栗子

给参数起别名

@Controller
@RequestMapping("/params")
public class RequestParamController {
    @RequestMapping("/test1")
    public String method1(@RequestParam(value = "name") String username) {
        System.out.println(username);
        return "参数别名"
    }
}
//请求地址 /params/test1?name='乔碧萝殿下'

使用默认值参数

@RestController
@RequestMapping("/params")
public class RequestParamController {
  	// 请求地址  /params/test2?page=1 或者/params/test2?page=1&size=10
    @RequestMapping("/test2")
    public String method2(@RequestParam(value = "page", defaultValue = "1") int page ,
                          @RequestParam(value = "size",required = false,defaultValue = "10") int size) {
        System.out.println(page);
        System.out.println(size);
        return "使用默认值参数+可选参数";
    }
}

六、@PathVariable

作用

用于绑定 url 中的占位符。例如:请求 url 中 /list/{page},这个{page}就是 url 占位符。url 支持占位符是 spring3.0 之后加入的。是 springmvc 支持 rest 风格 URL 的一个重要标志。

属性

属性 说明
String value() 用于指定 url 中占位符名称。
boolean required() 是否必须提供占位符。

栗子

@Controller
public class PathController {
    @RequestMapping("/path/{page}/{size}")
    public String pathTest(@PathVariable(value = "page") int page, @PathVariable String size) {
        System.out.println(page);
        System.out.println(size);
        return "动态路径匹配";
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章