導航:首頁 > 文檔加密 > servlet教程pdf

servlet教程pdf

發布時間:2024-03-29 12:29:20

⑴ 如何在jsp中直接打開本地硬碟上的pdf等文件

jsp中要利用java來實現打開,可以通過瀏覽器打開:
以下程序實現了讀取某個路徑下的pdf文件,並用瀏覽器打開:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PDFServlet extends HttpServlet {
private static final long serialVersionUID = -3065671125866266804L;
public PDFServlet() {
super();
}

public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/pdf");

FileInputStream in = new FileInputStream(new File("d:/1.pdf"));
OutputStream out = response.getOutputStream();
byte[] b = new byte[512];

while ((in.read(b)) != -1) {
out.write(b);
}

out.flush();
in.close();
out.close();
}

public void init() throws ServletException {
}
}

⑵ jsp中怎麼利用java需要將在oracle資料庫中存在的pdf,doc等文件下載下來。最好有代碼

首先你要明確一個概念,資料庫中是不可能存這些文件的,存的最多是這些文件對應的地址,是String類型的數據。
在這基礎上來看這些代碼。注意標注的1234:
//獲取網站部署路徑(通過ServletContext對象),用於確定下載文件位置,從而實現下載
String path = servletContext.getRealPath("/");

//1.設置文件ContentType類型,這樣設置,會自動判斷下載文件類型
response.setContentType("multipart/form-data");
//2.設置文件頭:最後一個參數是設置下載文件名(假如我們叫a.pdf)
response.setHeader("Content-Disposition", "attachment;fileName="+"a.pdf");
ServletOutputStream out;
//通過文件路徑獲得File對象(假如此路徑中有一個download.pdf文件)
File file = new File(path + "download/" + "download.pdf");

try {
FileInputStream inputStream = new FileInputStream(file);

//3.通過response獲取ServletOutputStream對象(out)
out = response.getOutputStream();

int b = 0;
byte[] buffer = new byte[512];
while (b != -1){
b = inputStream.read(buffer);
//4.寫到輸出流(out)中
out.write(buffer,0,b);
}
inputStream.close();
out.close();
out.flush();

} catch (IOException e) {
e.printStackTrace();
}

⑶ 如何把springmvc model 生成pdf文件

本文先敘述,如何操作PDF模板生成PDF文件,再說明在SpringMVC中如何根據PDF模板生成PDF文件。
使用PDF模板生成PDF文件需要以下幾個步驟:
下面按步驟說明:
1. 使用Microsoft Office Word畫好模板
此步驟就不詳述了,就是一個普通的Word文件(template.docx)。給個示例截圖:

2. 使用Adobe Acrobat X Pro將Word文件轉換為帶表單欄位的PDF模板文件
1) 打開Adobe Acrobat X Pro
2) 選擇「創建PDF表單」
3) 選擇源:(PDF、Word、Excel或其它文件類型),下一步
4) 定位Word文件路徑,下一步
5) Adobe Acrobat X Pro會自動猜測表單欄位位置,如圖

6) 一般生成的表單欄位都不符合我們的要求,選中刪除即可。
7) 點擊右鍵選擇文本框,拖動到適當的位置,設置好域名稱,字型大小,字體等。

8) 保存模板文件。(template.pdf)
3. 使用itext操作PDF模板,填充數據,生成PDF文件
1) 需要jar包:itext.jar、itextAsian.jar
2) 核心代碼:
package personal.hutao.test;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class TestPdf {

@Test
public void test() throws IOException, DocumentException {
String fileName = "D:/template.pdf"; // pdf模板
PdfReader reader = new PdfReader(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper ps = new PdfStamper(reader, bos);
AcroFields fields = ps.getAcroFields();
fillData(fields, data());
ps.setFormFlattening(true);
ps.close();
OutputStream fos = new FileOutputStream("D:/contract.pdf");
fos.write(bos.toByteArray());
}

public void fillData(AcroFields fields, Map<String, String> data) throws IOException, DocumentException {
for (String key : data.keySet()) {
String value = data.get(key);
fields.setField(key, value);
}
}

public Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("borrower", "胡桃同學");
return data;
}
}

