package useServ;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class firstServ extends GenericServlet{
public void service(ServletRequest request, ServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("
use Servlet");
out.println("");
out.println("This is my first Servlet
");
out.println("
");
out.println("");
}
}
2)编译firstServ.java,编译之前添加%Tomcathome%\lib\servlet-api.jar和jsp-api.jar到环境变量的CLASSPATH中,否则会出现无法找到javax.servlet的错误。
3)放置firstServ.class到webapps\本地路径\WEB-INF\classes\useServ\下
4)编辑 本地路径\WEB-INF\web.xml,添加Servlet映射如下:
<web-app>
<display-name>firstServdisplay-name>
<description>firstServdescription>
<servlet>
<servlet-name>firstServservlet-name>
<servlet-class>useServ.firstServservlet-class>
servlet>
<servlet-mapping>
<servlet-name>firstServservlet-name>
<url-pattern>/firstServurl-pattern>
servlet-mapping>
web-app>
最后的文档结构如下:
webapps
|--manager/
|--examples/
|--MyApps/
|--WEB-INF/
| |--classes/ 放为项目写的.class文件
| | |--MyAppServlet.class
| |--lib/ 放第三方jar包
| |--web.xml
|--index.html
|--login.jsp
注意:Eclipse for J2EE 在创建Dynamic Web Project时候用 @WebServlet("/xxxServlet")注释作Servlet配置, 因此项目树中并没有web.xml.
5)重启Tomcat,访问localhost:8080\work或en\firstServ即可
1.3JSP+JavaBean发布
1)编写bean(e.g.->Counter.java)
package bean;
public class Counter{
int count = 0;
public int getCount(){ //getXXX&setXXX为必须,且要遵循命名规范
count++;
return this.count;
}
public void setCount(int count){
this.count = count;
}
}
2)置Counter.java于%Tomcat%\webapps\自己的web工程\WEB-INF\classes下;控制台cd到classes下,用javac -d . Counter.java 命令编译(-d: 如果不存在bean文件夹则自动创建; . :当前目录);生成Counter.class文件于classes文件夹下。
3)编写《作用域演示.jsp》——演示javaBean的三个作用域的范围(request作用域尚不清楚).
<%@ page contentType="text/html; charset=GB2312" %>
counter
使用page作用域:
计数值为:<%= page_counter.getCount() %>
使用session作用域:
计数器值为:<%= session_counter.getCount() %>
使用application作用域:
计数器值为:<%= application_counter.getCount() %>
4)javaBean动作语法:——亦可使用内嵌脚本表达式使用Bean(此处略述)
/*如果property="*"则意味着从jsp页面查找获取到的parameters,与Bean里的属性相对应进行赋值*/
/*该动作语句类似表达式,直接返回取到的属性名对应的属性值*/
5)打开tomcat进行操作。
e 2.1 添加errorPage
.(0)errorPage
在开头部分加入<% errorPage="error.jsp" %>即可
消 2.2消除乱码
1
(1)表单提交乱码问题
逻辑处理部分的开头加入:
<% request.setCharacterEncoding("GB2312"); %>
举例:《encode.jsp》
<%@ page contentType="text/html;charset=GB2312" %>
<% request.setCharacterEncoding("GB2312"); %>
解决乱码
用户名为:<%=request.getParameter("name")%>
(2)使用Filter
1)编写Filter并编译:《EncodingFilter.java》
package bean;
import java.io.*;
import javax.servlet.*;
public class EncodingFilter implements Filter{
protected String encoding = null;
protected FilterConfig config;
public void init(FilterConfig filterConfig)throws ServletException{
this.config = filterConfig;
this.encoding = filterConfig.getInitParameter("Encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)
throws IOException,ServletException{
if(request.getCharacterEncoding()==null){
String encode = getEncoding();
if(encode != null){
request.setCharacterEncoding(encode);
}
}
chain.doFilter(request,response);
}
protected String getEncoding(){
return encoding;
}
public void destroy(){
}
}
2)web.xml建立Filter的映射
EncodingFilter
bean.EncodingFilter
Encoding
GB2312
EncodingFilter
/*
3)ok,以后所有前台页面的request都进行doFilter。从全局上解决了乱码问题。
2.3 SmartUpload上传下载
1)从下载jspSmartUpload.zip
2)解压。在控制台将目录切换到jspsmartupload/WEB-INF目录下
3)运行JAR打包命令:jar cvf jspSmartUpload.jar com
4)将jspSmartUpload.jar拷贝到Tomcat的lib目录下(以后全部的web应用都可以使用com.jspsmart.*来创建特定应用)
5)编写上传请求表单页面——注意:method=post enctype="multipart/form-data"
<%@ page contentType="text/html;charset=GB2312"%>
6)编写uploadProcess.jsp
<%@ page contentType="text/html;charset=gb2312" language="java" import="java.io.*, java.util.*, com.jspsmart.upload.*" %>
上传
<%
com.jspsmart.upload.SmartUpload su = new com.jspsmart.upload.SmartUpload();
su.initialize(pageContext);
su.setMaxFileSize(1024*1024);
su.setTotalMaxFileSize(4*1024*1024);
su.setAllowedFilesList("doc,txt,jpg");
su.setDeniedFilesList("exe,bat,jsp");
su.upload();
int count = su.save("/upload");
out.println(count+"个文件上传成功!
");
out.println("Test="+su.getRequest().getParameter("dscp")+"
");
for (int i=0;i com.jspsmart.upload.File file = su.getFiles().getFile(i);
if (file.isMissing()) continue;
out.println("
");
out.println("表单项名(FieldName) | "+file.getFieldName() + " |
");
out.println("文件长度(Size) | " + file.getSize() + " |
");
out.println("文件名(FileName) | "+ file.getFileName() + " |
");
out.println("文件扩展名(FileExt) | " + file.getFileExt() + " |
");
out.println("文件全名(FilePathName) | "+ file.getFilePathName() + " |
");
out.println("
");
}
%>
=============================================================================================
1)下载页面
<%@ page contentType="text/html;charset=GB2312" %>
2.4 POI处理Excel文件
1.处理Excel的组件有POI和jxl,此处使用POI,它是连接MSOffice和JSP的桥梁。
2.从进入POI项目下载poi-bin-3.7-beta1-20100620.zip。解压出poi-bin-3.7-beta1-20100620.jar置于%Tomcat%的lib下,可使所有web开发利用。
==========================================================================================
创建过程:创建输出流FileOutputStream(含地址)->使用HSSFWorkbook对象写输出流{wb.write(fout)}
创建Excel文件《workbook.xls》
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.io.*,java.util.*,
org.apache.poi.poifs.filesystem.*,org.apache.poi.hssf.usermodel.*"%>
<%
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(application.getRealPath("/")+"workbook.xls"); /*Key生成*/
wb.write(fileOut);
fileOut.close();
%>
创建Excel的sheet《sheet/second sheet/...》
<%
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet("new sheet");
HSSFSheet sheet2 = wb.createSheet("second sheet");
FileOutputStream fileOut = new FileOutputStream(application.getRealPath("/")+"workbook.xls");
wb.write(fileOut);
fileOut.close();
%>
创建Cells
<%
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(1);
row.createCell((short)1).setCellValue(1.2);
row.createCell((short)2).setCellValue("This is a string");
row.createCell((short)3).setCellValue(true);
// Write the output to the file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
%>
创建日期型Cell
<%
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
HSSFCell cell = row.createCell((short)0);
cell.setCellValue(new Date()); //当前日期
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
cell = row.createCell((short)1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
FileOutputStream fileOut = new FileOutputStream(application.getRealPath("/")+"workbook.xls");
wb.write(fileOut);
fileOut.close();
%>
Cell不同数据类型的展示
<%
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)2);
row.createCell((short) 0).setCellValue(1.1);
row.createCell((short) 1).setCellValue(new Date());
row.createCell((short) 2).setCellValue("a string");
row.createCell((short) 3).setCellValue(true);
row.createCell((short) 4).setCellType(HSSFCell.CELL_TYPE_ERROR);
FileOutputStream fileOut = new FileOutputStream(application.getRealPath("/")+"workbook.xls");
wb.write(fileOut);
fileOut.close();
%>
==========================================================================================================================
4.
JSP中查看excel文件《readExcel.jsp》
查看过程:
1)将待查看文件变成java输入流FileInputStream
2)java输入流转化成POI文件系统流(POIFSFileSystem),并关闭java输入流
3)利用POIFSFileSystem创建HSSF系统的Workbook(HSSFWorkbook)
4)创建HSSFSheet获取HSSFWorkbook的指定sheet
5)使用HSSFRow/HSSFCell查看
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.io.*,java.util.*, org.apache.poi.poifs.filesystem.*,org.apache.poi.hssf.usermodel.*" %>
ExcelReading JSP读取Excel中的值
<%
FileInputStream finput = new FileInputStream(application.getRealPath("/")+"aaa.xls"); //使用java.io的FileInputStream读取当前目录下的aaa.xls
POIFSFileSystem fs = new POIFSFileSystem(finput);//转化为POI文件系统
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);//获取第一个excel表到sheet(HSSFSheet)
finput.close();
HSSFRow row = null;
HSSFCell cell = null;
short i = 0;
short j = 0;
/*依次对行、列进行读取*/
for(i=0; i <= sheet.getLastRowNum(); i++){ //获取行数(从0数起)
out.println("
");
/*在没有对POI的相关API了解清楚的时候,try块是必要的,否则容易出现:空指针异常*/
try{
row = sheet.getRow(i);
for(j=0;j < row.getLastCellNum(); j++){//从0数起获取每行的cell数(注意:如不为空则会多1,因此此处不能令j<=,而只能是j<)
cell = row.getCell((short)j);
out.print(""); /*判断cell中数据类型*/ switch( cell.getCellType() ){ case HSSFCell.CELL_TYPE_NUMERIC: out.print(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_STRING: out.print(cell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: out.print(cell.getCellFormula()); break; default: out.print("不明的格式"); break; } out.println(" | ");
}
}catch(Exception e){out.print("xxx
");}
out.println("
");
}
%>
注:
public int getCellType()
返回值说明:
Celltype 定义值 值(int)
Blank CELL_TYPE_BLANK 3
Boolean CELL_TYPE_BOOLEAN 4
Error CELL_TYPE_ERROR 5
Formula CELL_TYPE_FORMULA 2
Numeric CELL_TYPE_NUMERIC 0
String CELL_TYPE_STRING 1
==========================================================================================
5.增加Excel记录《addExcel.jsp》
增加过程:
1)将待查看文件变成java输入流FileInputStream
2)java输入流转化成POI文件系统流(POIFSFileSystem),并关闭java输入流
3)利用POIFSFileSystem创建HSSF系统的Workbook(HSSFWorkbook)
4)创建HSSFSheet获取HSSFWorkbook的指定sheet
5)使用sheet.getLastRowNum/sheet.createRow/row.createCell/cell.setCellValue等方法操作
6)最后将Workbook写回原文件:输出流FileOutputStream(含地址)->使用HSSFWorkbook对象写输出流{wb.write(fout)}
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.io.*,java.util.*, org.apache.poi.poifs.filesystem.*,org.apache.poi.hssf.usermodel.*" %>
ExcelReading JSP增加Excel中的值
<%
FileInputStream finput = new FileInputStream(application.getRealPath("/")+"aaa.xls");
POIFSFileSystem fs = new POIFSFileSystem(finput);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
finput.close();
HSSFRow row = null;
HSSFCell cell = null;
int i = sheet.getLastRowNum()+1;
row = sheet.createRow(i);
cell = row.createCell((short)0);
// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("哈哈");
cell = row.createCell((short)1);
cell.setCellValue(40);
cell = row.createCell((short)2);
cell.setCellValue(3);
cell = row.createCell((short)3);
cell.setCellFormula("B"+(i+1)+"*C"+(i+1));
========================================================================================
6.Excel数据删除
删除过程:
1)将待查看文件变成java输入流FileInputStream
2)java输入流转化成POI文件系统流(POIFSFileSystem),并关闭java输入流
3)利用POIFSFileSystem创建HSSF系统的Workbook(HSSFWorkbook)
4)创建HSSFSheet获取HSSFWorkbook的指定sheet
5)使用sheet.getRow/sheet.removeRow方法操作
6)最后将Workbook写回原文件:输出流FileOutputStream(含地址)->使用HSSFWorkbook对象写输出流{wb.write(fout)}
<%
try{
FileInputStream finput = new FileInputStream(application.getRealPath("/")+"aaa.xls");
POIFSFileSystem fs = new POIFSFileSystem( finput );
HSSFWorkbook wb =new HSSFWorkbook(fs);
finput.close();
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
row = sheet.getRow(sheet.getLastRowNum());
if(row != null){
sheet.removeRow(row);
}
FileOutputStream fout = new FileOutputStream(application.getRealPath("/")+"aaa.xls");
wb.write(fout);
fout.close();
out.print("
删除成功
");
}catch(Exception e){
out.print("
"+e.toString()+"
");
}
%>
3.数据库(Access)
3.1 Access数据库配置