使用Spring MVC +JDBC 实现输出Json数据和视图两种形式 最后面有源代码

从web.xml開始配置:

声明定义两个Servlet各自是输出视图和json

<!-- 声明一个Servlet 并进行配置 -->
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-servlet.xml</param-value>
</init-param>
<!-- 标记容器是否在启动的时候就载入这个servlet 当是一个负数时或者没有指定时,则指示容器在该servlet被选择时才载入。正数的值越小。启动该servlet的优先级越高。 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!-- 声明一个Servlet END -->
<!-- 声明一个Servlet 并进行配置 -->
<servlet>
<servlet-name>json</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/json-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>json</servlet-name>
<url-pattern>/json/*</url-pattern>
</servlet-mapping>
<!-- 声明一个Servlet END -->

其它配置略过

首先是第一个Servlet – rest,指定的配置文件rest-servlet.xml(默认也是,,,)

<?

xml version="1.0" encoding="UTF-8"?

>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 搜索Controller路径 -->
<context:component-scan base-package="com.znn.rest.controller">
<!-- 忽略这个包 -->
<!-- <context:exclude-filter type="assignable" expression="com..."/> -->
</context:component-scan>
<!-- 简写形式 会自己主动注冊DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter两个bean,是spring
MVC为@Controllers分发请求所必须的。 -->
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

在包com.znn.rest.controller下创建一个Controller:UserController.java

用注解@Controller进行声明这是一个Controller。Spring会自己主动扫描到

package com.znn.rest.controller;

import java.lang.reflect.Method;
import java.util.List; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import com.znn.dao.UserDao;
import com.znn.vo.User;
/**
* RestFul 返回视图
*
* @author RANDY.ZHANG
* 2014-5-7
*/
@Controller
public class UserController {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
UserDao dao = (UserDao) applicationContext.getBean("userDao"); @RequestMapping("/hi")
public String helloWorld(Model model) {
model.addAttribute("msg", "Hello HelloWorld");
return "hello";
// return "redirect:hello.jsp";
}
@RequestMapping("/user/{id:\\d+}")
public String getUser(Model model,@PathVariable("id") int userid) {
User user;
user = dao.queryAUser(userid);
if (user == null) {
model.addAttribute("tip", "<font color='red'>用户不存在! </font>");
}else {
model.addAttribute("tip", user.toString());
}
return "user";
}
@RequestMapping(value = "/user/*",method=RequestMethod.GET)
public String getAllUser(Model model) {
List<User> list = dao.query();
String tipString = "";
for (int i = 0; i < list.size(); i++) {
tipString += list.get(i).toString()+"<br />";
}
model.addAttribute("tip",tipString);
return "user";
}
@RequestMapping(value = "/user",method=RequestMethod.GET)
public String getAUser(Model model,
@RequestParam(value="id",required=false,defaultValue="1") int userid,
@RequestHeader("user-agent") String agent) {
User user;
user = dao.queryAUser(userid);
if (user == null) {
model.addAttribute("tip", "<font color='red'>用户不存在! </font>");
}else {
model.addAttribute("tip", user.toString());
}
System.out.println(agent);
return "user";
}
}

使用InternalResourceViewResolver进行视图适配。方法返回的字符串会自己主动加入上前后缀,另外还支持redirect:和forward:两种特殊配置,仅仅是注意下要路径。

关于MVC的注解以及RequestMapping的配置使用方法到:http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html#mvc-introduction,里面讲的挺具体。

另外一种输出JSON:

从Spring 3.1開始支持@ResponseBody来直接将数据返回到HTTP响应体重,不在须要ModalView或者其它进行渲染。Spring提供了一些HttpMessageConverter来对数据进行转换,比方StringHttpMessageConverter,FormHttpMessageConverter。MappingJackson2HttpMessageConverter 。其它见这里,这里用到了StringHttpMessageConverter用来进行编码转换,MappingJackson2HttpMessageConverter 用来将数据转为Json形式。

json-servlet.xml

<?xml version="1.0" encoding="UTF-8"?

>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <!-- 搜索Controller路径 -->
<context:component-scan base-package="<strong>com.znn.json.controller</strong>">
<!-- 忽略这个包 -->
<!-- <context:exclude-filter type="assignable" expression="com..."/> -->
</context:component-scan> <!-- Spring 3.1之后開始用这两个 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
</list>
</property>
</bean>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html; charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
</beans>

从3.1開始推荐使用RequestMappingHandlerMapping和RequestMappingHandlerAdapter来取代DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter。只是不换也木事。

。。

在com.znn.json.controller下新建一个Controller

