标签:
数据用pdf和world显示和保存
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class BaseDao { private static String driver = "com.mysql.jdbc.Driver";// 数据库驱动字符串 private static String url = "jdbc:mysql://localhost/db_myprofile?user=root&password=root";// 连接URL private static String user = "root"; // 数据库用户名 private static String password = "123456"; // 用户密码 /** * 获取数据库连接对象。 */ public static Connection getConnection() { Connection conn = null;// 数据连接对象 // 获取连接并捕获异常 try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace();// 异常处理 } return conn;// 返回连接对象 } /** * 关闭数据库连接。 * * @param conn 数据库连接 * @param stmt Statement 对象 * @param rs 结果集 */ public static void closeAll(Connection conn, Statement stmt, ResultSet rs) { // 若结果集对象不为空,则关闭 if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } // 若Statement 对象不为空,则关闭 if (stmt != null) { try { stmt.close(); } catch (Exception e) { e.printStackTrace(); } } // 若数据库连接对象不为空,则关闭 if (conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } } ========================================== package 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 entity.Profile; public class ProfileDao extends BaseDao{ public List<Profile> getAll(){ Connection connection = getConnection(); //获取数据库连接 PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select * from profile"; List<Profile> profileList = new ArrayList<Profile>(); //个人档案列表 try { pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); // 执行此sql语句 while (rs.next()) { //遍历数据,存入profileList中 Profile profile = new Profile(); profile.setId(rs.getInt("id")); profile.setName(rs.getString("name")); profile.setBirthday(rs.getString("birthday")); profile.setGender(rs.getString("gender")); profile.setCareer(rs.getString("career")); profile.setAddress(rs.getString("address")); profile.setMobile(rs.getString("mobile")); profileList.add(profile); } } catch (SQLException e) { e.printStackTrace(); } finally { closeAll(connection, pstmt, rs); // 关闭此连接 } return profileList; } /* * 更新档案 */ public void updateProfile(Profile profile){ Connection connection = null; PreparedStatement pstmt = null; String sql = "update profile " + "set name=?,birthday=?,gender=?,career=?,address=?,mobile=? where id=" + profile.getId(); try{ connection = BaseDao.getConnection(); // 获得连接 pstmt = connection.prepareStatement(sql); pstmt.setString(1, profile.getName()); //名称 pstmt.setString(2, profile.getBirthday()); //生日 pstmt.setString(3, profile.getGender()); //性别 pstmt.setString(4, profile.getCareer()); //职业 pstmt.setString(5, profile.getAddress()); //地点 pstmt.setString(6, profile.getMobile()); //电话 pstmt.execute(); }catch(SQLException e){ e.printStackTrace(); }finally{ closeAll(connection, pstmt, null); // 关闭此连接 } } /** * 获得指定id的档案 * @param id * @return */ public Profile getProfile(int id){ Connection connection = getConnection(); //获取数据库连接 PreparedStatement pstmt = null; ResultSet rs = null; String sql = "select * from profile where id=" + id; Profile profile = new Profile(); try { pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); // 执行此sql语句 while (rs.next()) { //遍历数据,存入profileList中 profile.setId(rs.getInt("id")); profile.setName(rs.getString("name")); profile.setBirthday(rs.getString("birthday")); profile.setGender(rs.getString("gender")); profile.setCareer(rs.getString("career")); profile.setAddress(rs.getString("address")); profile.setMobile(rs.getString("mobile")); } } catch (SQLException e) { e.printStackTrace(); } finally { closeAll(connection, pstmt, rs); // 关闭此连接 } return profile; } public static void main(String[] args) { ProfileDao p = new ProfileDao(); List<Profile> list =p.getAll(); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).getAddress()); } } } ================================================ package entity; public class Profile { private int id; private String name; //姓名 private String birthday; //生日 private String gender; //性别 private String career; //职业 private String address; //住所 private String mobile; //电话 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; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getCareer() { return career; } public void setCareer(String career) { this.career = career; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public int getId() { return id; } public void setId(int id) { this.id = id; } } =============================================== package servlet; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.ProfileDao; import entity.Profile; import com.lowagie.text.Cell; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.Table; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfWriter; public class DetailServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String type = request.getParameter("type"); String id = request.getParameter("id"); int theId = Integer.parseInt(id); ProfileDao profileDao = new ProfileDao(); Profile profile = profileDao.getProfile(theId); request.setAttribute("profile", profile); RequestDispatcher rd = null; if (type == null || type.equals("")) { //如果是html格式 rd = request.getRequestDispatcher("detail.jsp"); } else if (type.equals("pdf")) { // 如果是pdf格式 String filePath = getServletContext().getRealPath("/") + "/" + "detail.pdf"; generatePdf(profile, filePath); BufferedInputStream bis = null; BufferedOutputStream bos = null; response.setContentType("application/pdf"); try{ bis = new BufferedInputStream(new FileInputStream(filePath)); bos = new BufferedOutputStream(response.getOutputStream()); byte[] buff = new byte[2048]; int bytesRead; while(-1 != (bytesRead = bis.read(buff,0,buff.length))){ bos.write(buff,0,bytesRead); } }catch(Exception e){ e.printStackTrace(); }finally{ if(bis != null) bis.close(); if(bos != null) bos.close(); } return; //request.setAttribute("filePath", filePath); //rd = request.getRequestDispatcher("detail_pdf.jsp"); } else if (type.equals("word")) { // 如果是word格式 rd = request.getRequestDispatcher("detail_doc.jsp"); } rd.forward(request, response); } /** * 生成所需的pdf文件 * @param profile * @param filePath * @throws FileNotFoundException * @throws IOException */ private void generatePdf(Profile profile, String filePath) throws FileNotFoundException, IOException { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream(filePath)); document.addTitle(profile.getName() + "的档案明细"); BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false); Font fontChinese = new Font(bfChinese); document.open(); document.add(new Paragraph(profile.getName() + "档案明细", fontChinese)); // 明细表格 Table table = new Table(2); int width[] = { 50, 50 }; table.setWidths(width); table.setWidth(80); table.setPadding(1); table.setSpacing(1); table.setBorder(1); Cell cell = null; cell = new Cell(new Phrase("编号:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getId() + "", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase("姓名:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getName(), fontChinese)); table.addCell(cell); cell = new Cell(new Phrase("生日:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getBirthday(), fontChinese)); table.addCell(cell); cell = new Cell(new Phrase("性别:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getGender(), fontChinese)); table.addCell(cell); cell = new Cell(new Phrase("职业:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getCareer(), fontChinese)); table.addCell(cell); cell = new Cell(new Phrase("住所:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getAddress(), fontChinese)); table.addCell(cell); cell = new Cell(new Phrase("电话:", fontChinese)); table.addCell(cell); cell = new Cell(new Phrase(profile.getMobile(), fontChinese)); table.addCell(cell); document.add(table); } catch (DocumentException e) { e.printStackTrace(); } document.close(); } } ================================================ package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.ProfileDao; import entity.Profile; public class ExcelServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProfileDao profileDao = new ProfileDao(); List<Profile> list = profileDao.getAll(); request.setAttribute("list", list); RequestDispatcher rd = request.getRequestDispatcher("list_excel.jsp"); rd.forward(request, response); } } =============================================== package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.ProfileDao; import entity.Profile; public class ListServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProfileDao profileDao = new ProfileDao(); List<Profile> list = profileDao.getAll(); System.out.println(list+"asd"); request.setAttribute("list", list); RequestDispatcher rd = request.getRequestDispatcher("list.jsp"); rd.forward(request, response); } } ================================================== package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.ProfileDao; import entity.Profile; public class UpdateServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String error = ""; String id = request.getParameter("id"); if(id == null || id.equals("")){ error = "id为空"; } String name = request.getParameter("name"); if(name== null || name.equals("")){ error = "名称为空"; }else{ name = new String(name.getBytes("iso-8859-1"),"utf-8"); } String birthday = request.getParameter("birthday"); if(birthday == null || birthday.equals("")){ error = "生日为空"; } String gender = request.getParameter("gender"); if(gender == null || gender.equals("")){ error = "性别为空"; }else{ gender = new String(gender.getBytes("iso-8859-1"),"utf-8"); } String career = request.getParameter("career"); if(career == null || career.equals("")){ error = "职业为空"; }else{ career = new String(career.getBytes("iso-8859-1"),"utf-8"); } String address = request.getParameter("address"); if(address == null || address.equals("")){ error = "地址为空"; }else{ address = new String(address.getBytes("iso-8859-1"),"utf-8"); } String mobile = request.getParameter("mobile"); if(mobile == null || mobile.equals("")){ error = "电话为空"; } RequestDispatcher rd = null; if(!error.equals("")){ request.setAttribute("error", error); rd = request.getRequestDispatcher("error.jsp"); return; } int theId = Integer.parseInt(id); ProfileDao profileDao = new ProfileDao(); Profile profile = new Profile(); profile.setId(theId); profile.setName(name); profile.setBirthday(birthday); profile.setGender(gender); profile.setCareer(career); profile.setAddress(address); profile.setMobile(mobile); profileDao.updateProfile(profile); request.setAttribute("profile", profile); List<Profile> list = profileDao.getAll(); request.setAttribute("list", list); rd = request.getRequestDispatcher("list.jsp"); //转向列表页 rd.forward(request, response); } } ===================================================== <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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_2_5.xsd"> <servlet> <servlet-name>list</servlet-name> <servlet-class>servlet.ListServlet</servlet-class> </servlet> <servlet> <servlet-name>detail</servlet-name> <servlet-class>servlet.DetailServlet</servlet-class> </servlet> <servlet> <servlet-name>excel</servlet-name> <servlet-class>servlet.ExcelServlet</servlet-class> </servlet> <servlet> <servlet-name>update</servlet-name> <servlet-class>servlet.UpdateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>list</servlet-name> <url-pattern>/list</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>detail</servlet-name> <url-pattern>/detail</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>excel</servlet-name> <url-pattern>/excel</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>update</servlet-name> <url-pattern>/update</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <login-config> <auth-method>BASIC</auth-method> </login-config> </web-app> =============================================== <%@ page import="entity.Profile" %> <%@ page contentType="text/html;charset=UTF-8" %> <% response.setContentType("application/msword"); Profile profile = (Profile)request.getAttribute("profile"); %> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <title>档案明细</title> </head> <body> <table border = "1"> <tr> <td>编号</td> <td><%=profile.getId() %></td> </tr> <tr> <td>姓名</td> <td><%=profile.getName()%></td> </tr> <tr> <td>生日</td> <td><%=profile.getBirthday() %></td> </tr> <tr> <td>性别</td> <td><%=profile.getGender()%></td> </tr> <tr> <td>职业</td> <td><%=profile.getCareer()%></td> </tr> <tr> <td>住所</td> <td><%=profile.getAddress() %></td> </tr> <tr> <td>电话</td> <td><%=profile.getMobile() %></td> </tr> </table> <br/> </body> </html> =================================================== <%@ page contentType="text/html;charset=UTF-8" %> <%response.setHeader("Pragma","No-cache"); %> <%response.setHeader("Cache-Control","no-cache"); %> <%response.setHeader("Expires","0");%> <%@ page import="entity.Profile" %> <% Profile profile = (Profile)request.getAttribute("profile"); %> <html> <head> <title>档案明细</title> </head> <body> <table border = "1"> <tr> <td>编号</td> <td><%=profile.getId() %></td> </tr> <tr> <td>姓名</td> <td><%=profile.getName() %></td> </tr> <tr> <td>生日</td> <td><%=profile.getBirthday() %></td> </tr> <tr> <td>性别</td> <td><%=profile.getGender() %></td> </tr> <tr> <td>职业</td> <td><%=profile.getCareer() %></td> </tr> <tr> <td>住所</td> <td><%=profile.getAddress() %></td> </tr> <tr> <td>电话</td> <td><%=profile.getMobile() %></td> </tr> </table> <br/> <input type=‘button‘ onclick=‘history.back(-1)‘ value=‘返 回‘/> </body> </html> =================================================== <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!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> <% response.sendRedirect(path+"/list"); %> <body> </body> </html> ============================================= <%@ page language="java" contentType="application/vnd.ms-excel;charset=GBK"%> <%@ page import="java.util.List" %> <%@ page import="entity.Profile" %> <% List<Profile> list = (List<Profile>)request.getAttribute("list"); %> <html> <head> <title>公告列表</title> </head> <body> <table width="80%" border="1"> <tr bgcolor="yellow"> <td width="10%">档案编号</td> <td width="10%">姓名</td> <td width="10%">生日</td> <td width="5%">性别</td> <td width="10%">职业</td> <td width="20%">住所</td> <td width="15%">电话</td> </tr> <% for(int i = 0;i < list.size();i++){ Profile profile = list.get(i); %> <tr> <td width="10%"><%=profile.getId() %></td> <td width="10%"><%=profile.getName() %></td> <td width="10%"><%=profile.getBirthday() %></td> <td width="5%"><%=profile.getGender() %></td> <td width="10%"><%=profile.getCareer() %></td> <td width="20%"><%=profile.getAddress() %></td> <td width="15%"><%=profile.getMobile() %></td> </tr> <%} %> </table> <br/> </body> </html> ================================================== <%@ page contentType="text/html;charset=UTF-8" %> <%response.setHeader("Pragma","No-cache"); %> <%response.setHeader("Cache-Control","no-cache"); %> <%response.setHeader("Expires","0");%> <%@ page import="java.util.List" %> <%@ page import="entity.Profile" %> <% List<Profile> list = (List<Profile>)request.getAttribute("list"); RequestDispatcher rd = request.getRequestDispatcher("/list"); if(list == null){ rd.forward(request,response); } %> <html> <head> <script language=‘Javascript‘> //阅读档案 function doRead(id){ document.location = ‘/MyProfile/detail?id=‘ + id; } //更新档案 function doUpdate(id){ document.location = ‘update.jsp?id=‘ + id; } function pdf(id){ document.location = ‘/MyProfile/detail?type=pdf&id=‘ + id; } function word(id){ document.location = ‘/MyProfile/detail?type=word&id=‘ + id; } </script> <title>档案列表</title> </head> <body onload="window.location.href=/list"> <table width="90%" border="1"> <tr bgcolor="yellow"> <td width="5%">编号</td> <td width="10%">姓名</td> <td width="10%">生日</td> <td width="5%">性别</td> <td width="10%">职业</td> <td width="15%">住所</td> <td width="10%">电话</td> <td width="25%">操作</td> </tr> <% for(int i = 0;i < list.size();i++){ Profile profile = list.get(i); %> <tr> <td width="5%"><%=profile.getId() %></td> <td width="10%"><%=profile.getName() %></td> <td width="10%"><%=profile.getBirthday() %></td> <td width="5%"><%=profile.getGender() %></td> <td width="10%"><%=profile.getCareer() %></td> <td width="15%"><%=profile.getAddress() %></td> <td width="10%"><%=profile.getMobile() %></td> <td width="25%"> <input type=‘button‘ value=‘明细‘ onclick=‘doRead(<%=profile.getId() %>)‘/> <input type=‘button‘ value=‘PDF‘ onclick=‘pdf(<%=profile.getId() %>)‘/> <input type=‘button‘ value=‘WORD‘ onclick=‘word(<%=profile.getId() %>)‘/> <input type=‘button‘ value=‘修改‘ onclick=‘doUpdate(<%=profile.getId() %>)‘/> </td> </tr> <%} %> </table> <br/> </body> </html> ================================================= <%@ page language="java" contentType="text/html;charset=UTF-8" %> <%response.setHeader("Pragma","No-cache"); %> <%response.setHeader("Cache-Control","no-cache"); %> <%response.setHeader("Expires","0");%> <%@ page import="entity.Profile" %> <%@ page import="dao.ProfileDao" %> <% String id = request.getParameter("id"); int theId = Integer.parseInt(id); ProfileDao profileDao = new ProfileDao(); Profile profile = profileDao.getProfile(theId); %> <html> <head> <title>档案明细</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> <script language="Javascript"> function init(){ var g = ‘<%=profile.getGender()%>‘; var gender = document.getElementById(‘gender‘); if(g == ‘男‘){ gender.selectedIndex = 0; }else{ gender.selectedIndex = 1; } } function doSubmit(){ document.getElementById(‘sform‘).submit(); } </script> </head> <body onload=‘init()‘> <form id=‘sform‘ action=‘/MyProfile/update‘/> <input type=‘hidden‘ value=‘<%=profile.getId() %>‘ name=‘id‘/> <table border = "1"> <tr> <td>编号</td> <td><%=profile.getId() %></td> </tr> <tr> <td>姓名</td> <td><input type=‘text‘ value=‘<%=profile.getName() %>‘ name=‘name‘/></td> </tr> <tr> <td>生日</td> <td><input type=‘text‘ value=‘<%=profile.getBirthday() %>‘ name=‘birthday‘/></td> </tr> <tr> <td>性别</td> <td> <select id=‘gender‘ name=‘gender‘/> <option value=‘男‘>男</option> <option value=‘女‘>女</option> </select> </td> </tr> <tr> <td>职业</td> <td><input type=‘text‘ value=‘<%=profile.getCareer() %>‘ name=‘career‘/></td> </tr> <tr> <td>住所</td> <td><input type=‘text‘ value=‘<%=profile.getAddress() %>‘ name=‘address‘/></td> </tr> <tr> <td>电话</td> <td><input type=‘text‘ value=‘<%=profile.getMobile() %>‘ name=‘mobile‘/></td> </tr> </table> <br/> <input type=‘button‘ onclick=‘doSubmit()‘ value=‘修 改‘/> <input type=‘button‘ onclick=‘history.back(-1)‘ value=‘返 回‘/> </form> </body> </html> ================================================== 依赖的架包:iText-2.1.3.jar iTextAsian.jar mysql-connector-java-5.0.6-bin.jar
标签:
原文地址:http://www.cnblogs.com/aicpcode/p/4264966.html