SpringMVC常用注解

一、RequestMapping注解

RequestMapping注解的作用是建立请求URL和处理方法之间的对应关系
RequestMapping注解可以作用在方法和类上

  1. 作用在类上:第一级的访问目录
  2. 作用在方法上:第二级的访问目录
  3. 细节:路径可以不编写 / 表示应用的根目录开始

1.RequestMapping的属性

  1. path 指定请求路径的url
  2. value value属性和path属性是一样的
  3. mthod 指定该方法的请求方式
  4. params 请求地址中必须包含指定的请求参数或请求参数们
@Controller
@RequestMapping(path = "/role") // 一级请求路径
public class RoleController {
    /**
     * /role/save.do
     * method="当前方法允许请求方式能访问"
     * params="请求路径上传参数"
     * @return
     */
    @RequestMapping(path = "/save.do",method = {RequestMethod.GET})
    public String save(){
        System.out.println("保存角色...");
        return "suc";
    }
    @RequestMapping(value = "/delete.do")
    public String delete(){
        System.out.println("删除角色...");
        return "suc";
    }
}

2.RequestMapping的请求参数绑定

(1). 绑定机制
   1. 表单提交的数据都是k=v格式的 username=haha&password=123
  2. SpringMVC的参数绑定过程是把表单提交的请求参数,作为控制器中方法的参数进行绑定的
   3. 要求:提交表单的name和参数的名称是相同的
(2). 支持的数据类型
   1. 基本数据类型和字符串类型
   2. 实体类型(JavaBean)
   3. 集合数据类型(List、map集合等)
基本数据类型和字符串类型
  1. 提交表单的name和参数的名称是相同的
   2. 区分大小写
实体类型(JavaBean)
   1. 提交表单的name和JavaBean中的属性名称需要一致
   2. 如果一个JavaBean类中包含其他的引用类型,那么表单的name属性需要编写成:对象.属性 例如:address.name
给集合属性数据封装
  1. JSP页面编写方式:list[0].属性

jsp代码

<html>
<head>
    <meta charset="utf-8">
    <title>入门程序</title>
</head>
<body>
<h3>入门</h3><a href="/SpringMVC/hello.do" >入门程序</a>
    <h1>请求参数绑定入门程序</h1>
    <form action="/SpringMVC/user/save.do" method="get">
        <input type="text" name="username"/><br/>
        <input type="text" name="age"/><br/>
        <input type="submit"/>
    </form>
    <h1>请求参数绑定入门程序(封装到实体类)</h1>
    <form action="/user/save1.do" method="post">
        <input type="text" name="username"/><br/>
        <input type="text" name="age"/><br/>
        <input type="submit"/>
    </form>
    <h1>请求参数绑定入门程序(封装到实体类)</h1>
    <form action="/user/save2.do" method="post">
        <input type="text" name="username"/><br/>
        <input type="text" name="age"/><br/>
        <input type="text" name="account.money"/><br/>
        <input type="submit"/>
    </form>
    <h1>请求参数绑定入门程序(存在list集合)</h1>
    <form action="/user/save3.do" method="post">
        <input type="text" name="username"/><br/>
        <input type="text" name="age"/><br/>
        <input type="text" name="account.money"/><br/>
        <input type="text" name="accounts[0].money"/><br/>
        <input type="text" name="accounts[1].money"/><br/>
        <input type="submit"/>
    </form>
</body>
</html>

JavaBean代码

public class Account {
    private Double money;

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "money=" + money +
                '}';
    }
}
public class User {
    private String username;
    private Integer age;
    private Account account;
    private List<Account> accounts;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", account=" + account +
                ", accounts=" + accounts +
                '}';
    }
}

controller代码

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/save.do")
    public String save(String username,Integer age){
        System.out.println(username);
        System.out.println(age);
        return "suc";
    }

    @RequestMapping("/save1.do")
    public String save1(User user){
        System.out.println(user.toString());
        return "suc";
    }

    @RequestMapping("/save2.do")
    public String save2(User user){
        System.out.println(user);
        return "suc";
    }

    @RequestMapping("/save3.do")
    public String save3(User user){
        System.out.println(user);
        return "suc";
    }

}

二、配置过滤器

post请求中参数中文乱码的解决
首先需要将原本的xml配置文档做出如下更改

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

在web.xml中配置Spring提供的过滤器类

 <!--配置过滤器,解决中文乱码的问题-->
<filter>
  <filter-name>characterEncodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <!--指定字符集-->
  <init-param>
    <param-name>encoding</param-name>
    <param-value>utf-8</param-value>
  </init-param>
</filter>
 <filter-mapping>
   <filter-name>characterEncodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

在控制器中使用原生的ServletAPI对象
只需要在控制器的方法参数定义HttpServletRequest和HttpServletResponse对象

@RequestMapping(value = "/save6.do",method = {RequestMethod.POST})
public String save6(HttpServletRequest request, HttpServletResponse response){
    // 获取到HttpSession对象
    System.out.println(request.getParameter("username"));
    HttpSession session = request.getSession();
    System.out.println(session);
    System.out.println(response);
    return "suc";
}

三、常用的注解

1.RequestParam注解

  1. 作用:把请求中的指定名称的参数传递给控制器中的形参赋值
  2. 属性
    1. value:请求参数中的名称
    2. required:请求参数中是否必须提供此参数,默认值是true,必须提供
  3. 代码如下
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/dept")
public class DeptController {
    @RequestMapping("/save")
    public String save(@RequestParam(value = "username",required = false) String name){
        System.out.println(name);
        return "suc";
    }
}

2. RequestBody注解

  1. 作用:用于获取请求体的内容(注意:get方法不可以)
  2. 属性
    1. required:是否必须有请求体,默认值是true
  3. 代码如下
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/dept")
public class DeptController {
    @RequestMapping("/save")
    public String save(@RequestParam(value = "username",required = false) String name){
        System.out.println(name);
        return "suc";
    }

    @RequestMapping("/save2")
    public String save2(@RequestBody String body){
        System.out.println(body);
        return "suc";
    }
}

四、RestFul风格

1.概念

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
在这里插入图片描述

2.功能

资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
分别对应 添加、 删除、修改、查询。
传统方式操作资源:通过不同的参数来实现不同的效果!方法单一,post 和 get
http://127.0.0.1/item/queryItem.action?id=1 查询,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST
使用RestFul操作资源:可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能可以不同!
http://127.0.0.1/item/1 查询,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE
相比于传统方式使用链接来访问请求,Resful可以通过使用通过不同的请求方式来达到不同的效果

3.基本使用

①:传统的方式

@Controller()
@RequestMapping("/rest")
public class RestFulController {

    @RequestMapping("/test.do")
    public String test(int a, int b, Model model){
        int rust = a + b;
        model.addAttribute("msg","结果="+rust);
        // 配置了视图解析器后,写法
        return "suc";
    }
}

访问的url

http://localhost:8080/SpringMVC/rest/test.do?a=1&b=1

返回结果
在这里插入图片描述
②:RestFul风格
首先需要改变DispatcherServlet的拦截
在这里插入图片描述
controller

//映射访问路径
@RequestMapping("/commit.do/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable String p2, Model model){
    String result = p1+p2;
    //Spring MVC会自动实例化一个Model对象用于向视图中传值
    model.addAttribute("msg", "结果:"+result);
    //返回视图位置
    return "suc";
}

url

http://localhost:8080/SpringMVC/rest/commit.do/1/1

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值