Java Spring 3 mvc中返回pdf,json,xml等不同的view

HttpServletRequest req,
HttpServletResponse resp)
throws Exception {

Person person = (Person) model.get(“person”);
doc.add( new Paragraph(person.toString()));

}

这里演示简单往itext中写入一个输出而已;

然后是web.xml:

Java代码  收藏代码

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

最核心的配置来了:

Java代码  收藏代码

<bean>
<property name=”order” value=”1″ />
<property name=”mediaTypes”>
<map>
<entry key=”json” value=”application/json” />
<entry key=”xml” value=”application/xml” />
<entry key=”pdf” value=”application/pdf” />

</map>
</property>

<property name=”defaultViews”>
<list>
<!– JSON View –>
<bean
>
</bean>
<!–  XML view –>
<bean>
<constructor-arg>
<bean>
<property name=”classesToBeBound”>
<list>
<value>com.test.Person</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
<!–  PDF view –>
<bean>

</bean>
</list>
</property>
<property name=”ignoreAcceptHeader” value=”true” />

t;/bean>

可以看到,其中使用的是:
org.springframework.web.servlet.view.ContentNegotiatingViewResolver,对其pdf,xml.json进行分别的view设置,JSON用的是著名的jackyson去解析了;

最后,通过rest风格的地址,比如http://localhost/view/view.json,返回json;
http://localhost/view/view.pdf,则导出到pdf,http://localhost/view/view.xml,
返回前端就xml了,真的十分方便呀

Tagged: ,

Comments are closed.