SpringMVC的Handler处理及url映射

1.Handler的理解?

 一个handler就是一个控制器里的某个方法,而通常情况下,该方法会对应到相应的url

2.每个Handler的返回值?

 1返回的是ModelAndView对象

ModelAndView代表的是响应的视图,还有一个向该视图传递的数据。比如:

@RequestMapping(value="/getalluser.action")

public ModelAndView getAllUser(){

ModelAndView model = new ModelAndView();

List<UserInfo> list = userInfoService.getList(null);

model.addObject("users", list);//表示向页面传递的数据

model.setViewName("/index.jsp");//表示呈现的页面

return model;

}

2返回的是String类型

   a.转发。类似于request.getRequestDispacher(“页面名称”).forward(request,response);

     特点:url路径不发生改变,但是request共享。

   在handler方法返回的时候:return “forward:/edit.action”;

   b.重定向,类似于response.sendRedirect(“页面名称”);

     特点:url路径发生改变,但是request不共享。

    在handler中返回值:return "redirect:/item.action";

3返回的是void类型。有的handler的处理是不需要有返回页面的情况,那这个时候就采取返回的类型为void

   适用情况:请求json或者xml的数据格式,或者请求的就是一串字符串数据。

    写法:类似于servlet的处理。

@RequestMapping(value=”/aaa.action”)

public void addType(HttpServletRequest req,HttpServletResponse resp){

        //JSON处理

        List<UserInfo> list = userService.getList();

//序列化的操作

   JSONArray jsonArray = JSONArray.fromObject(list);

   String strInfo = jsonArray.toString();

   System.out.println(strInfo);

   PrintWriter pw = response.getWriter();

   pw.print(strInfo);

    }

2.URL映射

1同一个handler处理多个路径的情况下

@RequestMapping(value={"/index", "/hello"}, method = {RequestMethod.GET})

以上表示的就是可以处理index.actionhello.action的路径。

method表示限定的请求方法,

2url风格设定

   restful风格设定:

我们的请求路径的风格为这样:

   /方法名/参数1/参数2

   案例:

   @RequestMapping(value="/detail/{id}",method={RequestMethod.GET})

public ModelAndView detail(@PathVariable(value="id") Integer id){

System.out.println("hello");

ModelAndView model = new ModelAndView();

    UserInfo u = userInfoService.getUserInfo(id);

    model.addObject("user", u);

    model.setViewName("/user.jsp");

return model;

}

注意:{}里的参数名和PathVariable里的value里的名字一定要一致

访问路径:http://localhost:10086/ssmdemo2/detail/81.action

3通配符映射 

•          我们还可以通过通配符对URL映射进行配置,通配符有“?”和“*”两个字符。其中“?”表示1个字符,“*”表示匹配多个字符,“**”表示匹配0个或多个路径。 

比如:“/helloworld/index?”可以匹配“/helloworld/indexA”“/helloworld/indexB”但不能匹配“/helloworld/index”也不能匹配“/helloworld/indexAA”

“/helloworld/index*”可以匹配“/helloworld/index”“/helloworld/indexA”“/helloworld/indexAA”但不能匹配“/helloworld/index/A”

“/helloworld/index/*”可以匹配“/helloworld/index/”“/helloworld/index/A”“/helloworld/index/AA”“/helloworld/index/AB”但不能匹配    /helloworld/index”“/helloworld/index/A/B”;

“/helloworld/index/**”可以匹配“/helloworld/index/”下的多有子路径,比如:“/helloworld/index/A/B/C/D”;

如果现在有“/helloworld/index”和“/helloworld/*”如果请求地址为“/helloworld/index”那么将如何匹配?Spring MVC会按照最长匹配优先原则(即和映射配置中哪个匹配的最多)来匹配,所以会匹配“/helloworld/index

4url正则表达式匹配

Spring MVC还支持正则表达式方式的映射配置,我们通过一 

@RequestMapping(value="/reg/{name:\\w+}-{age:\\d+}", method = {RequestMethod.GET})

public ModelAndView regUrlTest(@PathVariable(value="name") String name, @PathVariable(value="age") Integer age){

   }

 

猜你喜欢

转载自blog.csdn.net/y1991024/article/details/51945216
今日推荐