首页 > 其他分享 >SpringMVC系列之(三)常用注解

SpringMVC系列之(三)常用注解

时间:2024-02-28 09:01:25浏览次数:19  
标签:系列 RequestMapping SpringMVC org springframework Controller import 注解 String

常用注解

1. RequestMapping

在这里插入图片描述
RequestMapping可以放在类上和方法上,放在类上表示一级目录,或表示某一个具体的模块

属性

  1. path和value属性的作用相同
  2. method决定方法的请求方式
  3. params:请求必须包含的参数
  4. headers:请求必须包含的请求头

以上的属性出现多个,需要同时满足

2. RequestParam

2.1 应用场景

数据绑定时,前端传到后端的参数名与控制器中的方法参数名不同,通过RequestParam可建立映射关系,建立前端请求参数与Controller接收参数变量命名之间的映射关系

2.2 常用属性

属性 取值 默认值 功能
name 字符串 "" 前端传过来的参数名
required 布尔值 true 如:@RequestParam("name"),表示请求中必须携带name参数

2.3 实例

JSP

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <a href="hh/hello?name=lisi&age=12">入门程序</a>
</body>
</html>

Controller

package cn.itcast.controller;

import cn.itcast.domain.User;
import cn.itcast.utils.StringToDateConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
public class HelloController {

    @RequestMapping(path = "/hello")
    public String sayHello(@RequestParam("name") String username, @RequestParam("age") String password){
        System.out.println(username + "\t" + password);
        return "success";
    }
}

3. RequestBody

3.1 应用场景

获取整个请求体,与请求参数绑定不同,获取的是key=value&key=value这种形式
注:get请求方式不适用,get方式没有请求体

3.2 常用属性

属性 取值 默认值 功能
required 布尔值 true 如:@RequestBody(required = true),表示请求中必须存在请求体

3.3 实例

JSP

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <form action="hh/hello" method="post">
        姓名:<input type="text" name="name">
        年龄:<input type="text" name="age">
        <input type="submit" value="提交">
    </form>
</body>
</html>

Controller

package cn.itcast.controller;

import cn.itcast.domain.User;
import cn.itcast.utils.StringToDateConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
public class HelloController {

    @RequestMapping(path = "/hello")
    public String sayHello(@RequestBody(required = false) String body){
        System.out.println(body);
        return "success";
    }

}

4. PathVariable

4.1 关于Restful编程风格

Controller中各个方法的请求地址都相同,通过请求方式区分执行哪个方法,当几个方法的地址和请求方式都相同时,通过类似testRequest/{id}的方式进行区分
利于缓存
在这里插入图片描述

4.2 应用场景

绑定url中的占位符

4.3 实例

JSP

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <form action="hh/hello" method="post">
        姓名:<input type="text" name="name">
        年龄:<input type="text" name="age">
        <input type="submit" value="提交">
    </form>
</body>
</html>

Controller

package cn.itcast.controller;

import cn.itcast.domain.User;
import cn.itcast.utils.StringToDateConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
public class HelloController {

    @RequestMapping(path = "/hello/{id}")
    public String sayHello(@PathVariable(name = "id") String id){
        System.out.println(id);
        return "success";
    }

}

5. RequestHeader

5.1 应用场景

获取请求头的内容
在这里插入图片描述

5.2 实现

Jsp

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <a href="hh/hello">入门程序</a>
</body>
</html>

Controller

package cn.itcast.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
public class HelloController {

    @RequestMapping(path = "/hello")
    public String sayHello(@RequestHeader("Upgrade-Insecure-Requests") String header){
        System.out.println(header);
        return "success";
    }
}

6. CookieValue

6.1 应用场景

直接获取指定Cookie的值
在这里插入图片描述

6.2 实现

JSP

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <a href="hh/cookie">Cookie</a>
</body>
</html>

Controller

package cn.itcast.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
public class HelloController {
    @RequestMapping(path = "/cookie")
    public String testCookie(@CookieValue("JSESSIONID") String cookie){
        System.out.println(cookie);
        return "success";
    }
}

6.3 关于JSESSIONID

在这里插入图片描述

7. ModelAttribute

7.1 应用场景

当表单提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。
在控制器所有方法执行之前执行

7.2 实例

7.2.1 修饰有返回值的方法

实体类有四个属性,其中,name、gender、money从前端接收,date是根据name从数据库中取到的,不是来源于客户端。
在这里插入图片描述
JSP

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <form action="hh/hello" method="post">
        姓名:<input type="text" name="name">
        性别:<input type="text" name="gender">
        金额:<input type="text" name="money">
        <input type="submit" value="提交">
    </form>
</body>
</html>

在这里插入图片描述

7.2.2 修饰无返回值的方法
package cn.itcast.controller;

import cn.itcast.domain.User;
import cn.itcast.utils.StringToDateConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
public class HelloController {

    @RequestMapping(path = "/hello")
    public String sayHello(@ModelAttribute("aaa") User user){
        System.out.println(user);
        return "success";
    }

    @ModelAttribute
    public void addDate(String name, Map<String, User> map){
        //模拟根据name查询数据库的过程,为了从数据库中取到date的值
        User user = new User();
        user.setDate(new Date());
        user.setGender("南");
        user.setMoney(100);
        user.setName(name);
        map.put("aaa", user);

    }
}

8. SessionAttributes

8.1 应用场景

