0
点赞
收藏
分享

微信扫一扫

springmvc-02

小禹说财 2022-01-26 阅读 56
springmvc

几种注解

@RequestMapping:

还是这个好用,定义标签,就不用来回注册bean了,一个controller中可以写好多个方法

RestFul 风格:

以前我们用的url传递参数时:

http://localhost:8080/springmvx_04_controller_war_exploded/h1?a=1&b=2

用了RestFul风格之后,就不需要这么多等号了,需要在参数位置进行改变,看代码

http://localhost:8080/springmvx_04_controller_war_exploded/h1/1/2

@Controller
public class controllerRestFul {

    @RequestMapping("/h1/{a}/{b}")
    public String test(@PathVariable int a,@PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果为"+res);
        return "test1";
    }
}

我们通过在RequestMapping中增加位置,在函数参数增加 @PathVariable标签实现了该风格

简便,好看

额,还能这样写

总之,RestFul风格就是要注意 传递参数的时候使用 @PathVariable注释一下参数

调试过程中,出现问题就一步一步详细的看看代码,可能错误就解决了。小黄鸭调试法。

转发和重定向:

@Controller
public class ModeTest1 {

    @RequestMapping("/h1/t1")
    public String tes1(Model model){
        model.addAttribute("msg","转发和重定向");
        return "/WEB-INF/jsp/test1.jsp";
    }

    @RequestMapping("/h1/t2")
    public String tes2(Model model){

        model.addAttribute("msg","转发和重定向");

        return "redirect:/index.jsp";
    }
}

在不使用视图解析器的情况下,  return的内容是全路径名实现转发,也可以这样

 重定向需要使用  redirect 标签,在有视图解析器的情况也会优先使用转发,不会先去拼接。

前端传递数据:

如果传递的参数名字和给定的参数一致,可以直接传递

如果不一致,需要添加

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

    @RequestMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        model.addAttribute("msg",name);
        return "test1";
    }

    @RequestMapping("t2")
    public String test2(User user,Model model){
        model.addAttribute("msg",user.toString());
        return "test1";
    }
}

如果是对象,spring会自动匹配传递的参数和对象的参数是否一致,如果一致则传递,不一致就为 null。

过滤乱码:

正常的传递数字和字母没啥问题,但是提交一个汉字的话,就会出现乱码问题。

解决方法:使用过滤器,自定义的过滤器不好用,我也没写过;直接上spring提供的高级货,在web.xml中配置一下就好了

但是这个放在在一些情况下对  Get 方法不行,所以有大神就弄了个更高级的,我只留下代码,具体怎么用我也不会。

网上大神写的,看不懂,能用。总之,看看tomcat的编码,看看过滤器,不行就换。

举报

相关推荐

0 条评论