UserJson.java

package com.znn.json.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.znn.dao.UserDao;
import com.znn.vo.User;
/**
* 返回@ResponseBody须要配置HttpMessageConverters
*
* @author RANDY.ZHANG
* 2014-5-7
*/
@Controller
public class UserJson {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
UserDao dao = (UserDao) applicationContext.getBean("userDao"); @RequestMapping("/hi")
public @ResponseBody String helloWorld(Model model) {
// model.addAttribute("msg", "Hello HelloWorld");
return "hello world";
// return "redirect:hello.jsp";
} @RequestMapping("/user/{id:\\d+}")
public @ResponseBody User getUser(Model model,@PathVariable int id) {
User user;
user = dao.queryAUser(id);
if (user == null) {
model.addAttribute("tip", "<font color='red'>用户不存在!</font>");
}else {
model.addAttribute("tip", user.toString());
}
return user;
}
@RequestMapping(value = {"/user/*","/user"},method=RequestMethod.GET)//,produces="application/json" 406
public @ResponseBody List<User> getAllUser(Model model) {
List<User> list = dao.query();
String tipString = "";
for (int i = 0; i < list.size(); i++) {
tipString += list.get(i).toString()+"<br />";
}
model.addAttribute("tip",tipString);
return list;
}
@RequestMapping(value = "/user/aaa",method=RequestMethod.GET)
public @ResponseBody List<User> getTest(Model model,HttpServletResponse response, HttpServletRequest request) {
List<User> list = dao.query();
String tipString = "";
for (int i = 0; i < list.size(); i++) {
tipString += list.get(i).toString()+"<br />";
}
model.addAttribute("tip",tipString);
return list;
}
}

木有啥好说的….

跟JDBC连接的及DAO层代码和http://www.erdian.net/?p=141是一样的,不再写。

源代码:https://github.com/qduningning/SpringAll

spring_restful_json_jdbc的更多相关文章

随机推荐

  1. jmeter用BeanShell调用jar包对HTTP请求中的参数进行MD5加密

    前提: eclipse.JDK.Jmeter 说明: 本文分为两部分进行配置说明 第一部分:编写JavaMD5加密脚本 第二部分:使用Jmeter的BeanShell进行验证 ************ ...

  2. php中赋值和引用真真的理解

    php的引用(就是在变量或者函数.对象等前面加上&符号) //最重要就是 删除引用的变量 ,只是引用的变量访问不了,但是内容并没有销毁 在PHP 中引用的意思是:不同的名字访问同一个变量内容. ...

  3. 【原】不定义Order属性,通过切面类的定义顺序来决定通知执行的先后顺序

    [结论] 在多个切面类的“切入点相同”并且每个切面都“没有定义order属性”的情况下,则切面类(中的通知)的执行顺序与该切面类在<aop:config>元素中“声明的顺序”相关,即先声明 ...

  4. 解决MySQL建立连接问题,快速回收复用TCP的TIME_WAIT

    最近同事遇到一个问题,使用python开发的工具在执行的时候无法和MySQL建立连接,其最直接的现象就是满篇的TIME_WAIT,最后通过调整tcp_timestamps参数问题得以解决,再次记录一下 ...

  5. 设置ubuntu 终端显示路径长度

    ~/.bashrc 这个文件记录了用户终端配置. 打开~/.bashrc 这个文件 $: sudo vim ~/.bashrc 找到 将蓝色的w由小写改成大写,可以表示只显示当前目录名称.

  6. Apache的443端口被占用解决方法(转)

    今天想做PHP程序,结果启动Apache的时候控制台报443端口被占用.原因是我的虚拟机VMware占用443端口用于连接远程服务器的.其实出现这些状况很正常.因为不同的程序很有可能同时需要一个端口维 ...

  7. Hibernate: Implicit & Explicit Polymorphism

    As I was going through the various inheritance strategies in Hibernate, I came across the ‘class’ el ...

  8. Latex Error cannot determine the size of graphic 报错的解决的方法

    Latex Error cannot determine the size of graphic 报错的解决的方法 插入jpg文件老是会报错... 追究了半天,原来是编译的命令又问题,不应该使用 la ...

  9. 查看是否安装.NET Framework、.NET Framework的版本号、CLR版本号

    查看是否安装.NET Framework→%SystemRoot%\System32→如果有mscoree.dll文件,表明.NET Framework已安装 查看安装了哪些版本的.NET Framw ...

  10. 用宏判断程序当前的运行模式(debug or release)

    例子 #if defined (DEBUG) && DEBUG == 1 // 如果当前处于debug 模式 //to do #else //to do #endif