myEclipse,web项目连接数据库
Posted 夏沫浅语
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了myEclipse,web项目连接数据库相关的知识,希望对你有一定的参考价值。
下面的结构图
1.在src你创建com.hqyj.wj.model建立model包,model里放数据库的元素,User.java的截图
package com.hqyj.wj.model; //用户信息表 public class User { private int id; private String name; private String birthday; 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 getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } }
2.在src你创建com.hqyj.wj.dao.inf建立包,这个包是放接口类,这是UserDaoInf的截图
package com.hqyj.wj.dao.inf; import java.util.List; import com.hqyj.wj.model.User; /** * 数据访问层的接口定义数据接口的方法 * */ public interface UserDaoInf { //定义一个查询方法 List<User> search(); }
3.在src你创建com.hqyj.wj.dao建立包,这个包连接数据库,及实现上面的接口类
package com.hqyj.wj.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import com.hqyj.wj.dao.inf.UserDaoInf; import com.hqyj.wj.model.User; /** * * @author wl 数据访问接口 */ public class UserDao implements UserDaoInf { // 数据访问数据库的连接对象 protected Connection con = null; //预编译你写的sql语句 protected PreparedStatement ps=null; //查询预编译的sql语句 protected ResultSet rs=null; // 获取数据库链接 @SuppressWarnings("finally") public Connection getCon() { try { // 加载mysql驱动 Class.forName("com.mysql.jdbc.Driver"); //获取数据库链接 con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/image?characterEncoding=utf8", "root", "root"); System.out.println("链接成功"); return con; } catch (Exception e) { System.out.println("链接失败"+e.getMessage()); return null; // } finally { // try { // con.close(); // } catch (SQLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // return null; // } // } } /** * 查询方法 */ public List<User> search() { List<User> list=new ArrayList<User>(); try { //定义一个sql语句 //String sql="SELECT a.id as 序号,a.salary as \'薪水\',b.`name` as \'姓名\' from salary a LEFT JOIN `user` b on a.u_id=b.id"; String sql="SELECT * from user"; //获取数据库连接 con=getCon(); //预编译sql语句 ps=con.prepareStatement(sql); //把编译出来的结果集装载到ResultSet对象里面 rs=ps.executeQuery(); // rs=statement.executeQuery(sql); //取出ResultSet里的结果集装载到数据模型里 while(rs.next()){ User user=new User(); user.setName(rs.getString("name")); user.setBirthday(rs.getString("birthday")); user.setId(Integer.parseInt(rs.getString("id"))); list.add(user); } } catch (Exception e) { System.out.println("查询错误"+e.getMessage()); }finally{ try { rs.close(); ps.close(); con.close(); } catch (Exception e2) { e2.printStackTrace(); } } return list; } }
5.要引入数据库包mysql-connector-java-commercial-5.1.25-bin.jar,和json-lib-2.2.3-jdk15.jar在项目名字上右键->properties->java Build Path->Libraries->Add External Jars然后选择你下载的包
6.在src下面创建测试类
import java.util.List; import com.hqyj.wj.dao.UserDao; import com.hqyj.wj.model.User; public class Test { /** * @param args */ public static void main(String[] args) { //获取数据库访问类对象 UserDao dao=new UserDao(); dao.getCon(); List<User> list=dao.search(); for(int i=0;i<list.size();i++){ System.out.println("id=="+list.get(i).getId()); System.out.println("name=="+list.get(i).getName()); System.out.println("birthday=="+list.get(i).getBirthday()); } } }
7.成功显示
8.src创建服务类和接口,UserServiceInf和UserService
package com.hqyj.wj.service.inf; import java.util.List; import com.hqyj.wj.model.User; public interface UserServiceInf { List<User> search(); }
package com.hqyj.wj.service; import java.util.List; import com.hqyj.wj.dao.UserDao; import com.hqyj.wj.dao.inf.UserDaoInf; import com.hqyj.wj.model.User; import com.hqyj.wj.service.inf.UserServiceInf; /** *逻辑服务层实现类 */ public class UserService implements UserServiceInf{ UserDaoInf us=new UserDao(); public List<User> search() { return us.search(); } }
9.src创建控制层 ,下新建个服务
package com.hqyj.wj.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import com.hqyj.wj.service.*; import com.hqyj.wj.service.inf.*; import com.hqyj.wj.model.*; import java.util.List; import java.util.ArrayList; public class OneServlet extends HttpServlet { public OneServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } //doget对应的是ajax的$.get()方法 //request是装载请求数据 //response响应数据到前端对象 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决中文乱码的问题 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //在服务器端设置允许在其他域名下访问,及响应类型、响应头设置 System.out.println("这是"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods","POST"); response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type"); //响应的文本格式 response.setContentType("text/html"); //获取响应的输出对象 PrintWriter out = response.getWriter(); // out.print("nissssss"); // out.print("您好呀"); //创建服务器层实现类 UserServiceInf service=new UserService(); List<User> list=service.search(); //把list数据解析成前端页面能读取的数据 JSONArray json=JSONArray.fromObject(list); out.print(json.toString()); out.flush(); out.close(); } //doget对应的是ajax的$.post()方法 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \\"-//W3C//DTD HTML 4.01 Transitional//EN\\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } public void init() throws ServletException { // Put your code here } }
10.新建一个html,获取数据库数据
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajax获取集合</title> <script src="../js/jquery-3.1.1.min.js"></script> </head> <body> <table> <thead> <tr><th>id</th> <th>姓名</th> <th>生日</th></tr> </thead> <tbody> </tbody> </table> <script> $(function(){ $.get("http://localhost:8080/jquery/servlet/OneServlet",function(data){ var num=eval(data); var str; // for(var o in num){ // console.log(num[o].name); // str+=" <tr> <td>"+num[o].id+"</td> <td>"+num[o].name+"</td> <td>"+num[o].birthday+"</td></tr>"; // $("tbody").html(str) // } for(var i=0;i<num.length;i++){ str+=" <tr> <td>"+num[i].id+"</td> <td>"+num[i].name+"</td> <td>"+num[i].birthday+"</td></tr>"; } $("tbody").html(str) }) }) </script> </body> </html>
11.就可以运行成功了,我最开始运行失败了,把tomcat7换为tomcat6就正确了
以上是关于myEclipse,web项目连接数据库的主要内容,如果未能解决你的问题,请参考以下文章