3) 打開contract.pdf,如圖
至此,就實現了根據PDF模板生成PDF文件。
SpringMVC的視圖中已提供了對PDF模板文件的支持:org.springframework.web.servlet.view.document.AbstractPdfStamperView。那麼只需要配置好此視圖就可以了。具體分為以下步驟:
1) 實現抽象類 AbstractPdfStamperView
package personal.hutao.view;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.view.document.AbstractPdfStamperView;

import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfStamper;

public class PdfStamperView extends AbstractPdfStamperView {

public static final String DATA = "data";
public static final String FILENAME = "mergePdfFileName";

@SuppressWarnings("unchecked")
@Override
protected void mergePdfDocument(Map<String, Object> model,
PdfStamper stamper, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(model.get(FILENAME).toString().getBytes(), "ISO8859-1"));
AcroFields fields = stamper.getAcroFields();
fillData(fields, (Map<String, String>) model.get(DATA));
stamper.setFormFlattening(true);
}

private void fillData(AcroFields fields, Map<String, String> data)
throws IOException, DocumentException {
for (String key : data.keySet()) {
String value = data.get(key);
fields.setField(key, value);
}
}

}

2) 在SpringMVC的配置文件中配置視圖
<!-- 按照BeanName解析視圖 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
<property name="order" value="1" />
</bean>

<!-- 定義Pdf模版視圖 -->
<bean id="contract" class="personal.hutao.view.PdfStamperView">
<property name="url" value="/WEB-INF/template/template.pdf" />
</bean>

3) Controller中的業務邏輯處理
package personal.hutao.controller;

import static personal.hutao.view.PdfStamperView.DATA;
import static personal.hutao.view.PdfStamperView.FILENAME;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.coamctech.sample.commons.controller.BaseController;

@RequestMapping("/contract")
@Controller
public class TestController {

@RequestMapping("/export/pdf")
public String (Model model) {
model.addAttribute(DATA, data());
model.addAttribute(FILENAME, "XXX貸款合同");
return "contract";
}

private Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("borrower", "胡桃同學");
return data;
}
}

⑷ java中怎麼利用struts2上傳多個pdf文件