与Session域对象有关,实现控制器方法间的参数共享

8.2 实例

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:27
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h3>入门程序</h3>
    <a href="hh/saveMsg">存入msg</a>
    <a href="hh/checkMsg">查看msg</a>
    <a href="hh/delMsg">删除msg</a>
</body>
</html>

Controller

package cn.itcast.controller;

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

/**
 * @author 商务小本本
 */
@Controller
@RequestMapping("/hh")
//把msg=妹妹存入session域对象中
@SessionAttributes("msg")
public class HelloController {

    @RequestMapping(path = "/saveMsg")
    public String saveMsg(Model model){
        //Model中存入的数据底层会被存到request域对象中
        model.addAttribute("msg", "妹妹");
        return "success";
    }

    @RequestMapping(path = "/checkMsg")
    public String checkMsg(ModelMap modelMap){
        String msg = (String) modelMap.get("msg");
        System.out.println("获取到的Msg为:" + msg);
        return "success";
    }

    @RequestMapping(path = "/delMsg")
    public String delMsg(SessionStatus status){
        status.setComplete();
        return "success";
    }
}

success.jsp

<%--
  Created by IntelliJ IDEA.
  User: 商务小本本
  Date: 2022/3/3
  Time: 23:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h3>入门成功!</h3>
    ${sessionScope}
</body>
</html>

9. @ResponseBody

这个注解标注在类上,表明这个类的所有方法返回的数据直接写给浏览器,如果返回的是对象就转为json数据。
在这里插入图片描述

10. @RestController

@RestController等同于@ResponseBody和@Controller的组合
在这里插入图片描述

标签:系列,RequestMapping,SpringMVC,org,springframework,Controller,import,注解,String
From: https://www.cnblogs.com/wzzzj/p/18038902

相关文章

  • SpringMVC系列之(一)入门程序
    Web层,表现层入门程序1.需求描述页面上设置一个链接,点击链接后跳转到成功页面。2.搭建环境从骨架创建项目解决创建项目过慢的问题项目创建后,完善目录结构,创建相应的目录并设置目录类型源代码目录(java)和资源目录(resources)注:我这里已经设置过了,所以就不......
  • Spring系列之(十)Spring的事务控制
    Spring的事务控制1.Spring中基于XML的声明式事务控制配置步骤配置事务管理器<beanclass="org.springframework.jdbc.datasource.DataSourceTransactionManager"id="transactionManager"><propertyname="dataSource"ref="dataSource">......
  • Spring系列之(九)Spring中的JdbcTemplate
    Spring中的JdbcTemplate持久层总图1.JdbcTemplate相关的jar包spring-jdbc-5.2.11.RELEASE.jar2.JdbcTemplate的学习路径JdbcTemplate的作用用于和数据库交互,实现对表的CRUD操作如何创建JdbcTemplate对象对象中的常用方法方法功能voidsetDataSource(DataS......
  • Spring系列之(八)Spring中的AOP
    Spring中的AOP通过配置(XML/注解)实现AOP1.AOP相关术语1.1连接点方法,Service接口中的所有方法1.2切入点方法,Service接口中被增强过的方法Tip:所有的切入点都是连接点1.3通知方法,通常,具有增强功能的方法会放到一个类中,该类中所有用于增强的方法就被称为通知分类:前置通......
  • Spring系列之(七)动态代理
    动态代理1.特点字节码随用随创建,随用随加载2.作用不修改类的源码基础上对类的方法进行增强3.分类基于接口的动态代理基于子类的动态代理4.基于接口的动态代理4.1涉及的类Proxy4.2提供者JDK官方4.3如何创建代理对象Proxy的newProxyInstance方法4.4创建代......
  • Spring系列之(六)Spring整合Junit
    Spring整合Junit上面部分的内容是把8.3.7节的第一个问题给解决了,我们来看第二个问题(测试代码开发和测试部分耦合度高,图中标红部分一般测试人员无法完成)pom中导入Spring整合Junit的坐标使用Junit提供的@RunWith注解把Junit原有的main方法替换成Spring提供的main方法告知Sprin......
  • Spring系列之(五)Spring基于注解的IOC
    Spring基于注解的IOC1.构建注解环境在beans.xml中加入context名称空间和约束<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&......
  • Spring系列之(四)Spring的依赖注入
    Spring的依赖注入在当前类需要用到其他类的对象,其他类的对象也是由Spring创建并将引用传递给当前类的对象的,我们只需要在配置文件中说明,说白了就是为当前类填充(也叫注入)其他类的对象1.能够注入的数据能够注入的数据是指支持注入的这部分数据是可以被Spring填充(注入)到当前类的......
  • Spring系列之(三)Spring对Bean的管理细节
    Spring对Bean的管理细节1.创建Bean的三种方式使用默认构造函数创建bean标签仅配置id和class,即标识和全限定类名,同时保证要创建的类是有无参构造函数的如果没有无参构造函数,将会报错使用某个类中的方法创建对象,该方法的返回值是某个类的对象以新建的Factory类为例,需......
  • Spring系列之(二)Spring基于XML的IOC实例
    Spring基于XML的IOC实例将改进后的工厂模式通过Spring来实现,解析配置文件、创建仓库,将对象存入仓库的过程都由Spring来做,我们只需要配置好配置文件,获取仓库中的对象即可1.在pom中引入Spring环境<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.o......