SpringMVC基本注解的使用和理解

9 篇文章 0 订阅

SpringMVC基本注解的使用和理解

RequestParam注解

使用在方法入参位置,用于指定请求参数名称,将该请求参数绑定到注解参数位置。
属性:name:指定要绑定的请求参数名称; name属性和value属性互为别名。
required 和:指定请求参数是否必传; true:表明必须提交参数,true默认值, 没有400
defaultValue:指定当没有传入请求参数时的默认取值;
注意: 如果required 和 defaultValue 都存在, required属性失效。

在做案例测试时请务必进行下述配置:

在这里插入图片描述

**注意:**如果是想要根据文章想要基础学习的可以沿用上次发布的文章的maven和spring配置(https://blog.csdn.net/m0_56245143/article/details/130095359?spm=1001.2014.3001.5501)

示例:

创建一个实体类:Student.java

示例代码:

 index.jsp

<form action="testController/t01" method="post">
<%--        当都能通过name="un"传值过去,那么后端能获取到页面传回去的数据,否则是默认值--%>
        <%--        账号<input type="text" name="un"><br>--%>
        <input type="submit">
    </form>

TestController.java

//RequestParam注解使用
    @RequestMapping(value = "t01" , method = {RequestMethod.POST})
    public String t01(@RequestParam(name = "un",required = true,defaultValue = "李四") String username){
        System.out.println(username);
        return "main";
    }

运行结果:当页面没有传值给到name="un"注入给username,那默认显示的时defaultValue设置的值

在这里插入图片描述

RequestHeader注解

这个可以做一个了解

注解在方法入参位置,用于获取请求头信息。
属性:
value:指定头的名称;
name:和value属性会别名
require:是否是必须, true,必须传递, 没传递。400
defaultValue: 如果前台没传递头信息, 指定默认值。 require冲突。

示例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="test/t02" method="post">
        <%--账号:<input type="text" name="un"><br>--%>
        <input type="submit">
    </form>
</body>
</html>
    
@RequestMapping(value = "t02",method = {RequestMethod.POST})
public String t02(@RequestHeader(name = "Upgrade-Insecure-Requests") String data) {
    System.out.println(data);
    return "main";
}

RequestBody注解

用于方法入参位置,获取请求体内容。直接使用得到是 key=value&key=value…结构的数据。get 请求方式不适用。通常用于将json格式字符串绑定到bean对象中;

示例代码:

index.jsp

 		<form action="testController/t03" method="post">
            账号:<input type="text" name="username"><br>
            密码:<input type="password" name="password"><br>
            <input type="submit">
        </form>
        
        TestController.java
        
     //RequestBody注解使用
    @RequestMapping(value = "t03" , method = {RequestMethod.POST})
    public String t03(@RequestBody String data){
        System.out.println(data);
        return "main";
    }

运行结果:通过注解RequestBody可以拿到页面提交的所有数据并且以字符串的方式输出(直接获取请求体内容)

在这里插入图片描述

将json格式请求参数绑定到指定对象bean中:

示例代码:

index.jsp
        <script>
        $(function (){
            $("#btn").click(function (){
                $.ajax({
                    url:"test/04",
                    type:"post",
                  data:'{"sid":1,"name":"mary","gender":"女","age":18,"email":"dsfdmdairn@qq.com"}',
                    contentType:"application/json",
                    success:function (resp){
                        alert(resp);
                    }
                });
            });
        });
    </script>
    
    <input type="button" value="测试" id="bth">

@RequestMapping(value = "t04",method = {RequestMethod.POST})
public String t04(@RequestBody Student student) {
    System.out.println(student);
    return "main";
}

注意: 使用json 需要引入json的解析器~ 
	<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
    </dependency>
    
静态文件无法加载?需配置如下内容:
<mvc:default-servlet-handler></mvc:default-servlet-handler>

CookieValue注解

用于方法入参位置,把指定 cookie 名称的值传入控制器方法参数。 

回顾: Cookie 会话。 
客户端技术: cookie ,浏览器当中, 不安全。 
服务端技术: session,服务器端, 安全。 
原生cookie的获得: 
       Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if(name.equals("JSESSIONID")){
                //获得cookie的值: 
                String value = cookie.getValue();
            }
        }

示例代码:

    //CookieValue注解使用
    @RequestMapping(value = "t05",method = {RequestMethod.GET})
    public String t05(@CookieValue("JSESSIONID") String data){
        System.out.println(data);
        return "main";
    }

    @RequestMapping(value = "t06",method = {RequestMethod.GET})
    public String t06(@CookieValue("JSESSIONID") Cookie cookie){
        System.out.println(cookie.getName()+":"+cookie.getValue());
        return "main";
    }

