根据URL获取参数值得出json结果集,对外给一个接口让别人调用
背景:测试接口的时候,经常都是后端get\post请求直接返回json结果集,很想知道实现方式,虽然心中也大概了解如何实现,但还不如自己来一遍踏实!
先来看一下结果吧:
以下对一个web的get接口进行解析:
一、分层架构图:因都是老生常谈,具体不详解,我的层级分的很清楚,数据读mysql库,理论上有基础的都看得懂
二、代码展示
(1)工具类-数据源连接
package util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /* * DAO层的工具类-读取数据库文件生成实例 */ public class ConfigManager { private static ConfigManager configManager; private static Properties properties = null; //构造方法私有化,用单例模式,一生成实例,就加载data.properties private ConfigManager(){ properties = new Properties(); InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream("data.properties"); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); }finally{ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } //生成实例 public static ConfigManager getInstance(){ if(configManager==null){ configManager = new ConfigManager(); } return configManager; } //得到属性值的方法 public static String getValue(String key){ return properties.getProperty(key); } }
ConfigManager只是为了读取data.properties文件中的各个数据源配置的值
jdbc.driver_class=com.mysql.jdbc.Driver jdbc.connection.url=jdbc\:mysql\://127.0.0.1\:3306/test?characterEncoding\=UTF-8 jdbc.connection.username=root jdbc.connection.password=root
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /* * 基类:获取数据库连接及关闭连接、数据库增删改和查询 工具类 * 对数据库的基本操作 */ public class BaseDao { private Connection connection=null; private PreparedStatement pstm =null; private ResultSet resultset = null; //获取数据库连接 public boolean getconnection(){ boolean flag =false; String driver = ConfigManager.getInstance().getValue("jdbc.driver_class"); String url = ConfigManager.getInstance().getValue("jdbc.connection.url"); String username = ConfigManager.getInstance().getValue("jdbc.connection.username"); String password = ConfigManager.getInstance().getValue("jdbc.connection.password"); try { Class.forName(driver); connection = DriverManager.getConnection(url, username, password); flag = true; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return flag; } //增、删、改操作 public int executeUpdate(String sql,Object[] params){ int update = 0; try { //预加载sql pstm = connection.prepareStatement(sql); for(int i=0;i<params.length;i++){ pstm.setObject(i+1, params[i]); } update = pstm.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return update; } //查询操作 public ResultSet executeQuery(String sql,Object[] params){ try { pstm = connection.prepareStatement(sql); for(int i=0;i<params.length;i++){ pstm.setObject(i+1, params[i]); } resultset = pstm.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return resultset; } /*//模糊查询操作 public ResultSet executeQueryLike(String sql,Object[] params){ try { pstm = connection.prepareStatement(sql); for(int i=0;i<params.length;i++){ pstm.setObject(i+1, "%"+params[i]+"%"); } resultset = pstm.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return resultset; }*/ //关闭连接 public void clossconnection(){ if(resultset!=null){ try { resultset.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pstm!=null){ try { pstm.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
真正获取数据库连接,把增删除改查的方法集成工具类的,还得看BaseDao,你也可以一个java一锅炖,获取data.properties值,然后用到什么写什么
(2)dao和dao.impl
package dao; import java.util.List; import entity.News; /** * new表实现接口 * @author 0 * */ public interface NewsDao { public List<News> getrows(String where); } ---------------------------- package dao.impl; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import util.BaseDao; import dao.NewsDao; import entity.News; /** * dao实现类 * @author 0 * */ public class NewsDaoImpl extends BaseDao implements NewsDao { @Override public List<News> getrows(String where) { List<News> listnews=new ArrayList<News>(); News news=null; String sql="select id,title,createdate,createby,url from news where 1=1 "+where; Object[] params={}; System.out.println("sql==="+sql); if(this.getconnection()){ ResultSet rs = this.executeQuery(sql, params); try { while(rs.next()) { news = new News(); int id = rs.getInt("id"); String title = rs.getString("title"); Timestamp createdate = rs.getTimestamp("createdate"); String createby=rs.getString("createby"); String url=rs.getString("url"); news.setId(id); news.setTitle(title); news.setCreatedate(createdate); news.setCreateby(createby); news.setUrl(url); listnews.add(news); } } catch (Exception e) { e.printStackTrace(); } } return listnews; } }
备注:这里要注意的是select最好写自己想要的字段,而不要写*
(3)service与service.impl
package service; import java.util.List; import entity.News; public interface NewsService { public List<News> getrows(String where); } ------------------------------------------------------------- package service.impl; import java.util.List; import dao.NewsDao; import dao.impl.NewsDaoImpl; import entity.News; import service.NewsService; public class NewsServiceImpl implements NewsService { private NewsDao newsdao=new NewsDaoImpl(); @Override public List<News> getrows(String where) { return newsdao.getrows(where); } }
备注:可要可不要,我这没什么逻辑,所以可以不用。
(4)json字段
package util; import java.util.List; import entity.News; /** * 新建分页测试类NewTotal,主要用于Json分页显示 * @author 0 * */ public class NewTotal { private int totle;//总数 private List<News> rows;//新闻列表 public NewTotal() { } public NewTotal(int totle, List<News> rows) { this.totle = totle; this.rows = rows; } public int getTotle() { return totle; } public void setTotle(int totle) { this.totle = totle; } public List<News> getRows() { return rows; } public void setRows(List<News> rows) { this.rows = rows; } }
备注:其实这里的2个字段定义,就是页面中出现的2个
(5)servlet
package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import entity.News; import service.NewsService; import service.impl.NewsServiceImpl; import util.NewTotal; public class NewsInfoServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { NewsService newsService=new NewsServiceImpl(); String createby=request.getParameter("createby"); String page = request.getParameter("page"); String pageSize=request.getParameter("pageSize"); int pageNo=0;//页码 int pageS=0;//页码量 StringBuffer where=new StringBuffer();//where条件查询拼接字符串 //判断页码值或参数存不存在 if(page!=null &&!"".equals(page)){ pageNo=Integer.parseInt(page); }else{//如果当前页码为空,则默认出第1页 pageNo=1; } if(pageSize!=null &&!"".equals(pageSize)){ pageS=Integer.parseInt(pageSize); }else{//如果页码容量为空,则默认出一页10条 pageS=10; } //判断创建者参数是否为空,并拼接字符串查询 if(createby!=null &&!"".equals(createby)){ where.append(" and createby like '%"+createby+"%'"); } //如果页码值存在,页码容量不存在 if(pageNo>0 &&(pageSize==null &&"".equals(pageSize))){ where.append(" limit "+(pageNo-1)*10+",10"); System.out.println("第1"); } //如果页码值存在,页码容量存在:实际上完全为空的情况已经排除掉了,如果都存在肯定则可能输入默认的情况 if(pageNo>0 && pageS>0){ where.append(" limit "+(pageNo-1)*pageS+","+pageS); System.out.println("第2"); } //如果页码值不存在,页码容量存在 if((page==null &&"".equals(page)) && pageS>0 ){ where.append(" limit 1,"+pageS); System.out.println("第3"); } System.out.println(where.toString()); List<News> listn=newsService.getrows(where.toString()); int totalCount=listn.size();//总量 //新数据封装到新闻总计类中 NewTotal nt=new NewTotal(totalCount, listn); //调用Gson Gson gson=new Gson(); String json=gson.toJson(nt); //输出到界面 System.out.println(json); response.setCharacterEncoding("text/plain"); response.setCharacterEncoding("utf-8"); PrintWriter out =new PrintWriter(response.getOutputStream()); out.print(json); out.flush(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
备注:就这个想了一下,因为条件会比较多,各样条件,也有可能不是太充分有考虑,遇到bug再加吧~~~(我们这的开发都是这样的水平,哈哈)
(6)jsp页面与web.xml
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my JSP page. <br> <form action="getJson" method="get"> <!-- <input type="submit" value="点击获取新闻JSON数据"/> --> </form> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>NewsInfoServlet</servlet-name> <servlet-class>servlet.NewsInfoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>NewsInfoServlet</servlet-name> <url-pattern>/newsInfoServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>JsonServlet</servlet-name> <servlet-class>servlet.NewsInfoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JsonServlet</servlet-name> <url-pattern>/getJson</url-pattern> </servlet-mapping> </web-app>
其实上面这个例子非常之简单,有一段时间没有碰代码了,写起来费了点时间,不过很多都是找旧代码拷过来的。
常时间不写代码就是这么生疏!!
ps:我的servlet写的都挺顺手,但是框架不行~框架不行~框架不行~~~
如果您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】
本文版权归作者和博客园共有,欢迎转载