当前位置: 首页 > news >正文

spring_restful_json_jdbc

使用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


相关文章:

  • Docker - 生成镜像
  • 飞鱼星路由器配置端口映射
  • 《Linux Device Drivers》第十八章 TTY驱动程序——note
  • 延迟加载JavaScript
  • 【解决】缺少libstdc++.so.6库的原因及解决的方法
  • 雪城大学信息安全讲义 五、竞态条件
  • virtual的使用方法
  • POJ 1321 棋盘问题(DFS板子题,简单搜索练习)
  • Swift字符串基本操作(二)
  • Oracle空间查询 ORA-28595
  • 优化代码,有效使用内存总结
  • Bootstrap 介绍
  • Liunx笔记:zabbix编译安装
  • 这个时代会残酷惩罚不肯改变的人
  • POJ 3155 Hard Life(最大密度子图)
  • php的引用
  • [原]深入对比数据科学工具箱:Python和R 非结构化数据的结构化
  • 【React系列】如何构建React应用程序
  • Android开发 - 掌握ConstraintLayout(四)创建基本约束
  • C++入门教程(10):for 语句
  • CentOS7简单部署NFS
  • JSONP原理
  • JS基础之数据类型、对象、原型、原型链、继承
  • JWT究竟是什么呢?
  • Laravel Mix运行时关于es2015报错解决方案
  • Odoo domain写法及运用
  • vue-router 实现分析
  • 半理解系列--Promise的进化史
  • 入职第二天:使用koa搭建node server是种怎样的体验
  • 提升用户体验的利器——使用Vue-Occupy实现占位效果
  • 想写好前端,先练好内功
  • 消息队列系列二(IOT中消息队列的应用)
  • 一道闭包题引发的思考
  • Linux权限管理(week1_day5)--技术流ken
  • 你学不懂C语言,是因为不懂编写C程序的7个步骤 ...
  • #define
  • #pragma once
  • (20)目标检测算法之YOLOv5计算预选框、详解anchor计算
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (附源码)node.js知识分享网站 毕业设计 202038
  • (理论篇)httpmoudle和httphandler一览
  • (深度全面解析)ChatGPT的重大更新给创业者带来了哪些红利机会
  • (一一四)第九章编程练习
  • (最优化理论与方法)第二章最优化所需基础知识-第三节:重要凸集举例
  • .gitignore文件---让git自动忽略指定文件
  • .Net - 类的介绍
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • [.NET 即时通信SignalR] 认识SignalR (一)
  • [AutoSar]BSW_Com07 CAN报文接收流程的函数调用
  • [BUUCTF 2018]Online Tool(特详解)
  • [C#] 如何调用Python脚本程序
  • [CF494C]Helping People
  • [dfs搜索寻找矩阵中最长递减序列]魔法森林的秘密路径
  • [DP 训练] Longest Run on a Snowboard, UVa 10285
  • [JavaScript]_[初级]_[不使用JQuery原生Ajax提交表单文件并监听进度]