servlet示例四:与数据库交互

来源:互联网 发布:淘宝旅行网机票预订 编辑:程序博客网 时间:2024/05/18 02:24

背景:学生基本信息管理系统中,要求输出学生的基本信息情况。


合理地完成任务需要做到以下三点:

1.创建Students类储存所有的学生信息(我把该类专门放在了adn.entities包内)

2.创建Students_dao类储存所有的工具比如说连接数据库的相关信息等(我把该类专门放在了adn.daos包内)

3.创建AllStuInfo类的servlet将查询的学生的信息显示在网页上(我把该类专门放在了adn.MyServlets包内)

出现的问题:尝试连线已失败

解决:由于我将conn=DriverManager.getConnection(url,"postgres","csy32384");用户名输入错误(少了一个s)导致的

下面就是对这三点代码的具体化:

步骤一:

package adn.entities;


public class Students {
private String sno,sname,sex;
public Students(String sno, String sname, String sex) {
super();
this.sno = sno;
this.sname = sname;
this.sex = sex;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
}


步骤二:

package adn.daos;


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 adn.entities.Students;


public class Students_dao {
public List<Students> getAllStudents(){
List<Students> list=null;
Connection conn=null;
try{
list=new ArrayList<Students>();
Class.forName("org.postgresql.Driver");
String url="jdbc:postgresql://localhost:5432/CSY";
conn=DriverManager.getConnection(url,"postgres","csy32384");
String SQL="select sno,sname,sex from students";
PreparedStatement pr=conn.prepareStatement(SQL);
ResultSet rs=pr.executeQuery();
while(rs.next()){
String sno=rs.getString(1);
String sname=rs.getString(2);
String sex=rs.getString(3);
Students student=new Students(sno,sname,sex);
list.add(student);

}
rs.close();
conn.close();
}
catch(Exception e){
System.out.println("错误1 "+e);
}

return list;
}
}


步骤三:

package adn.MyServlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import adn.daos.Students_dao;
import adn.entities.Students;


@WebServlet("/GetAllStu.do")
public class GetStuInfo extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");

Students_dao sdao=new Students_dao();
List<Students> list=sdao.getAllStudents();

PrintWriter out=response.getWriter();
for(Students s:list){
out.print(s.getSno()+" ");
out.print(s.getSname()+" ");
out.print(s.getSex());
out.print("<br>");
}
}



protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}


}


1 0