栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot前后端交互

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot前后端交互

set集合是怎么做到内部不重复的

https://blog.csdn.net/bsegebr/article/details/125243056

Spring Boot之前后端交互

在Springboot中,使用控制器来处理接受的请求,前后端的交互风格也变了,之前使用?来传递参数,并用&来链接。现在也出现了一种Restful风格

常用注解

1.@Controller
标记在类上,用于声明Spring类的实例时一个控制器

2.@RequestMapping

可以标注在类上或者方法上,将url映射到控制器类或者方法上,表示类中所有的响应请求的方法都以改地址做位父路径
有6个属性
1)value或path:指定请求的地址
2)method:指定请求的类型
3)consumes:消费信息,指定处理请求的提交内容类型(Content-Type),例如application/json,text/html。
4)params:指定request中必须包含某些参数值才让该方法处理请求
5)headers:指定request中必须包含某些指定的header值才让该方法处理请求
6)produces:生产消息,指定返回的类型

3.@ResponseBody
标注在类上或者方法上,标注在方法上,表示该方法返回的不再是视图,而是返回数据

4.RequestParam
标注在方法的参数上,用于获取url上传递的参数

5.RequestBody

6.RestController
标注在类上,相当于@ResponseBody加上@Controller

7.@PathVariable
将请求url中的模板变量映射到方法参数上,即获取url中的变量作为参数.
例如下面代码,访问http://localhost:8080/blog/2,则是获取url上的id作为参数值,

@GetMapping(“/blog/{id}”)
public Object blogByKey(@PathVariable(“id”) Integer id){
return blogService.blogOfId(id);
}

@GetMapping 处理get请求
@PostMapping 处理post请求
@PutMapping 更改
@DeleteMapping 删除

传统操作资源的方式

传统前后端交互方式
通过不同的参数来实现不同的效果,方法单一,post和get,查询用get ,增删改用post

传统方法的实现步骤如下

1.新建spring boot项目
2.编写实体类Blog,以及对于增删改查的接口BlogMapper及实现。
3.编写Service接口及实现
4.编写Controller

@RestController
public class BlogController {
	
    private BlogService blogService;

    @Autowired
    public BlogController(BlogService blogService){
        this.blogService = blogService;
    }
	//http://localhost/blog/likeTitle/detail?title=xxx
    @GetMapping("/blog/likeTitle/detail")
    public Object blogLikeTitle(HttpServletRequest req){
        String title = req.getParameter("title").trim();
        return  blogService.blogLikeTitle('%'+title+'%');
    }
	//http://localhost/blog/likeAuthor/detail?author=xxx
    @GetMapping("/blog/likeAuthor/detail")
    public Object blogLikeAuthor(@RequestParam("author") String author){
        return blogService.blogLikeAuthor('%'+author+'%');
    }
	
    @PostMapping("/blog/add1")
    public Object addBlog(HttpServletRequest req){
        String title= req.getParameter("title").trim();
        String author =req.getParameter("author").trim();
        String createTime =req.getParameter("createTime").trim();
        String views =req.getParameter("views").trim();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date createDate = new Date();
        try{
            createDate = dateFormat.parse(createTime);
        }catch (Exception e){
            e.printStackTrace();
        }

        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setAuthor(author);
        blog.setCreateTime(createDate);
        blog.setViews(Integer.parseInt(views));

        boolean res = blogService.addBlogSelective(blog);
        if (res){
            return HttpUtil.ok();
        }else
            return HttpUtil.error();
    }

