thinkphp加iview-admin的前后端分离项目,请问thinkphp如何调试后端自己写的接口?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了thinkphp加iview-admin的前后端分离项目,请问thinkphp如何调试后端自己写的接口?相关的知识,希望对你有一定的参考价值。
我现在写的接口,直接用浏览器访问拼出来的地址,提示要登录,不知道怎么才能看到我返回的字串
参考技术A 无需登录的接口,*表示全部SQL前后端分页
/class Page<T>
package com.neusoft.bean; import java.util.List; public class Page<T> { private List<T> data; //后台数据库查询出来 private int totalRecord; //表示总共有多少记录,从数据库中查询出来 // private int totalPage; // 表示总共有多少页,计算得到! // private int index; //表示当前索引值,计算出来的! private int pageNumber; //表示的是当前页码,这个参数是从页面传递过来的! private int pageSize; //表示的是每页显示多少条数据 ,在servlet中设置的! private String path; public Page() { super(); } public Page(int totalRecord, int pageNumber, int pageSize) { super(); this.totalRecord = totalRecord; this.pageNumber = pageNumber; this.pageSize = pageSize; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public int getTotalRecord() { return totalRecord; } public void setTotalRecord(int totalRecord) { this.totalRecord = totalRecord; } public int getTotalPage() { /** * totalPage:表示总共有几页! * * 总页数 totalRecord[总记录数] pageSize * 5 10 2 * 5 9 2 * 4 8 2 */ if(totalRecord % pageSize ==0){ return totalRecord / pageSize; } return (totalRecord / pageSize + 1); } public int getIndex() { /** * index表示的是当前索引值,是计算得到的! * 当前索引值 每页显示几条数据 当前页是第几页 * 0 3 1 * 3 3 2 * index = (pageNumber -1)*pageSize; */ return (getPageNumber() -1)*pageSize; } public int getPageNumber() { if(pageNumber < 1){ return 1; }else if(pageNumber > getTotalPage()){ return getTotalPage(); } return pageNumber; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } }
/class Student
package com.neusoft.bean; public class Student { private int id; private String name; private String school; private String score; public Student() { super(); // TODO Auto-generated constructor stub } public Student(int id, String name, String school, String score) { super(); this.id = id; this.name = name; this.school = school; this.score = score; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", school=" + school + ", score=" + score + "]"; } }
/class StudentDao
package com.neusoft.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.neusoft.bean.Student; import com.neusoft.utils.JDBCUtil; public class StudentDao { public List<Student> getStudentList(){ PreparedStatement ps=null; ResultSet rs =null; List<Student> list=new ArrayList<Student>(); Connection conn=JDBCUtil.getConnection(); String sql="select * from student"; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { Student stu=new Student(); int id = rs.getInt("id"); String username = rs.getString("name"); String school = rs.getString("school"); String score = rs.getString("score"); stu.setId(id); stu.setName(username); stu.setSchool(school); stu.setScore(score); list.add(stu); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtil.close(ps, rs, conn); } return list; } public static int delete(int id){ return JDBCUtil.executeUpdate("delete from student where id=?",id); } public int update(Student student){ return JDBCUtil.executeUpdate("update student set name=?,school=?,score=? where id=?",student.getName(),student.getSchool(),student.getScore(),student.getId()); } public int add(Student student){ return JDBCUtil.executeUpdate("insert into student (id,name,school,score) values (?,?,?,?)",null,student.getName(),student.getSchool(),student.getScore()); } public List<Student> getStudent(Student student){ PreparedStatement ps=null; ResultSet rs =null; List<Student> list=new ArrayList<Student>(); Connection conn=JDBCUtil.getConnection(); String sql="select * from student where name= \'"+student.getName()+"\'"; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { Student stu=new Student(); int id = rs.getInt("id"); String username = rs.getString("name"); String school = rs.getString("school"); String score = rs.getString("score"); stu.setId(id); stu.setName(username); stu.setSchool(school); stu.setScore(score); list.add(stu); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtil.close(ps, rs, conn); } return list; } public Student getStuInfoById(String id) { PreparedStatement ps=null; ResultSet rs =null; Student stu=null; List<Student> list=new ArrayList<Student>(); Connection conn=JDBCUtil.getConnection(); String sql="select * from student where id = ?"; try { ps = conn.prepareStatement(sql); ps.setInt(1, Integer.parseInt(id)); rs = ps.executeQuery(); while (rs.next()) { stu=new Student(); String username = rs.getString("name"); String school = rs.getString("school"); String score = rs.getString("score"); stu.setId(Integer.parseInt(id)); stu.setName(username); stu.setSchool(school); stu.setScore(score); list.add(stu); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtil.close(ps, rs, conn); } return stu; } public int getTotalRecord() { PreparedStatement ps=null; ResultSet rs =null; Connection conn=JDBCUtil.getConnection(); String sql="select count(*) as total from student "; int total=0; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()) { total= rs.getInt("total"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtil.close(ps, rs, conn); } return total; } public List<Student> getLimitStuList(int index, int pageSize) { PreparedStatement ps=null; ResultSet rs =null; Connection conn=JDBCUtil.getConnection(); String sql="select * from student limit ? , ?"; List<Student> list= new ArrayList<Student>(); try { ps = conn.prepareStatement(sql); ps.setInt(1, index); ps.setInt(2, pageSize); rs = ps.executeQuery(); while (rs.next()) { int id=rs.getInt("id"); String name = rs.getString("name"); String school = rs.getString("school"); String score = rs.getString("score"); list.add(new Student(id,name,school,score)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { JDBCUtil.close(ps, rs, conn); } return list; } }
/class StudentService
package com.neusoft.service; import java.util.List; import com.neusoft.bean.Page; import com.neusoft.bean.Student; import com.neusoft.dao.StudentDao; public class StudentService { private StudentDao stuDao=new StudentDao(); public Page<Student> getStudentList(int pageNo, int pageSize){ //第一步:查询当前表的所有记录数 int totalRecord= stuDao.getTotalRecord(); //第二步:创建page对象 Page<Student> page = new Page<Student>(totalRecord,pageNo,pageSize); //第三步:查询分页列表数据并设置到page对象中! List<Student> list = stuDao.getLimitStuList(page.getIndex(),page.getPageSize()); page.setData(list); return page; } public List<Student> getStudent(Student student){ return stuDao.getStudent(student); } public Student getStuInfoById(String id) { // TODO Auto-generated method stub return stuDao.getStuInfoById(id); } public int Add(Student student){ return stuDao.add(student); } public int Update(Student student){ return stuDao.update(student); } }
/class BaseServlet
package com.neusoft.servlet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class BaseServlet */ @WebServlet("/BaseServlet") public class BaseServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected static int pageSize=1; protected static int pageNo=1; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf8"); try { pageNo =Integer.parseInt(request.getParameter("pageNo")); } catch (Exception e) { e.getMessage(); } //获取用户传递的请求参数 String methodName = request.getParameter("method"); //通过方法名获取到方法的对象 //获取当前类的Class对象 Class<? extends BaseServlet> cla = this.getClass(); //获取cla的的方法(Method对象) //getDeclaredMethod需要两个参数,方法名和参数名 //因为在java需要通过方法名和参数列表来确定一个方法 try { //获取方法对象 Method method = cla.getDeclaredMethod(methodName, HttpServletRequest.class , HttpServletResponse.class); //设置方法的访问权限 method.setAccessible(true); //调用方法 //invoke用于调用一个方法,第一个参数时要调用方法的对象,剩下是调用方法需要的参数 method.invoke(this, request , response); }catch (InvocationTargetException e) { System.out.println("此处接收被调用方法内部未被捕获的异常"); e.getMessage(); }catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf8"); doGet(request, response); } }
/class StudentServlet
package com.neusoft.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.neusoft.bean.Page; import com.neusoft.bean.Student; import com.neusoft.dao.StudentDao; import com.neusoft.service.StudentService; import com.neusoft.utils.WEBUtils; @WebServlet("/StudentServlet") public class StudentServlet extends BaseServlet { private static final long serialVersionUID = 1L; private StudentService stuService=new StudentService(); protected void getStuList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String url = WEBUtils.getPath(request); Page<Student> page = stuService.getStudentList(pageNo,pageSize); page.setPath(url); request.setAttribute("page",page); request.getRequestDispatcher("/WEB-INF/view/main.jsp").forward(request, response); } protected void toUpdatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Student stu= stuService.getStuInfoById(id); if (stu != null) { request.setAttribute("stu",stu); request.getRequestDispatcher("/WEB-INF/view/update.jsp").forward(request, response); } } protected void Delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ids = request.getParameter("id"); int id=Integer.parseInt(ids); StudentDao.delete(id); getStuList(request, response); //request.getRequestDispatcher("/WEB-INF/view/main.jsp").forward(request, response); } protected void Update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf8"); String name = request.getParameter("name"); String school = request.getParameter("school"); String score = request.getParameter("score"); int id=Integer.parseInt(request.getParameter("id")); Student student=new Student(); student.setName(name); student.setSchool(school); student.setScore(score); student.setId(id); System.out.println(name); stuService.Update(student); // response.sendRedirect("/Regist-success.html");//重定向 getStuList(request, response); } protected void Add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf8"); String name = request.getParameter("name"); String school = request.getParameter("school"); String score = request.getParameter("score"); Student student=new Student(); student.setName(name); student.setSchool(school); student.setScore(score); List<Student> student2 = stuService.getStudent(student); System.out.println(student2.toString()); if (student2.isEmpty()) { stuService.Add(student); getStuList(request, response); }else { // response.sendRedirect("/Regist-success.html");//重定向 request.getRequestDispatcher("/WEB-INF/view/insert-error.jsp").forward(request, response);//转发 } } }
/class TOInsert
package com.neusoft.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class TOInsert */ @WebServlet("/TOInsert") public class TOInsert extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getRequestDispatcher("/WEB-INF/view/insert.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); request.setCharacterEncoding("utf8"); } }
/ class JDBCUtil
package com.neusoft.utils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtil { private static String driver="com.mysql.jdbc.Driver"; private static String url="jdbc:mysql://localhost:3306/demo"; private static String username="root"; private static String password="123456"; static{ try {//加载驱动 Class.forName(driver); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection(){//创建连接 try { return DriverManager.getConnection(url, username, password); } catch (SQLException e) { // TODO Auto-generated catch block return null; } } public static void close(Statement st,ResultSet rs,Connection conn){//全部关闭 if (conn !=null) { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (rs !=null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (st !=null) { try { st.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void close(Connection conn){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(PreparedStatement ps){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(ResultSet rs){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //封装函数,直接传参使用 public static int executeUpdate(String sql,Object... papram) { // TODO Auto-generated method stub Connection conn =getConnection(); int result=0; try { PreparedStatement pst = conn.prepareStatement(sql); if (papram!=null) { for (int i = 0; i < papram.length; i++) { pst.setObject(i+1, papram[i]); } } result =pst.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { close(conn); } return result; } }
/class WEBUtils
package com.neusoft.utils; import javax.servlet.http.HttpServletRequest; public class WEBUtils { public static String getPath(HttpServletRequest request){ String requestURI = request.getRequestURI(); String queryString = request.getQueryString(); String url = requestURI+"?"+queryString; if(url.contains("&pageNo")){ url = url.substring(0, url.indexOf("&pageNo")); } if(url.contains("Update")){ url = url.replace("Update", "getStuList"); } if(url.contains("Add")){ url = url.replace("Add", "getStuList"); } if(url.contains("Delete")){ url = url.replace("Delete", "getStuList"); } return url; } }
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="${pageContext.request.contextPath}/StudentServlet?method=getStuList&pageNo=1">go!</a> </body> </html>
main.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script> </head> <body> <table border="1" align="center" width="50%"> <tr> <th>姓名</th> <th>学校</th> <th>成绩</th> <th colspan="2">操作</th> </tr> <c:forEach items="${page.data}" var="stu"> <tr> <td>${stu.name}</td> <td>${stu.school}</td> <td>${stu.score}</td> <td> <a href="${pageContext.request.contextPath}/StudentServlet?method=toUpdatePage&id=${stu.id}">修改</a></td><!-- TOUpdate?id=${ stu.id}&name=${stu.name}&school=${stu.school}&score=${stu.score}之前用的方法 --> <td> <a href="${pageContext.request.contextPath}/StudentServlet?method=Delete&id=${stu.id}">删除</a></td> </tr> </c:forEach> <tr><td colspan="3" align="center"><a href="/Student-Sql/TOInsert">添加</a></td></tr> </table> <br> <%@ include file="/WEB-INF/view/paging.jsp" %> </body> </html>
insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${pageContext.request.contextPath}/StudentServlet?method=Add" method="post"> 姓名:<input type="text" name="name"/><br> 学校:<input type="text" name="school"/><br> 分数:<input type="text" name="score"/><br> <input type="submit" value="添加信息"/> </form> </body> </html>
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <%-- <table border="1" align="center" width="50%" > <tr> <th>原信息</th> <th>新信息</th> </tr> <c:forEach items="${student2}" var="stu"> <form action="/Student-Sql/UpdateServlet?id=${stu.id}" method="post"> <tr> <td>${stu.id}</td> <td>ID:${stu.id}</td> </tr> </c:forEach> <c:forEach items="${student2}" var="stu"> <tr> <td>${stu.name}</td> <td>姓名:<input type="text" name="name"/></td> </tr> </c:forEach> <c:forEach items="${student2}" var="stu"> <tr> <td>${stu.school}</td> <td>学校:<input type="text" name="school"/></td> </tr> </c:forEach> <c:forEach items="${student2}" var="stu"> <tr> <td>${stu.score}</td> <td>分数:<input type="text" name="score"/></td> </tr> <tr><td> </td> <td><input type="submit" value="修改信息 "></td></tr> </c:forEach> </form> </table> --%> <form action="${pageContext.request.contextPath}/StudentServlet?method=Update&id=${stu.id}" method="post" > <%-- <input type="hidden" name="id" value="${stu.id}"/> --%> 姓名:<input type="text" name="name" value="${stu.name}"/> 学校:<input type="text" name="school" value="${stu.school}"/> 分数:<input type="text" name="score" value="${stu.score}"/> <input type="submit" value="修改信息 "> </form> </body> </html>
paging.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div id="page_nav" align="center"> <a href="${page.path}&pageNo=1">首页</a> <a href="${page.path}&pageNo=${page.pageNumber -1 }">上一页</a> <c:choose> <c:when test="${page.totalPage <= 5 }" > <c:set var="begin" value="1"></c:set> <c:set var="end" value="${page.totalPage}"></c:set> </c:when> <c:when test="${page.pageNumber <= 3 }"> <c:set var="begin" value="1"></c:set> <c:set var="end" value="5"></c:set> </c:when> <c:otherwise> <c:set var="begin" value="${page.pageNumber-2}"></c:set> <c:set var="end" value="${page.pageNumber+2}"></c:set> <c:if test="${end > page.totalPage }"> <c:set var="begin" value="${page.totalPage-4}"></c:set> <c:set var="end" value="${page.totalPage}"></c:set> </c:if> </c:otherwise> </c:choose> <c:forEach begin="${begin }" end="${end}" var="num"> <c:if test="${page.pageNumber == num }"> 【${num}】 </c:if> <c:if test="${page.pageNumber != num }"> <a href="${page.path}&pageNo=${num}">${num }</a> </c:if> </c:forEach> <a href="${page.path}&pageNo=${page.pageNumber +1}">下一页</a> <a href="${page.path}&pageNo=${page.totalPage}">末页</a> 共${page.totalPage }页,${page.totalRecord }条记录到,去第<input value="${page.totalPage }" name = "pn" id ="pn_input"/>页 <input type="button" value="确定" id="btn_id"/> <script type="text/javascript"> $("#btn_id").click(function(){ var value= $("#pn_input").val(); window.location="${page.path}&pageNo="+value; }); </script> </div>
最后。。导包
以上是关于thinkphp加iview-admin的前后端分离项目,请问thinkphp如何调试后端自己写的接口?的主要内容,如果未能解决你的问题,请参考以下文章