ModelAttribute注解

该注解是SpringMVC4.3版本以后新加入的。它可以用于修饰方法和参数。
出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。
出现在参数上,获取指定的数据给参数赋值。

示例代码:

<a href="test/t08">测试</a>

    //ModelAttribute注解使用
    @RequestMapping("param")
    public String t07(){
        System.out.println("这是ModelAttribute注解的方法");
        return "hello word";
    }

    @RequestMapping(value = "t08",method = {RequestMethod.GET})
    public String t08(@ModelAttribute("param") String data){
        System.out.println(data);
        return "main";
    }

SessionAttributes注解

注解在类上,作用将请求域中的参数存放到session域中,用于参数共享。

示例代码:

<%--SessionAttributes注解的使用--%>
    <a href="session/s01">测试1</a>
    <a href="testController/t09">测试2</a>
    
    //SessionAttributes注解使用
    @RequestMapping(value = "t09" , method = {RequestMethod.GET})
    public String t09(){
        return "main";
    }
    
    package com.etime.controller;

import com.etime.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/session")
@SessionAttributes("student")
public class SessionController {

    @RequestMapping("s01")
    public ModelAndView s01(ModelMap modelMap){
        ModelAndView modelAndView = new ModelAndView();
        modelMap.addAttribute("student",new Student(1,"cc","男",22,"ajhif@qq.com"));
        modelAndView.setViewName("main");
        return modelAndView;
    }

}

Rest风格

restfuul?

​ 一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

restful的优点:

它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。

restful的特性:
体现形式1: 
资源:http://localhost:8080/user/ URL:统一资源定位符。

传统请求url:
新增:http://localhost:8888/user/add      POST
修改:http://localhost:8888/user/update   POST
删除:http://localhost:8888/user/deleteById?id=1   GET
查询:http://localhost:8888/user/findById?id=1     GET
查询:http://localhost:8888/user/findAll     GET

REST风格请求: 通过不同的请求动词(get post put delete )区分执行不同的操作; 
新增:http://localhost:8888/user        POST
修改:http://localhost:8888/user        PUT
删除:http://localhost:8888/user/1      DELETE 
查询:http://localhost:8888/user/1      GET
查询:http://localhost:8888/user        GET

体现形式2: 
http://localhost:8888/user/id  
id作为了url地址的一部分。

PathVariable注解

	该注解用于绑定 url 中的占位符。例如:请求 url 中/annotation/test9/{id},这个{id}就是 url 占位符。url 支持占位符是 spring3.0 之后加入的。是springmvc 支持 rest 风格 URL 的一个重要标志。
属性:
	value:用于指定 url 中占位符名称。
	required:是否必须提供占位符。
	
	前端: 
	localhost:8080/user/findUser/1001 
	后端: 
	@RequestMapping("findUser/{uid}") 
	
    参数: 
    PathVariable("uid") Integer id

示例代码:

<%--    PathVariable注解的使用--%>
<%--    添加--%>
    <form action="studentController/add" method="post">
        编号:<input type="text" name="sid"><br>
        姓名:<input type="text" name="name"><br>
        性别:<input type="text" name="gender"><br>
        年龄:<input type="text" name="age"><br>
        邮件:<input type="text" name="email"><br>
        <input type="submit">
    </form>

<%--    修改--%>
    <form action="studentController/update" method="post">
        <input type="hidden" name="_method" value="PUT">
        编号:<input type="text" name="sid"><br>
        姓名:<input type="text" name="name"><br>
        性别:<input type="text" name="gender"><br>
        年龄:<input type="text" name="age"><br>
        邮件:<input type="text" name="email"><br>
        <input type="submit">
    </form>

<%--    删除--%>
    <form action="studentController/delete" method="post">
        <input type="hidden" name="_method" value="DELETE">
        编号:<input type="text" name="id"><br>
        <input type="submit" value="删除">
    </form>

<%--    查询--%>
    <a href="/studentController/1">获取学生信息</a>

控制层:

package com.etime.controller;

import com.etime.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/studentController")
public class StudentController {

    //@RequestMapping(value = "add",method = {RequestMethod.POST})
    @PostMapping("add")
    public String add(Student student){
        System.out.println(student);
        return "main";
    }

