关于SpringMVC控制器的一点补充

首先复习一下之前控制器的写法:http://www.cnblogs.com/eco-just/p/7882016.html

我们可以看到,之前的写法是这样的:

@RequestMapping("/hello3")
    //http://localhost:8080/webmvc/hello4?name=eco
    public String hello4(String name){
        System.out.println(name);
        return "hello";
    }
@RequestMapping("/hello4")
    public void hello3(HttpServletRequest req,HttpServletResponse resp) throws Exception{
        req.setAttribute("a", "就是我");//a可以用el表达式在下面的页面写出来
        req.getRequestDispatcher("01.jsp").forward(req, resp);//请求转发到根目录下的jsp--不需要视图解析器 
        //resp.sendRedirect("01.jsp");//请求重定向到根目录下的jsp--不需要视图解析器  } 
}

亦或是将上面两者结合起来,但是我们发现一个问题,如果像上面那样写的话,有多少个链接就得写多少个

与之匹配的@RequestMapping,可以说是非常蛋疼的。例如对于一类链接,我们可以将这一类链接综合到一

个@RequestMapping上去。于是就引出下面要说的@PathVariable

@RequestMapping("/{put}")
    public String hello1(@PathVariable String put) {
        return put;
    }

@RequestMapping(
"/free/{put}") public String hello2(@PathVariable("put") String get) { return get; }

两种方法:

1.将路径参数put传给方法参数put,注意,这两个put要一致,就是说路径参数名为put,函数参数名也要是put;

2.@PathVariable("put")获取了路径参数名为put的值,并将其传给方法参数get,这里的函数参数名可以是任意的;

这样一来,虽然我们只写了一个@RequestMapping,但是却可以实现很多链接的跳转行为:

http://localhost:8080/projectname/index--------跳转到index页面;

http://localhost:8080/projectname/hello---------跳转到hello页面;

http://localhost:8080/projectname/free/good---------跳转到good页面;

http://localhost:8080/projectname/free/job-----------跳转到job页面;

原文地址:https://www.cnblogs.com/eco-just/p/8537215.html