SpringMvc数据响应

1、Spring-mvc.xml中配置视图解析

 <!--  配置视图解析   -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--    视图名前缀  -->
        <property name="prefix" value="/jsp/"></property>
        <!--     视图名后缀  -->
        <property name="suffix" value=".jsp"></property>
    </bean>

2、返回视图以及返回信息的几种实现方式

@RequestMapping("/quick1")
    public String Test1(HttpServletRequest request) {
        request.setAttribute("username", "HttpServletRequest");
        return "ok";
    }

    @RequestMapping("/quick2")
    public String Test2(Model model) {
        model.addAttribute("username", "Model");
        return "ok";
    }

    @RequestMapping("/quick3")
    public ModelAndView Test3(ModelAndView modelAndView) {
        modelAndView.addObject("username", "ModelAndView");
        modelAndView.setViewName("ok");
        return modelAndView;
    }

    @RequestMapping("/quick4")
    public ModelAndView Test4() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("username", "ModelAndView");
        modelAndView.setViewName("ok");
        return modelAndView;
    }

3、Spring-Mvc.xml中配置处理器映射

    <!--  对象转json   配置处理器映射-->
    <!--    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
    <!--        <property name="messageConverters">-->
    <!--            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>-->
    <!--        </property>-->
    <!--    </bean>-->
    <mvc:annotation-driven/>

4、返回内容实现方式:

 @RequestMapping("/quick5")
    @ResponseBody
    public void Test5(HttpServletResponse response) throws IOException {
        response.getWriter().println("HttpServletResponse");
    }

    @RequestMapping("/quick6")
    @ResponseBody
    public String Test6() {
        return "Hello Word Spring MVC";
    }

    @RequestMapping("/quick7")
    @ResponseBody
    public String Test7() throws JsonProcessingException {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1);
        userInfo.setUserName("zhangsan");
        userInfo.setPassword("123456");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(userInfo);
        return s;
    }

    @RequestMapping("/quick8")
    @ResponseBody
    public UserInfo Test8() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(1);
        userInfo.setUserName("zhangsan");
        userInfo.setPassword("123456");
        return userInfo;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值