MyEclipse------制作通讯录

时间:2023-11-28 22:46:50

addinfo.java

public class addinfo extends HttpServlet {
private String url="jdbc:mysql://localhost:3306/student?useSSL=true";
private String useName="root";
private String password="2277092";
private Connection conn=null;
private PreparedStatement pstmt=null;
private Statement stmt=null;
private ResultSet rs=null;
private String sql=null; private static final long serialVersionUID = 1L; public addinfo() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} //建立数据库的连接
public void setConn(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,useName,password);
}
catch(Exception e){
e.printStackTrace();
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { setConn(); request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312"); //int no=Integer.parseInt(request.getParameter("no"));
String no=request.getParameter("no");
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String sex=request.getParameter("sex");
String address=request.getParameter("address");
//System.out.print(name+phone+sex+address);
if(no.equals("")||name.equals("")||phone.equals("")||sex.equals("")||address.equals("")){
request.setAttribute("tips", "信息不能为空");
RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/add.jsp");
dispatcher.forward(request, response);
} try {
//判断学号是否已经存在
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from info;");
while(rs.next()){
int num=rs.getInt(1);
if(no.equals(num)){
//System.out.print("该学号已经存在");
request.setAttribute("tips", "该学号已经存在");
RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/add.jsp");
dispatcher.forward(request, response);
}
} sql="insert into info values(?,?,?,?,?)";
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, no);
pstmt.setString(2, name);
pstmt.setString(3, phone);
pstmt.setString(4, sex);
pstmt.setString(5, address);
pstmt.executeUpdate(); rs.close();
stmt.close();
pstmt.close();
if(conn!=null){
conn.close();
//System.out.print("数据库关闭成功");
} //跳转回首页
RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/list.jsp");
dispatcher.forward(request, response); } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.print("出错le");
}
} public void init() throws ServletException {
// Put your code here
} }

deleteinfo.java

public class deleteinfo extends HttpServlet {
private static final long serialVersionUID = 1L;
private String url="jdbc:mysql://localhost:3306/student?useSSL=true";
private String useName="root";
private String password="2277092";
private String sql="";
private Connection conn=null;
private Statement stmt=null,stmt2=null;
private ResultSet rs=null; public deleteinfo() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doPost(request,response);
} //连接数据库
private void setConn(){
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,useName,password);
//System.out.print("数据库连接成功,加载驱动类成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
setConn(); request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312"); String no=request.getParameter("no"); sql="select * from info;";
try {
stmt=conn.createStatement();
stmt2=conn.createStatement();
rs=stmt.executeQuery(sql); //执行完后rs会关闭,所以要用stmt2,即使也能运行,但会抛出异常
while(rs.next()){
String num=rs.getString(1);
if(no.equals(num)){
stmt2.execute("delete from info where no="+no+";");
RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/list.jsp");
dispatcher.forward(request, response);
}
}
rs.close();
stmt.close();
stmt2.close();
} catch (SQLException e) {
e.printStackTrace();
} try{
conn.close();
//System.out.print("成功关闭数据库");
}
catch(SQLException e){
e.printStackTrace();
} } public void init() throws ServletException {
// Put your code here
} }

downfile.java

