SpringMVC(注解方式)

一.配置文件

<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
         xmlns:mvc="http://www.springframework.org/schema/mvc"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
                  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
                  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
         <context:component-scan base-package="com.tledu.controller"/>
        <!--
        这是该注解的主要功能,添加< mvc:annotation-driven/>注解后,容器中会<自动注册HandlerMapping与HandlerAdapter 两个bean。省去手动注册HandlerMapping和HandlerAdapter的步骤。
        当配置了< mvc:annotation-driven/>后,Spring就知道了我们启用注解驱动。然后Spring通过< context:component-scan/>标签的配置,会自动为我们将扫描到的@Component,@Controller,@Service,@Repository等注解标记的组件注册到工厂中,来处理我们的请求。
        HandlerMapping的实现类的作用:将请求映射到带@RequestMapping注释的控制器方法,将URL路径映射到控制器bean名称。
        HandlerAdapter的实现类的作用:实现类RequestMappingHandlerAdapter,处理请求的适配器,确定调用哪个类的哪个方法,并且构造方法参数,返回值。
        -->
          <mvc:annotation-driven />
         <!--视图解析器 -->
         <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                  <property name="prefix"value="/WEB-INF/jsp/"/>
                  <property name="suffix"value=".jsp"/>
         </bean>
</beans>
  1. 配置包扫描,需要能把controller放到spring容器管理
  2. 添加一个Controller类,并加上Controller注解
  1. 类上加@RequestMapping(""),配置地址和controller的映射关系
  2. 在方法上加@RequestMapping(""),配置地址和方法的映射关系
  1. 执行方法,并返回一个字符串,这个字符串就是view-name

二.常用注解 

1.     @Controller

使用Controller注解之后,在方法上可以通过return的jsp或者html页面的名字,通过视图解析器,就能跳转到指定页面

如果没有Controller注解,这个类中的方法是不会被请求过去的

所对应的层也是controller层,表现层

2.     @RestController

RestController注解相当于Controller和ResponseBody一起使用

这个类中的方法可以被请求过来,但是方法中无法jsp和html页面,视图解析器就不会起到作用,返回的内容就是return后面的内容

3.     @RequestMapping

是Spring Web应用中最常用到的注解之一,这个注解会将http请求映射到MVC和Controller控制器的处理方法上

@GetMapping

@PostMapping

@PutMapping

@DeleteMapping

4.     @RequestBody

@RequestBody 主要用于接收前端通过 请求体 传递给后端的JSON字符串中的数据

GET方式无请求体,所以使用@RequestBody的时候不能使用GET方式,而应该使用POST形式

jsp页面
<script>
var userList = new Array();
userList.push(username:"beijing"),age:30);
$.ajax({
    url:"${pageContext.request.contextPath}/bike",
    type:"post",
    data:JSON.stringify(userList),
    contentType:"application/json;charset=utf-8",
    success:function(result){
        alert(result);
    }
})
</script>
controller
@RequestMapping("/bike")
@ResponseBody
public String bike(@RequestBody List<User> userList){
    for(User user:userList){
        System.out.printn(user.getUserName());
    }
    return "ok";
}

5.     @RequestParam

用于接收前端传递过来的url中的参数(key=value)的形式

主要用于接收前后端key不一致的时候,使用@RequestParm来指定获取

@RequestMapping("/test")
public String test(@RequestParam(value="name",required=false,default="tom")String name)

6.     @PathVaraible

@PathVaraible主要用于获取url请求中的动态参数的

@RequestMapping("/delete/{id}")
public String delete(@PathVaraible(“id”) int id){}

当RequestMapping中需要动态传递过来参数的时候,需要通过@PathVaraible来接收

7.     @ResponseBody

如果方法需要返回JSON或者XML或者自定义内容到页面中去,就需要再方法上加上ResponseBody,这个时候,返回的数据就会不被视图解析器所解析

 @RequestMapping("/login")
  @ResponseBody
  public User login(User user){
    return user;
  }
  User字段:userName pwd;
  那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'

  效果等同于如下代码:
  @RequestMapping("/login")
  public void login(User user, HttpServletResponse response){
              //通过response对象输出指定格式的数据
    response.getWriter.write(JSONObject.fromObject(user).toString());
  }

8.     SessionAttributes注解

用于多次执行控制器方法间的参数,可以通过value指定存入属性的名字

若希望在多个请求之间共用数据,则可以在控制器类上标注一个 @SessionAttributes,配置需要在session中存放的数据范围,Spring MVC将存放在model中对应的数据暂存到

HttpSession 中。

@SessionAttributes只能使用在类定义上。

@SessionAttributes 除了可以通过属性名指定需要放到会 话中的属性外,还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中 例如:

@SessionAttributes(types=User.class)会将model中所有类型为 User的属性添加到会话中。

@SessionAttributes(value={“user1”, “user2”}) 会将model中属性名为user1和user2的属性添加到会话中。

@SessionAttributes(types={User.class, Dept.class}) 会将model中所有类型为 User和Dept的属性添加到会话中。

@SessionAttributes(value={“user1”,“user2”},types={Dept.class})会将model中属性名为user1和user2以及类型为Dept的属性添加到会话中。

value和type之间是并集关系

比如 :

package com.tledu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@RequestMapping(path="/hello")
@SessionAttributes(value= {"username","password","age"},types=
        {String.class,Integer.class})