通過3種方式模擬多個文件上傳
第一種方式
package com.ljq.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
private File[] image; //上傳的文件
private String[] imageFileName; //文件名稱
private String[] imageContentType; //文件類型
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(realpath);
if (image != null) {
File savedir=new File(realpath);
if(!savedir.getParentFile().exists())
savedir.getParentFile().mkdirs();
for(int i=0;i<image.length;i++){
File savefile = new File(savedir, imageFileName[i]);
FileUtils.File(image[i], savefile);
}
ActionContext.getContext().put("message", "文件上傳成功");
}
return "success";
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
}
第二種方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用數組上傳多個文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport{
private File[] image; //上傳的文件
private String[] imageFileName; //文件名稱
private String[] imageContentType; //文件類型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
//取得需要上傳的文件數組
File[] files = getImage();
if (files !=null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
//建立上傳文件的輸出流, getImageFileName()[i]
System.out.println(getSavePath() + "\\" + getImageFileName()[i]);
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName()[i]);
//建立上傳文件的輸入流
FileInputStream fis = new FileInputStream(files[i]);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=fis.read(buffer))>0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
}
}
return SUCCESS;
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上傳文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
第三種方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用List上傳多個文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction3 extends ActionSupport {
private List<File> image; // 上傳的文件
private List<String> imageFileName; // 文件名稱
private List<String> imageContentType; // 文件類型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
// 取得需要上傳的文件數組
List<File> files = getImage();
if (files != null && files.size() > 0) {
for (int i = 0; i < files.size(); i++) {
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName().get(i));
FileInputStream fis = new FileInputStream(files.get(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
return SUCCESS;
}
public List<File> getImage() {
return image;
}
public void setImage(List<File> image) {
this.image = image;
}
public List<String> getImageFileName() {
return imageFileName;
}
public void setImageFileName(List<String> imageFileName) {
this.imageFileName = imageFileName;
}
public List<String> getImageContentType() {
return imageContentType;
}
public void setImageContentType(List<String> imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上傳文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
struts.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 該屬性指定需要Struts2處理的請求後綴,該屬性的默認值是action,即所有匹配*.action的請求都由Struts2處理。
如果用戶需要指定多個請求後綴,則多個後綴之間以英文逗號(,)隔開。 -->
<constant name="struts.action.extension" value="do" />
<!-- 設置瀏覽器是否緩存靜態內容,默認值為true(生產環境下使用),開發階段最好關閉 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 當struts的配置文件修改後,系統是否自動重新載入該文件,默認值為false(生產環境下使用),開發階段最好打開 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 開發模式下使用,這樣可以列印出更詳細的錯誤信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默認的視圖主題 -->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectFactory" value="spring" />-->
<!--解決亂碼 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.multipart.maxSize" value="10701096"/>
<package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload1" namespace="/upload1" extends="struts-default">
<action name="upload1" class="com.ljq.action.UploadAction2" method="execute">
<!-- 要創建/image文件夾,否則會報找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload2" namespace="/upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.UploadAction3" method="execute">
<!-- 要創建/image文件夾,否則會報找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
上傳表單頁面upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上傳</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
<!-- ${pageContext.request.contextPath}/upload1/upload1.do -->
<!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
<!-- -->
<form action="${pageContext.request.contextPath}/upload2/upload2.do" enctype="multipart/form-data" method="post">
文件1:<input type="file" name="image"><br/>
文件2:<input type="file" name="image"><br/>
文件3:<input type="file" name="image"><br/>
<input type="submit" value="上傳" />
</form>
</body>
</html>
顯示頁面message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.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">
</head>
<body>
上傳成功
<br/>
<s:debug></s:debug>
</body>
</html>

⑸ 《JSP&Servlet學習筆記》pdf下載在線閱讀,求百度網盤雲資源

《JSP & Servlet學習筆記》(【台灣】林信良)電子書網盤下載免費在線閱讀

資源鏈接:

鏈接:https://pan..com/s/1oil-SMK44sHQVnO1lg2PXA

提取碼:qvj6

書名:JSP & Servlet學習筆記

作者:【台灣】林信良

豆瓣評分:8.6

出版社:清華大學出版社

出版年份:2012-5

頁數:463

內容簡介:本書是作者多年來教學實踐經驗的總結,匯集了教學過程中學生在學習JSP & Servlet時遇到的概念、操作、應用或認證考試等問題及解決方案。

本書針對Servlet 3.0的新功能全面改版,無論是章節架構與范常式序代碼,都做了全面更新。書中詳細介紹了Servlet/ JSP與Web容器之間的關系,必要時從Tomcat源代碼分析,了解Servlet/ JSP如何與容器互動。本書還涵蓋了文本處理、圖片驗證、自動登錄、驗證過濾器、壓縮處理、JSTL應用與操作等各種實用範例。

本書在講解的過程中,以「微博」項目貫穿全書,隨著每一章的講述都在適當的時候將JSP & Servlet技術應用於「微博」程序之中,以便讀者能了解完整的應用程序構建方法。

作者簡介:林信良(網名:良葛格)

學歷:台灣大學電機工程學系

經歷:台灣升陽教育訓練技術顧問、專業講師,Oracle授權訓練中心講師

著作:《Java JDK 5.0學習筆記》、《Java SE 6技術手冊》、《Spring技術手冊》等

譯作:《Ajax實戰手冊》、《jQuery實戰手冊(第2版)》

個人網站:http://openhome.cc

⑹ servlet 、jsp有像java基礎一樣的API文檔嗎

servlet和jsp也有像java一樣的api文檔。一般做成chm格式供開發人員參考。

比如在網路中搜索servlet幫助文檔,點擊網路一下:

點擊進去按照要求下載即可。

用同樣的方法可以下載到jsp的辦幫助文檔。

⑺ jsp頁面如何導成pdf格式

先在伺服器上生成PDF文件,然後用戶通過點擊指向PDF文件的超鏈接選擇下載或打開。這是一個思路,或者說是思路之一。本文實現了這個思路,又給出另外一個思路並通過兩種途徑實現之。

1)直接在伺服器上生成PDF文件。

<%@ page import ="com.lowagie.text.*
,com.lowagie.text.pdf.*, java.io.*"%>
<%
String filename =
"PDF"+(new Random()).nextInt()+".pdf" ;
Document document =
new Document(PageSize.A4);
ServletOutputStream out1
= response.getOutputStream();
try{
PdfWriter writer =
PdfWriter.getInstance(document,
new FileOutputStream(filename) );
document.open();
document.add(new Paragraph("Hello World"));
document.close();
}
catch(Exception e){}
%>

上面的程序在伺服器上生成了一個靜態的PDF文件。顯然,每次運行所得的PDF文件的名稱應該是獨一無二不能有重的。本程序通過隨機函數來命名生成的PDF文件。本程序的缺點就是,每次運行都會在伺服器上產生一個PDF文件,如果不及時刪除,數量會越來越大,這顯然是站點維護者所不願意看到的。

2)將PDF文件通過流的形式輸送到客戶端的緩存。這樣做的好處是不會在伺服器上留下任何「遺跡」。

i)直接通過JSP頁面生成

<%@
page import="java.io.*,
java.awt.Color,com.lowagie.text.*,
com.lowagie.text.pdf.*"%>
<%
response.setContentType
( "application/pdf" );
Document document = new Document();
ByteArrayOutputStream buffer
= new ByteArrayOutputStream();
PdfWriter writer=
PdfWriter.getInstance( document, buffer );
document.open();
document.add(new Paragraph("Hello World"));
document.close();
DataOutput output =
new DataOutputStream
( response.getOutputStream() );
byte[] bytes = buffer.toByteArray();
response.setContentLength(bytes.length);
for( int i = 0;
i < bytes.length;
i++ )
{
output.writeByte( bytes[i] );
}
%>

ii)通過Servlet生成

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public void doGet
(HttpServletRequest request,
HttpServletResponse response)
throws IOException,ServletException
{
Document document =
new Document(PageSize.A4, 36,36,36,36);
ByteArrayOutputStream ba
= new ByteArrayOutputStream();
try
{
PdfWriter writer =
PdfWriter.getInstance(document, ba);
document.open();
document.add(new
Paragraph("Hello World"));
}
catch(DocumentException de)
{
de.printStackTrace();
System.err.println
("A Document error:" +de.getMessage());
}
document.close();
response.setContentType
("application/pdf");
response.setContentLength(ba.size());
ServletOutputStream out
= response.getOutputStream();
ba.writeTo(out);
out.flush();
}

閱讀全文

與servlet教程pdf相關的資料

熱點內容
更新快學習看片網站 瀏覽:604
上海人名廣場解壓博物館 瀏覽:222
nyy. onlie/ index. php/ vohpl 瀏覽:701
行為科學pdf 瀏覽:135
電影最後的演員表是頓號還是空格 瀏覽:501
怎麼鎖pdf 瀏覽:524
手機sd文件夾為空 瀏覽:193
邵氏武打功夫片大全 瀏覽:230
抖音電影音樂榜單 瀏覽:674
jquery旋轉木馬特效源碼 瀏覽:428
電影永恆無刪減版185 瀏覽:720
完美世界的後續小說 瀏覽:4
台灣電影埃及場景 瀏覽:806
華為的親情關懷app哪裡下載 瀏覽:488
win8定時關機命令 瀏覽:612
榮耀手機電池app耗電量如何隱藏 瀏覽:322
Win10開機啟動項命令 瀏覽:949
兒女傳奇所有電影資源 瀏覽:847
葉子楣跟徐錦江電影 瀏覽:318
十大封禁鬼片國產 瀏覽:559