public class downfile extends HttpServlet {
private static final long serialVersionUID = 1L; public downfile() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } @Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
super.service(request, response);
String path="E:\\Tomcat\\webapps\\MyWeb\\myfile\\"; //文件读取路径
response.reset(); //清除缓冲区中的任何数据存在的状态码和标题
try {
String str = request.getParameter("name");
//第一个参数为要解码的字节字符,第二个参数为解码方法
//getBytes()里面的参数为str原来的编码方式
//str = new String(str.getBytes("UTF-8"), "UTF-8"); //path = path.substring(0, path.lastIndexOf("\\"));
//path = path + "\\myfile\\"; //第一个参数为路径,第二个参数文件名
File fileLoad = new File(path, str);
response.reset(); //输出流
OutputStream o = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(o); //增强写入文件的能力 //输出文件用的字节数组,每次发送500个字节到输出流
//在内存开辟内存空间,最大一次读取500字节
byte b[] = new byte[500]; //客户端使用保存文件的对话框
response.setHeader(
"Content-disposition", //指定文件的类型是文件的扩展名
"attachment;filename=" //指定文件的名字
+ new String(str.getBytes("UTF-8"), "UTF-8"));
//通知客户文件的MIMIE类型
response.setContentType("application/x-tar");
long fileLength = fileLoad.length();
String length = String.valueOf(fileLength);
response.setHeader("Content_length", length); //文件字节流读取文件
FileInputStream in = new FileInputStream(fileLoad);
int n = 0;
while ((n = in.read(b)) != -1) { //in.read(b),返回读到的字节数,没有时返回-1
//write(data,offset,length)
bos.write(b, 0, n);
//System.out.print(n);
}
in.close();
bos.close();
} catch (Exception e) {
System.out.print(e);
} } public void init() throws ServletException {
// Put your code here
} }

split.java

