SpringMvc学习笔记(三)对Servlet API和json的支持

来源:互联网 发布:ubuntu dokuwiki 编辑:程序博客网 时间:2024/05/19 16:04

一.对Servlet API的支持

springmvc支持传入的Sevlet原生api一共有以下这些:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. Java.security.Principal
5. Locale
6. InputStream
7. OutputStream
8. Reader

9. Writer

使用起来很简单,就是把你想用的Servlet API传入Controller类方法的参数中即可使用。

@RequestMapping("/login")public void login(HttpServletRequest request,HttpServletResponse response){}

二.对json的支持

首先需要添加支持json需要的jar包

然后是添加spring-mvc.xml配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:p="http://www.springframework.org/schema/p"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="        http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc.xsd        http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd"><!-- 支持对象与json的转换。 -->    <mvc:annotation-driven/>  <!-- 使用注解的包,包括子集 -->    <context:component-scan base-package="com.zhu"/>    <!-- 视图解析器 --><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp"></property></bean></beans>

使用方法  在返回值前添加@ResponseBody注解即可,非常简单

@RequestMapping("/get")public @ResponseBody Student getStudent(){return new Student(1,"张三",10);}
响应的页面

阅读全文
1 0