springmvc搭建返回json格式的restful api

目标:实现如下的restful api,返回格式为json

/blog/100 HTTP GET  =>  得到id = 100的blog
/blog/100 HTTP DELETE => 删除 id = 100的blog
/blog/100 HTTP PUT =>  更新id = 100的blog
/blog   HTTP POST =>  新增blog


用到的jar包:

springmvc搭建返回json格式的restful api_第1张图片


主要代码:

web应用配置文件

web.xml 



	
		CharacterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			UTF-8
		
		
			forceEncoding
			true
		
	

	
		CharacterEncodingFilter
		/*
	
	
		springmvc
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			classpath:springmvc.xml
		
		1
	

	
		springmvc
		/
	


springmvc配置文件,注意配置stringConverter和jsonConverter

springmvc.xml


	
		
			
				text/plain;charset=UTF-8
			
		
	
	

	
		
			
				
				
			
		
	
	
		
		
		
	
	


记录日志,使用log4j

log4j.properties

### set log levels ### 
log4j.rootLogger = info , Console , D
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=INFO
log4j.logger.java.sql.PreparedStatement=INFO
#output2file
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender 
log4j.appender.D.File = D:/logs/log-restful.log 
log4j.appender.D.Append = true 
log4j.appender.D.Threshold = INFO ## è¾åºinfo级å«ä»¥ä¸çæ¥å¿ 
log4j.appender.D.layout = org.apache.log4j.PatternLayout 
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n 


控制器,定义请求参数,方法,返回格式json

BlogController.java

package com.ihefe.controller;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
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.ihefe.model.Blog;


@Controller
public class BlogController {
	/** 日志实例 */
	private static final Logger logger = Logger.getLogger(BlogController.class);

	@RequestMapping(value = "/index", produces = "text/plain;charset=UTF-8")
	public @ResponseBody String hello() {
		return "hello";
	}

	@RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
	public @ResponseBody String say(@PathVariable(value = "msg") String msg) {
		return "{\"msg\":\"you say:'" + msg + "'\"}";
	}

	@RequestMapping(value = "/blog/{id:\\d+}", method = RequestMethod.GET)
	public @ResponseBody Blog getBlog(@PathVariable("id") int id) {
		logger.info("获取博客id=" + id);
		Blog blog = new Blog();
		blog.setTitle("博客标题");
		blog.setBrief("博客概要");
		blog.setContent("博客内容");
		blog.setId(id);
		return blog;
	}

	@RequestMapping(value = "/blog/{id:\\d+}", method = RequestMethod.DELETE)
	public @ResponseBody Object deleteBlog(@PathVariable("id") int id) {
		logger.info("删除博客信息id=" + id);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", "删除博客成功");
		return jsonObject;
	}

	@RequestMapping(value = "/blog", method = RequestMethod.POST)
	public @ResponseBody Object addBlog(Blog blog) {
		logger.info("添加博客成功id=" + blog.getId());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", "添加博客成功");
		return jsonObject;
	}

	@RequestMapping(value = "/blog/{id:\\d+}", method = RequestMethod.PUT)
	public @ResponseBody Object updateBlog(Blog blog) {
		logger.info("更新博客id=" + blog.getId());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("msg", "更新博客成功");
		return jsonObject;
	}

}

博客实体类
Blog.java

package com.ihefe.model;

public class Blog {
	private int id;
	private String title;
	private String brief;
	private String content;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getBrief() {
		return brief;
	}

	public void setBrief(String brief) {
		this.brief = brief;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "Blog [id=" + id + ", title=" + title + ", brief=" + brief
				+ ", content=" + content + "]";
	}

	public Blog() {
		super();
		// TODO Auto-generated constructor stub
	}
}

测试,使用火狐httprequester工具:

springmvc搭建返回json格式的restful api_第2张图片

springmvc搭建返回json格式的restful api_第3张图片

springmvc搭建返回json格式的restful api_第4张图片

springmvc搭建返回json格式的restful api_第5张图片

springmvc搭建返回json格式的restful api_第6张图片



你可能感兴趣的:(java)