public class HelloController {
    /**
     * 向session中存入值
     * @return
     */
    @RequestMapping(path="/save")
    public String save(Model model) {
        System.out.println("向session域中保存数据");
        model.addAttribute("username", "root");
        model.addAttribute("password", "123");
        model.addAttribute("age", 20);
        return "success";
    }
    /**
     * 从session中获取值
     * @return
     */
    @RequestMapping(path="/find")
    public String find(ModelMap modelMap) {
        String username = (String) modelMap.get("username");
        String password = (String) modelMap.get("password");
        Integer age = (Integer) modelMap.get("age");
        System.out.println(username + " : "+password +" : "+age);
        return "success";
    }
    /**
     * 清除值
     * @return
     */
    @RequestMapping(path="/delete")
    public String delete(SessionStatus status) {
        status.setComplete();
        return "success";
    }
}
作用
可以多个请求之间共享数据,作用域是session作用域

怎么用
@SessionAttributes注解声明有哪些数据需要放在SessionAttributes中
通过model.addAttribute进行添加
通过model.getAttribute获取
通过SessionStatus status中status.setComplete();进行清除

三.控制器类和参数绑定

RequestMapping详解

1. RequestMapping注解的作用是建立请求URL和处理方法之间的对应关系

2. RequestMapping注解可以作用在方法和类上

    • 作用在类上:第一级的访问目录
    • 作用在方法上:第二级的访问目录
    • 细节:路径可以不编写 / 表示应用的根目录开始
    • 细节:${ pageContext.request.contextPath }也可以省略不写,但是路径上不能写 /

3. RequestMapping的属性

path 指定请求路径的url

value value属性和path属性是一样的

method 指定该方法的请求方式
GetMapping
PostMapping
PutMapping
DeleteMapping
@RequestMapping(value = "/list" , method = RequestMethod.POST)
public BaseDTO list(@PathVariable String communityId) {
    // TODO
}
    • consumes :指定处理请求的 提交内容类型 (Content-Type),例如 application/json, text/html

//方法仅处理request Content-Type为“application/json”类型的请求
@RequestMapping(value = "/list" , method = RequestMethod.POST,consumes="application/json")
public void list(@PathVariable String communityId) {
   // TODO
}

    • produces: 指定 返回的内容类型 ,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
  • @RequestMapping(value = "/list" , method = RequestMethod.POST,produces="application/json")
    public JSONObject list(@PathVariable String communityId) {
       JSONObject object = new JSONObject();
       object.put("communityId",communityId);
       return object;
    }
    • params: 指定request中必须包含某些参数值时,才让该方法处理。
//设定必须包含username 和age两个参数,且age参数不为10 (可以有多个参数)
@RequestMapping(value = "/list" , method = RequestMethod.POST,params = { "username","age!=10" })
public JSONObject list(@PathVariable String communityId) {
   JSONObject object = new JSONObject();
   object.put("communityId",communityId);
   return object;
}
    • headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
//仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;
@RequestMapping(value = "/list" , method = RequestMethod.POST,headers="Referer=http://www.ifeng.com/")
public JSONObject list(@PathVariable String communityId) {
   JSONObject object = new JSONObject();
   object.put("communityId",communityId);
   return object;
}

 参数绑定说明

请求参数的绑定说明

1. 1 绑定机制

1. 表单提交的数据都是k=v格式的username=haha&password=123

2. SpringMVC的参数绑定过程是把表单提交的请求参数,作为控制器中方法的参数进行绑定的

3. 要求:提交表单的name和参数的名称是相同的

2.1 支持的数据类型

1. 基本数据类型和字符串类型

2. 实体类型(JavaBean)

3.集合数据类型(List、map集合等)

2.2基本数据类型和字符串类型

  • 提交表单的name和参数的名称是相同的
  • 区分大小写

6.3.3 参数绑定使用

5 为了方便向视图层传值,提供了 Model 专门向视图层传递数据

请求为 http://localhost:8080/SpringMVC_01_Basic/hello?username=root

        

 @RequestMapping("/hello")
         public String hello(String username,Model model) {
                  // 键值对,页面可以通过username获取对应的值
                  model.addAttribute("username", "Hello : "+username);
                  // 参数是值,页面需要根据值的类型的首字母小写获取
                  model.addAttribute(username);
                  // 如果 类名前两个字母都是大写,就不会把首字母转换为小写了
                  return "hello";
}
<body>
        Hello~ <br>
        ${username } <br>
        ${string }
</body>

6 多个Url映射到同一个方法上

请求为 http://localhost:8080/SpringMVC_01_Basic/hello?username=root

    @RequestMapping({"/hello","/h","/hi"}) public String hello(String username,Model model) {                   model.addAttribute("username", "Hello : "+username);                   return "hello"; }

这时候/hello 和/h 以及 /hi 请求 都会来执行这个方法

知识点补充

import

import resource="classpath:applicationContext.xml" />

可以通过import导入别的配置文件

重定向

返回"redirect:地址"。就可以重定向到指定地址

怎么给前端返回json数据

加入接口不希望跳转界面,希望返回一个json格式的数据,可以在这个接口上加@ResponseBody

如果我们希望一个Controller所有的方法都返回json格式的数据,这个时候可以使用@RestController代替@Controller

1、地址参数

在resful风格的接口中,会直接通过地址进行参数的传递,如,在进行详情查询的时候,我们需要传递参数id,这个时候id这个参数就可以放在地址中进行传递。

  @GetMapping("/detail/{id}/{name}")
    public String userDetailPage(@PathVariable Integer id, @PathVariable("name") String name) {
        System.out.println(id);
        System.out.println(name);
        return "user-detail";
    }

使用步骤:

  • 定义参数
    1. 会在地址上通过{参数名}指定参数
  • 获取参数
    1. 请求方法的参数中加上@PathVariable
  • 传递参数,参数直接写在url里面
    1. /detail/id参数/name参数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值