七【SpringMVC参数绑定】

✅作者简介:Java-小白后端开发者 🥭公认外号:球场上的黑曼巴

🍎个人主页:不会飞的小飞侠24

🍊个人信条:谨 · 信

💞当前专栏:高级内容

🥭本文内容: SpringMVC框架

更多内容点击👇
小飞侠的博客>>>>欢迎大家!!!

在这里插入图片描述

🚩一 . 视图传参到控制器

🌴1.基本数据类型绑定

形参的名字和传递参数的名字保持一致,参数需要全部传递否则报500错误,为了解决不传参报错,可以给基本类型的参数设置默认值

 /**
     * 设置基本参数类型的默认值 @RequestParam(defaultValue = "xx")
     *如果通过url传递了参数,则以传递的为最终的参数
     * @param age
     * @param score
     */
    @RequestMapping("/login2")
    public void login2(@RequestParam(defaultValue = "20") int age , @RequestParam(defaultValue = "24.7") double score){
        System.out.println(age);
        System.out.println(score);
    }

🎄1 设置参数的别名

 public void login3(@RequestParam(defaultValue = "20" ,name = "Age") int age , double score)
 {
        System.out.println(age);
        System.out.println(score);
 }

🌴2.包装数据类型的传递

使用包装类型可以解决基本类型不传递值,出现500错误的问题但是还是要保持参数名字和形参保持一致,

 @RequestMapping("/login4")
    public void login3(Integer age , Double score){
        System.out.println(age);
        System.out.println(score);
    }

🌴3.字符串类型数据的绑定

参照包装类即可

🌴4.数组类型

 public void login3(String[] ids){
        for (int i = 0; i < ids.length; i++) {
            System.out.println(ids[i]);
        }
  }

🌴5.javaBean类型

参数名的字段和Javabean中的属性保持一致即可

 public void login3(User user){
        System.out.println(user);
    }
url:http://localhost:8080/user/login6?age=12&username=lisi&height=1.7

🌴6 返回数据到视图层

@RequestMapping(path = "/res1")
    public ModelAndView test01(){

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("hello");
        modelAndView.addObject("msg", "ModelAndView");
        return modelAndView;
    }

    @RequestMapping(path = "/res2")
    public String test02(Model model){
        model.addAttribute("msg", "model");
        return "hello";
    }

    @RequestMapping(path = "/res3")
    public String test03(ModelMap map){
        map.addAttribute("msg", "ModelMap");
        return "hello";
    }

🚩二 . SpringMVC跳转方式

Spring MVC默认采用服务器内部转发的形式展示页面信息,同时也支持重定向页面

🌴2.1 重定向(302状态码给浏览器)

@Controller
public class HelloController3 {

    @RequestMapping("/r1")
    public void test01(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("redirect.jsp");
    }

    @RequestMapping("/r2")
    public String test02(){
        return  "redirect:redirect.jsp";
    }

    @RequestMapping("/f1")
    public void test03(HttpServletRequest request,HttpServletResponse response) throws 	ServletException, IOException {
        request.getRequestDispatcher("redirect.jsp").forward(request, response);
    }

    @RequestMapping("/f2")
    public String test04(){
        return  "forward:redirect.jsp";
    }

    @RequestMapping("/f3")
    public String test05(){
        return  "redirect";
    }

🚩三 SpringMVC处理json请求和响应

🌴响应json格式的数据

public class JsonController {

    @GetMapping("/login/{username}/{password}")
    public void login(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        //响应json格式的字符串
        res.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
        res.getWriter().write(result.toJSONString());
    }

    @GetMapping("/login2/{username}/{password}")
    @ResponseBody
    public Object login2(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        return JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
    }

    @RequestMapping("/login3")
    @ResponseBody
    public Object login3(User user) {
        System.out.println(user);
        return user;
    }

   

🌴请求数据类型为JSON

 /**
     * 接收json格式的参数
     * @param user
     * @return
     */
    @RequestMapping("/login4")
    @ResponseBody
    public Object login4(@RequestBody User user) {
        System.out.println(user);
        return user;
    }
}


前台ajax请求
<script type="text/javascript">
    $(function () {
        $("#jsbutton").click(function () {
            $.ajax({
                    url:'/login3',
                    type:'post',
                    data:{
                        username:"lisi",
                        age:20,
                        height:170,
                        birth:new Date()
                    },
                    dataType:'json',
                    success:function (result) {
                        console.log(result);
                    },
                    error:function () {
                         console.log("请求失败!")
                     }
            })
        })


        $("#jsbutton2").click(function () {
            var user = {
                username:"lisi",
                age:20,
                height:170,
                birth:'1999-9-9'
            }
            $.ajax({
                url:'/login4',
                type:'post',
                data:JSON.stringify(user),
                contentType:'application/json;charset=utf-8',
                dataType:'json',
                success:function (result) {
                    console.log(result);
                },
                error:function () {
                    console.log("请求失败!")
                }
            })
        })

    })

</script>

🌴RestFul风格

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

URL定义

资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
分别对应 添加、 删除、修改、查询

🌴传统方式操作资源

http://127.0.0.1/item/queryUser.action?id=1       查询,GET 
http://127.0.0.1/item/saveUser.action             新增,POST 
http://127.0.0.1/item/updateUser.action           更新,POST 
http://127.0.0.1/item/deleteUser.action?id=1      删除,GET或POST

🌴RestFul请求方式
可以通过 GET、 POST、 PUT、 PATCH、 DELETE 等方式对服务端的资源进行操作。其中:

  • GET 用于查询资源,
  • POST 用于创建资源,
  • PUT 用于更新服务端的资源的全部信息,
  • DELETE 用于删除服务端的资源。
public class RestController {

    @GetMapping("/rest")
    public void test01(){
        System.out.println("test01: ");
    }  

    @PostMapping("/rest")
    public void test02(){
        System.out.println("test02: ");
    }

    @DeleteMapping("/rest")
    public void test03(){
        System.out.println("test03:");
    }

    @PutMapping("/rest")
    public void test04(){
        System.out.println("test04: ");
    }

    @PatchMapping("/rest")
    public void test05(){
        System.out.println("test05: ");
    }

}

🌴表单发送PUT请求设置方式

 <form action="rest/r" method="post">
        <input type="hidden" name="_method" value="PUT">
        <p><input type="text" placeholder="请输入id" name="id"></p>
        <p><input type="text" placeholder="请输入姓名" name="username"></p>
        <p><input type="date" placeholder="请输入生日" name="birth"></p>
        <p><input type="submit"></p>
 </form>

🌴设置web.xml

<filter>
       <filter-name>Hidden</filter-name>
       <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

<filter-mapping>
    <filter-name>Hidden</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

🌴REST风格传参问题

 @GetMapping("/login/{username}/{password}")
    public void login(@PathVariable String username, @PathVariable String password, HttpServletResponse res) throws IOException {
        System.out.println(username+"::"+password);
        //响应json格式的字符串
        res.setContentType("application/json;charset=utf-8");
        JsonResult result = JsonResult.builder().code(200).count(100L).data(null).msg("ok").build();
        res.getWriter().write(result.toJSONString());
    }

🌴数据提交中文乱码的处理

<!--解决中文乱码-->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

🚩四 SpringMVC静态资源处理

1.配置静态资源的路径

<mvc:resources mapping="/static/**" location="/static/"/>

2.配置使用tomcat的servlet处理器

<mvc:default-servlet-handler/>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值