public class split {
private Connection conn=null;
private Statement stmt=null;
private ResultSet rs=null;
private ResultSetMetaData rsmd=null; private String url="jdbc:mysql://localhost:3306/student?useSSL=true";
private String useName="root";
private String password="2277092";
private String sqlStr; //SQL查询语句
private int rowCount=0; //总记录数目
private int pageCount=0; //所分的逻辑页数
private int pageSize=0; //每页显示的记录数 public void setCon(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,useName,password);
//System.out.print("加载驱动类和数据库连接成功");
}
catch(Exception e){
e.printStackTrace();
}
} //初始化,第三个参数表示目前所显示的是第几页
public void initialize(String sqlStr,int pageSize,int ipage){
this.sqlStr=sqlStr;
this.pageSize=pageSize; //检索开始位置=每页显示的记录数*(所在的页数-1)
//实际是从第irows+1条记录开始检索
int irows=pageSize*(ipage-1); try{
//第一次执行SQL语句,获取所有数据库表所有信息
stmt=this.conn.createStatement();
rs=stmt.executeQuery(this.sqlStr); //执行SQL语句,获取MySQL里面的数据
if(rs!=null){
rs.last(); //将游标指向最后一行
this.rowCount=rs.getRow();//获取当前记录所在的行数,即记录总数
//rs.first();
//页数总数=(总记录数目-1)/每页显示的记录数+1
this.pageCount=(this.rowCount-1)/this.pageSize+1;
} //第二次执行SQL语句,对数据库信息进行检索
this.sqlStr=sqlStr+" limit "+irows+","+pageSize+";"; //检索pageSize条数据
stmt=this.conn.createStatement();
rs=stmt.executeQuery(this.sqlStr);
this.rsmd=rs.getMetaData(); //获取数据库中ColumnName的信息
//System.out.print(rsmd); }
catch(SQLException e){
System.out.print(e.toString());
}
} //将显示的结果保存到集合类中
public Vector<Object[]> getPage(){
Vector<Object[]> vData=new Vector<Object[]>();
try{
if(rs!=null){
while(rs.next()){
String[] sData=new String[5];//5表示一行中属性种类的个数
for(int j=0;j<rsmd.getColumnCount();j++){//获取一行中有几种属性的数目
sData[j]=rs.getString(j+1);
}
//System.out.print(rsmd.getColumnCount());
vData.addElement(sData);
}
}
rs.close();
stmt.close();
}
catch(SQLException e){
System.out.print(e.toString());
}
return vData;
} //获取页面总数
public int getPageCount(){
return this.pageCount;
} //获取数据表中记录总数
public int getRowCount(){
return this.rowCount;
} //关闭数据库连接
public void closeConn(){
if(conn!=null){
try {
conn.close();
//System.out.print("成功关闭数据库连接");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

updateinfo.java

public class updateinfo extends HttpServlet {
private static final long serialVersionUID = 1L;
private String url="jdbc:mysql://localhost:3306/student?useSSL=true";
private String useName="root";
private String password="2277092";
private String sql="";
private Connection conn=null;
private Statement stmt=null;
private ResultSet rs=null; public updateinfo() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} //连接数据库
private void setConn(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,useName,password);
}
catch(ClassNotFoundException e){
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
setConn(); request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312");
String id=request.getParameter("id");
//System.out.print(id); try {
sql="select * from info;";
stmt=conn.createStatement();
rs=stmt.executeQuery(sql); while(rs.next()){
String no=rs.getString(1);
String name=rs.getString(2);
String phone=rs.getString(3);
String sex=rs.getString(4);
String address=rs.getString(5);
try{
if(id.equals(no)){
request.setAttribute("no", no);
request.setAttribute("name", name);
request.setAttribute("phone", phone);
request.setAttribute("sex", sex);
request.setAttribute("address", address); RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/update.jsp");
dispatcher.forward(request, response);
}
}
catch(Exception e){
e.printStackTrace();
}
}
rs.close();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try{
if(conn!=null){
conn.close();
//System.out.print("关闭数据库成功");
}
}
catch(SQLException e){
e.printStackTrace();
}
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
setConn(); request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312"); String no=request.getParameter("no");
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String sex=request.getParameter("sex");
String address=request.getParameter("address");
//System.out.print(sex); try{
sql="update info set name='"+name+"',phone='"+phone+"',sex='"+sex+"',address='"+address+"' where no="+no+";";
stmt=conn.createStatement(); stmt.executeUpdate(sql);
stmt.close();
conn.close(); RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/list.jsp");
dispatcher.forward(request, response);
}
catch(SQLException e){
e.printStackTrace();
}
} public void init() throws ServletException {
// Put your code here
} }

upfile.java

public class upfile extends HttpServlet {
private static final long serialVersionUID = 1L; public upfile() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("gb2312");
response.setContentType("text/html;charset=gb2312"); SmartUpload up=new SmartUpload(); try{
/*
第一个参数是传递一个Servlet,在servlet中传递this就可以了;
第二个和第三个参数是request与response不多说明了;
第四个参数是发生错误后的url路径地址,如果没有可以键入null;
第五个参数是是否需要session,这里可以写入true;
第六个参数是缓存大小,我们用了8*1024;
第七个蚕食是是否需要刷新,键入ture;*/
PageContext context = JspFactory.getDefaultFactory().getPageContext(this, request, response, null, true, 8*1024, true);
up.initialize(context);
up.setTotalMaxFileSize(5*1024*1024); //上传的总文件大小不能超过这个
up.upload(); //获取文件名
//String fn=up.getFiles().getFile(0).getFieldName(); String path="E:\\Tomcat\\webapps\\MyWeb\\myfile";
//java.io.File d=new java.io.File(path);
File d=new File(path);
if(!d.exists()){
d.mkdirs();
}
up.save(path);
//System.out.print(fn);
//System.out.print("文件上传成功啦!!!");
RequestDispatcher dispatcher=request.getRequestDispatcher("/splitpage2/list.jsp");
dispatcher.forward(request, response);
}
catch(Exception e){
e.printStackTrace();
} } public void init() throws ServletException {
// Put your code here
} }

add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%request.setCharacterEncoding("gb2312"); %>
<%response.setContentType("text/html;charset=gb2312"); %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>添加/删除信息</title>
<style type="text/css">
.bg{
background:url(image/3.jpeg);
}
</style>
</head> <body class="bg">
<center>
<h1>添加与删除信息</h1><hr><br>
<form action="servlet/addinfo" method="post">
<table border="1" cellspacing="0" cellpadding="3">
<tr align="right">
<td>学号:</td>
<td><input type="text" name="no" size="30" ></td>
</tr>
<tr align="right">
<td>姓名:</td>
<td><input type="text" name="name" size="30"></td>
</tr>
<tr align="right">
<td>联系方式:</td>
<td><input type="text" name="phone" size="30"></td>
</tr>
<tr align="right">
<td>性别:</td>
<td align="left">
<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女
</td>
</tr>
<tr align="right">
<td>地址:</td>
<td><input type="text" name="address" size="30"></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="提交">&nbsp;
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
提示:<input type="text" name="tips" value="<%=request.getAttribute("tips") %>" readonly>
<a href="splitpage2/list.jsp">返回主页</a>
</center> <br><br><br>
<center>
<form action="servlet/deleteinfo" method="post">
请输入要删除的学号:
<input type="text" name="no">
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</center> </body>
</html>

downfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@ page import="java.io.*" %>
<%request.setCharacterEncoding("gb2312"); %>
<%response.setContentType("text/html;charset=gb2312"); %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>文件下载站</title>
<style type="text/css">
.bg{
background:url(image/3.jpeg);
}
.textS{
font-size:25px;
}
a:hover{
color:red;
}
</style>
</head> <body class="bg">
<center>
<font color="#00008b" size="6" >文件下载站</font><br><br>
<table>
<%
path="E:\\Tomcat\\webapps\\MyWeb";
File file=new File(path,"\\myfile");
String str[]=file.list();
for(int i=0;i<str.length;i++){
String s=str[i];
out.print("<tr class='textS'><td>"+s+"</td><td><a href='servlet/downfile?name="+s+"'>下载</a></td></tr>");
}
%>
</table>
<br><br> <form action="servlet/upfile" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="20"/><br>
<input type="submit" value="上传"/>
</form> <br>
<a href="splitpage2/list.jsp">返回主页</a>
</center>
</body>
</html>

list.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@page import="java.sql.*" %>
<%@page import="java.io.*" %>
<%@page import="com.*" %>
<jsp:useBean id="pages" scope="page" class="com.split"/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>蓝霸学院名册</title>
<style type="text/css">
.tablebg{
width:440px;
height:247px;
background-color:rgba(255,255,255,0.3);
}
.bg{
background:url(image/3.jpeg);
}
.left-message{
float:left;
margin-top:10px;
}
.left-message-margin{
margin-top:10px;
margin-left:15px;
}
.left-message-bg{
width:120px;
height:260px;
padding-left:10px;
padding-top:10px;
background-color:rgba(224,224,224,0.3) ;
}
a{
text-decoration:none;
}
a:hover{
text-decoration:underline;
color:red;
}
</style>
</head> <body class="bg">
<br>
<!-- 标题 -->
<center><div align="center"><h1>学员信息一览</h1></div><br></center> <!-- 友情提示 -->
<div class="left-message left-message-bg">
<font size="5px">友情提示:</font><br>
<div class="left-message-margin"><a href="splitpage2/list.jsp">查看信息</a><br></div>
<div class="left-message-margin"><a href="splitpage2/add.jsp">添加信息</a><br></div>
<div class="left-message-margin"><a href="splitpage2/add.jsp">删除信息</a><br></div>
<div class="left-message-margin"><a href="splitpage2/update.jsp">修改信息</a></div>
<div class="left-message-margin"><a href="splitpage2/downfile.jsp">资料上传</a></div>
<div class="left-message-margin"><a href="splitpage2/downfile.jsp">资料下载</a></div>
<div class="left-message-margin"><a href="">联系客服</a></div>
<div class="left-message-margin"><a href="">关于我们</a></div>
</div> <%!
String sqlStr="";
int pageSize=5; //每页显示的记录数
int showPage=1; //当前页
%> <%
//连接数据库
pages.setCon(); //这里后面不能加";"号,因为后面还有limit 0,2;
sqlStr="select * from info order by no";
String strPage=null;
strPage=request.getParameter("showPage");//获取目前显示的页数
if(strPage==null){
showPage=1;
}
else{
try{
showPage=Integer.parseInt(strPage);
}
catch(NumberFormatException e){
System.out.print(e.toString());
showPage=1;
}
if(showPage<1){
showPage=1;
}
} pages.initialize(sqlStr, pageSize, showPage);
Vector<Object[]> vData=pages.getPage();
%> <div align="center" ><br>
<div class="tablebg">
<!-- 表格区 -->
<table border="1" cellspacing="1" cellpadding="10" >
<tr align="center">
<td>学号</td>
<td>姓名</td>
<td>联系方式</td>
<td>性别</td>
<td>地址</td>
</tr>
<%
for(int i=0;i<vData.size();i++){
String[] sData=(String[])vData.get(i); //显示数据
%>
<tr align="center">
<td width="50"><%=sData[0] %></td>
<td width="80"><%=sData[1] %></td>
<td width="150"><%=sData[2] %></td>
<td width="50"><%=sData[3] %></td>
<td width="100"><%=sData[4] %></td>
</tr>
<%
}
%>
</table>
</div>
<br>
<br>
<br>
<!-- 分页区 -->
<form action="splitpage2/list.jsp" method="get" target="_self">
共<%=pages.getRowCount() %>条&nbsp;
<%=pageSize %>条/页&nbsp;
第<%=showPage %>页/共<%=pages.getPageCount() %>页&nbsp;
<a href="splitpage2/list.jsp?showPage=1" target="_self">[首页]</a>&nbsp; <!-- 上一页 -->
<%
if(showPage>1){
%>
<a href="splitpage2/list.jsp?showPage=<%=showPage-1%>" target="_self">[上一页]</a>
<%
}
else{
%>
[上一页]&nbsp;
<%
}
%> <!-- 下一页 -->
<%
if(showPage<pages.getPageCount()){
%>
<a href="splitpage2/list.jsp?showPage=<%=showPage+1 %>" target="_self">[下一页]</a>
<%
}
else{
%>
[下一页]&nbsp;
<%
}
%> <a href="splitpage2/list.jsp?showPage=<%=pages.getPageCount()%>">[尾页]</a>&nbsp; <!-- 转到第n页 -->
转到
<select name="showPage">
<%
for(int i=1;i<=pages.getPageCount();i++){
%>
<option value="<%=i%>"
<%
if(showPage==i)
out.print("selected");
%>>
<%=i %>
</option>
<%
}
%>
</select>
页&nbsp;
<input type="submit" value="跳转">
</form>
</div>
<%
pages.closeConn();
%>
</body>
</html>