    //@RequestMapping(value = "getStudent/{sid}",method = {RequestMethod.GET})
    @PostMapping("getStudent/{sid}")
    public String getStudent(@PathVariable("sid") int id){
        System.out.println(id);
        return "main";
    }

    //@RequestMapping(value = "update",method = {RequestMethod.PUT})
    @PutMapping("update")
    public String update(Student student){
        System.out.println(student);
        return "main";
    }

    //@RequestMapping(value = "delete",method = {RequestMethod.DELETE})
    @DeleteMapping("delete")
    public String delete(int id){
        System.out.println(id);
        return "main";
    }
}

请求方式转换过滤器

(1)form:实际上 post 
    hidden隐藏域: _method PUT | DELETE |  
(2)后端处理器:  
    @GetMapping 处理get请求。   查询操作。 
    @PostMapping 处理post请求。 新增操作
    @PutMapping  处理put请求。  修改操作。 
    @DeleteMapping 处理delete 请求, 删除操作。 
(3)请求方式转换过滤器: 
	<!--过滤请求方式:自动识别请求体中是否有_method数据,如果有,将其值设为当前请求方式,如果没有,直接放行-->
    <filter>
        <filter-name>hiddenMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

jsp只支持get,post,head类型请求,其他类型请求会有405错,我们不用管,以后不会用JSP

响应数据及结果视图

返回值类型为字符串

用于指定返回的逻辑视图名称;
控制器代码:
    @GetMapping("resp01")
    public String resp01() {
        return "main";
    }

void类型

通常使用原始servlet处理请求时,返回该类型;
控制器代码:
    @GetMapping("resp02")
    public void resp02(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.sendRedirect("../main.jsp");
    }

ModelAndView

   //ModelAndView
    @GetMapping("resp03")
    public ModelAndView resp03(ModelMap modelMap){
        ModelAndView modelAndView = new ModelAndView();
        modelMap.addAttribute("username","mch");
        modelAndView.setViewName("main");
        return modelAndView;
    }

返回值自定义类型

@Response注解:

引入依赖包:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>

ResponseBody注解:能够将bean List Map 转换成Json格式,异步响应到客户端浏览器

示例代码:

    //ResponseBody注解:能够将bean List Map 转换成Json格式,异步响应客户端浏览器
    @GetMapping("resp02")
    public void resp02(HttpServletRequest request,HttpServletResponse response) throws IOException {
        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student(1,"mary","女",20,"jdfawrj@qq.com");
        Student student2 = new Student(2,"mark","男",23,"jdfawrj@qq.com");
        Student student3 = new Student(3,"jack","男",23,"jdfawrj@qq.com");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(list);
        PrintWriter out = response.getWriter();
        out.println(json);
        out.close();
    }

    //SpringMVC的方式:
    //对象
    @GetMapping("resp04")
    @ResponseBody
    public Student resp04(){
        Student student = new Student(1,"may","女",20,"ajdgiaie@qq.com");
        return student;
    }

    //单列集合:
    @GetMapping("resp05")
    @ResponseBody
    public List<Student> resp05(){
        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student(1,"mary","女",20,"jdfawrj@qq.com");
        Student student2 = new Student(2,"mark","男",23,"jdfawrj@qq.com");
        Student student3 = new Student(3,"jack","男",23,"jdfawrj@qq.com");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        return list;
    }

    //双列集合:
    @GetMapping("resp06")
    @ResponseBody
    public Map<String,Object> resp06(){
        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student(1,"mary","女",20,"jdfawrj@qq.com");
        Student student2 = new Student(2,"mark","男",23,"jdfawrj@qq.com");
        Student student3 = new Student(3,"jack","男",23,"jdfawrj@qq.com");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("students",list);
        return map;
    }

转发和重定向

forward请求转发

示例代码:

    @GetMapping("resp02")
    public String resp02(){
        System.out.println("进来了");
        return "forward:../main.jsp";
    }
redirect重定向

示例代码:

 @GetMapping("resp02")
    public String resp02(){
        System.out.println("进来了");
        return "redirect:../main.jsp";
    }

nt2);
list.add(student3);
Map<String,Object> map = new HashMap<String, Object>();
map.put(“students”,list);
return map;
}


### 转发和重定向

#### forward请求转发

示例代码:

```java
    @GetMapping("resp02")
    public String resp02(){
        System.out.println("进来了");
        return "forward:../main.jsp";
    }
redirect重定向

示例代码:

 @GetMapping("resp02")
    public String resp02(){
        System.out.println("进来了");
        return "redirect:../main.jsp";
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@湖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值