    @PostMapping("/blog/add2")
    public Object addBlog2(@RequestBody Blog blog){
        boolean res = blogService.addBlogSelective(blog);
        if(res){
            return HttpUtil.ok();
        }else{
            return HttpUtil.error();
        }
    }

   
    @PutMapping("/blog/update1")
    public Object updateBlog1(HttpServletRequest req){

        String title= req.getParameter("title").trim();
        String author =req.getParameter("author").trim();
        String createTime =req.getParameter("createTime").trim();
        String views =req.getParameter("views").trim();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        Date createDate = new Date();
        try{
            createDate = dateFormat.parse(createTime);
        }catch (Exception e){
            e.printStackTrace();
        }

        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setAuthor(author);
        blog.setCreateTime(createDate);
        blog.setViews(Integer.parseInt(views));

        boolean res = blogService.updateBlogSelective(blog);
        if (res){
            return HttpUtil.ok();
        }else
            return HttpUtil.error();
    }

    @PutMapping("/blog/update2")
    public Object updateBlog2(@RequestBody Blog blog){
        boolean res = blogService.updateBlogSelective(blog);
        if(res){
            return HttpUtil.ok();
        }else{
            return HttpUtil.error();
        }
    }
}

获取传统路径中的参数

1.直接获取路径中的参数(url上的参数必须与方法上的参数名一致)
访问http://localhost/blog/likeAuthor/detail?author=子是不睡。

@GetMapping("blog/likeAuthor/detial")
	public Object blogLikeAuthor(String author){
		return blogService.blogLikeAuthor('%'+author+'%');
}

2.HttpServletRequest 对象接收参数
使用HttpServletRequest中的getParameter(“参数名”)方法,返回对应的参数的值。但是返回值时字符串类型
访问//http://localhost/blog/likeTitle/detail?title=xxx

3.用@RequestParam绑定参数
用法如下

@RequestParam(value=“author”,required=false)

当请求参数不存在时会发生异常,可以设置required=false来解决;
http://localhost/blog/likeAuthor/detail?author=子是不睡
url中的参数名对应的时@RequestParam注解中的值,方法的参数名就可以任意了

 @GetMapping("/blog/author/detail")
    public Object blogByAuthor(@RequestParam("author") String author){
        return blogService.blogOfAuthor(author);
    }

也可以处理其它请求,比如POST请求

@PostMapping("/blog/add1")
    public Object addBlog(HttpServletRequest req){
        String title= req.getParameter("title").trim();
        String author =req.getParameter("author").trim();
        String createTime =req.getParameter("createTime").trim();
        String views =req.getParameter("views").trim();

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date createDate = new Date();
        try{
            createDate = dateFormat.parse(createTime);
        }catch (Exception e){
            e.printStackTrace();
        }

        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setAuthor(author);
        blog.setCreateTime(createDate);
        blog.setViews(Integer.parseInt(views));

        boolean res = blogService.addBlogSelective(blog);
        if (res){
            return HttpUtil.ok();
        }else
            return HttpUtil.error();
    }

4.@RequestBody接收Json数据
前端需要传递的是JSON数据

@PutMapping("/blog/update2")
    public Object updateBlog2(@RequestBody Blog blog){
        boolean res = blogService.updateBlogSelective(blog);
        if(res){
            return HttpUtil.ok();
        }else{
            return HttpUtil.error();
        }
    }

5、通过Bean接收HTTP提交的对象

 @PostMapping("/blog/add2")
    public Object addBlog2(Blog blog){
        boolean res = blogService.addBlogSelective(blog);
        if(res){
            return HttpUtil.ok();
        }else{
            return HttpUtil.error();
        }
    }

6.通过注解@@ModelAttribute获取参数
用于从Model、From或URL请求参数获取值

补充
@RequestBody:主要用于接收前端传递给后端的json字符串中的数据(请求题中的数据)
一般用于POST请求中,可以接受简单的对象,复杂的对象和字符串等

@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而@RequestParam()可以有多个。

@RequestParam() 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。

@RestParam可以接受简单类型的属性,也可以接受对象类型

Restful模式

相较于传统模式
1.通过@PathVaribale注解直接获取URL中的值
”/blog/{id}“中的{}起占位符的作用。

//http://localhost:8080/blog/2
    @GetMapping("/blog/{id}")
    public Object blogByKey(@PathVariable("id") Integer id){
          return blogService.blogOfId(id);
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006736.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号