update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%@page import="com.*" %>
<%request.setCharacterEncoding("gb2312"); %>
<%response.setContentType("text/html;charset=gb2312"); %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>修改信息</title>
<style type="text/css">
.bg{
background:url(image/3.jpeg);
}
</style>
</head> <body class="bg">
<center>
<h1>修改学员信息</h1><hr><br>
<form action="servlet/updateinfo" method="get">
输入要修改的学号:
<input type="text" name="id">
<input type="submit" value="查询">
<input type="reset" value="重置">
</form> <form action="servlet/updateinfo" method="post">
<table border="1" cellspacing="0" cellpadding="3">
<tr align="right">
<td>学号:</td>
<td><input type="text" name="no" size="30" value="<%=request.getAttribute("no")%>"></td>
</tr>
<tr align="right">
<td>姓名:</td>
<td><input type="text" name="name" size="30" value="<%=request.getAttribute("name")%>"></td>
</tr>
<tr align="right">
<td>联系方式:</td>
<td><input type="text" name="phone" size="30" value="<%=request.getAttribute("phone")%>"></td>
</tr>
<tr align="right">
<td>性别:</td>
<td><input type="text" name="sex" size="30" value="<%=request.getAttribute("sex")%>"></td>
</tr>
<tr align="right">
<td>地址:</td>
<td><input type="text" name="address" size="30" value="<%=request.getAttribute("address")%>"></td>
</tr>
<tr>
<td></td>
<td align="center">
<input type="submit" value="提交">&nbsp;
</td>
</tr>
</table>
</form> <a href="splitpage2/list.jsp">返回主页</a>
</center>
</body>
</html>