SpringMVC基于注解使用: 响应处理 视图解析器

276 阅读1分钟

1、使用默认内置试图解析器 ViewReslover image.png

为了让jsp文件经过控制器 ,所有的jsp文件都放到 WEB-INF/views里面

方法

@RequestMapping("/response")
public String response1(){



  //  return "/WEB-INF/views/index.jsp";
//将/WEB-INF/views/index.jsp简写为index 此时需要配置试图解析器
    return "index";
}

Shift+ Ctrl +Alt +N 搜索 file dispatcherServlet

image.png

打开后能够看到默认配置信息

image.png

通过配置视图解析器 简化视图名称

1、配置sping xml 文件

<!--默认试图解析器  配置前缀 后缀  简化逻辑视图名称-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" name="viewResolver">
    <!--前缀-->
    <property name="prefix" value="/WEB-INF/views/"></property>
    <!--后缀-->
    <property name="suffix" value=".jsp"></property>

</bean>

2、可以将视图/WEB-INF/views/index.jsp简写为index

不在根目录的jsp 视图控制器配置

<!--视图控制器-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<mvc:view-controller path="/main" view-name="main"></mvc:view-controller>

path : 需要映射的路径
view-name : 对应的视图名称

=======================================

响应处理 使用request Map ModelMap Model 传输数据

1、使用例子:

  @RequestMapping("servletAPI")
    public String servletAPI(HttpServletRequest request){
        request.setAttribute("type","servletAPI");

        return "main";
    }
    //使用Model Map ModelMap 传输数据到页面
    @RequestMapping("/model")
    public String model(Model model){
//        model.addAttribute( );
//        model.addAllAttributes();

        //底层还是使用的 request.setAttribute
        model.addAttribute("type","Model");
        return "main";
    }

    @RequestMapping("modelmap")
    public String modelmap(ModelMap modelMap){
        modelMap.addAttribute("type","ModelMap");
        return "main";

    }
    @RequestMapping("map")
    public String map(Map map){
        map.put("type","map");
        return "main";
    }

模板调用:

测试:${requestScope.type}

2、依赖分析 1675495839463.png

HttpServletRequest 耦合ServletAPI方式

Map ModelMap Model 实际上是一样的 最终使用 BindingAwareModel

image.png

分别使用

System.out.println("ModelMap:"+modelMap.getClass());

打印参数类。

HttpServletRequest:class org.apache.catalina.connector.RequestFacade
model:class org.springframework.validation.support.BindingAwareModelMap
ModelMap:class org.springframework.validation.support.BindingAwareModelMap
Map:class org.springframework.validation.support.BindingAwareModelMap

响应处理使用ModelAndView

@RequestMapping("modelandview")
public ModelAndView modelAndView(){
    ModelAndView main = new ModelAndView("main");


  //  main.setViewName("index");  //设置跳转视图

    main.addObject("type","ModelAndView");
    return main;
}