jsp牛刀小试

        因为帮人做个网站,不想再用vs,改用java。但做小应用没必要用servlet这些重口味的。因此试试jsp,把过程写下来备忘:

一、JSP语法:

1、import包:<%@ page contentType="text/html; charset=gb2312" language="java" import="java.util.*,com.jspsmart.upload.*" errorPage="" %>

2、包含文件:<%@ include file="/conn.jsp" %>

3、常用对象:

  • String yid = request.getParameter("yid").toString();//注意getParameter和getAttribute的区别。
  • response.sendRedirect("abc.jsp");//注意服务器端跳转和客户端跳转的区别。
  • String name = (String)session.getAttribute("name");

二、分页代码:

      分页其实比较简单,取数时有两种方法,一个是全部取出来,然后根据页数展示相应数据;另一种是只取特定位置数据,需要数据库支持(此处未用)。代码分成两部分,一部分是数据展示,一部分是翻页展示。 

  1 <table width="98%"  border="0" align="center" cellpadding="0" cellspacing="0">
  2   <tr>
  3     <td height="25"><b><font color="#FF0000">信息列表</font></b></td>
  4   </tr>
  5   <tr>
  6     <td><table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#799AE1">
  7       <tr>
  8         <form action="newsgl.jsp" method="post" name="toGetBWList" id="Form1">
  9           <td  height="30" align=left> &nbsp;&nbsp;&nbsp;&nbsp;搜索:
 10               <input name="keyword" type=text value="" class="button1">
 11               <input type="submit" name="Submit" value=" 搜 索 " class="button2">
 12           </td>
 13           <td align=right>
 14             <div align="center">
 15             <input type="button" name="add" value=" 新 增 " class="button2" onclick="javascript:window.open('newsmodify.jsp');">
 16               <input name=reloadPage type=button value=" 刷 新 " id="reloadPage" onClick="javascript:window.location.reload();" class="button2">
 17           </div></td>
 18         </form>
 19       </tr>
 20     </table>
 21     <br>
 22     <table width="100%" border="1" cellspacing="0" cellpadding="0" bordercolordark="#FFFFFF" bordercolorlight="#CCCCCC">
 23       <tr bgcolor="#799AE1">
 24         <td width="6%"><div align='center'><font color="#FFFFFF">选定</font></div></td>
 25         <td height="20" bgcolor="#799AE1"><div align="center"><font color="#FFFFFF">标题</font></div></td>
 26         <td width="22%" height="20"><div align="center"><font color="#FFFFFF">作者</font></div></td>
 27         
 28         <td width="7%"><div align="center"><font color="#FFFFFF">修改</font></div></td>
 29       </tr>
 30       <form name="delnews" action="newsgl.jsp" method=post>
 31       <input name="action" type="hidden" value="" id="action">
 32 <%
 33 int intPageSize; //一页显示的记录数 
 34 int intRowCount=0//记录总数 
 35 int intPageCount=1//总页数 
 36 int intPage; //待显示页码 
 37 String strPage; 
 38 int i; 
 39 //设置一页显示的记录数 
 40 intPageSize = 20
 41 //取得待显示页码 
 42 strPage = request.getParameter("page"); 
 43 if(strPage==null){//表明在QueryString中没有page这一个参数,此时显示第一页数据 
 44 intPage = 1
 45 } 
 46 else{//将字符串转换成整型 
 47 intPage = java.lang.Integer.parseInt(strPage); 
 48 if(intPage<1) intPage = 1
 49 }
 50 String keyword=request.getParameter("keyword");
 51 if(keyword==null)keyword="*";
 52   else if(keyword.equals(""))keyword="*";
 53          else keyword = "*"+keyword+"*";
 54 String action = request.getParameter("action");
 55 if((action!=null)&&(action.equals("del"))){//delete items
 56     try{
 57     Connection con1=DriverManager.getConnection(dburl) ; 
 58     for(int j=0;j<request.getParameterValues("NewsID").length;j++){
 59             PreparedStatement stmt1 = con1.prepareStatement("delete from news where nid=?");
 60                stmt1.setInt(1,Integer.parseInt(request.getParameterValues("NewsID")[j]));
 61                stmt1.executeUpdate();
 62                stmt1.close();
 63         }
 64     con1.close();
 65     }catch(Exception ex){
 66         ex.printStackTrace();
 67     }
 68 }
 69 try{
 70     String title="";
 71     String author="";
 72     String content = "";
 73     int nid = 0;
 74     Connection con=DriverManager.getConnection(dburl) ; 
 75     PreparedStatement stmt = con.prepareStatement("select * from news",java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);
 76     ResultSet rst=stmt.executeQuery();
 77     
 78     //获取记录总数 
 79     rst.last();//??光标在最后一行 
 80     intRowCount = rst.getRow();//获得当前行号 
 81     //记算总页数 
 82     intPageCount = (intRowCount+intPageSize-1) / intPageSize; 
 83     //调整待显示的页码 
 84     if(intPage>intPageCount) intPage = intPageCount;
 85 
 86     if(intPageCount>0){ 
 87     //将记录指针定位到待显示页的第一条记录上 
 88     rst.absolute((intPage-1) * intPageSize + 1);
 89     
 90     int c = 0;
 91     while(c<intPageSize && !rst.isAfterLast())
 92     {
 93         c++;
 94         title=rst.getString("title");
 95         author=rst.getString("author");
 96         content=rst.getString("content");
 97         nid=rst.getInt("nid");
 98 %>
 99                       <tr>
100           <td width="6%"><div align="center"><input type="checkbox" name="NewsID" value="<%=nid%>"></div></td>
101           <td height="43%" align="center" style="word-break:break-all;"><a href='newsmodify.jsp?nid=<%=nid %>' class='tt4' target='_blank'><%=title %></a></td>
102           <td width="43%" height="22"><div align="center"><a href='newsmodify.jsp?nid=<%=nid %>' class='tt4' target='_blank'><%=author %></a></div></td>
103           <td width="8%"><div align='center'><a href="newsmodify.jsp?nid=<%=nid %>" class="tt2">修改</a></div></td>
104                       </tr>
105 <%
106         rst.next();
107     }
108     }
109     rst.close();
110     stmt.close();
111     con.close();
112 }catch(Exception ex){
113     ex.printStackTrace();
114 }
115 %>    
116       </form>
117     </table>
118     <table width="100%" border="0" cellpadding="0" cellspacing="0">
119       <form name="pageform" method="post" action="newsgl.jsp">
120         <tr>
121           <td width="6%" height="25">
122             <div align="center">
123               <input type='checkbox' name='selectCheck' id=selectCheck2 onclick="javascript:SelectCheckBox();">
124           </div></td>
125           <td width="33%">全部选中
126               <input name="delbtn" value="删除" type="button" class="button2" onclick="javascript:cdel();">
127               
128             </td>
129           <td>
130           <div align="right">
131             共<%=intRowCount %>条信息&nbsp;当前为:<font color="#FF0000"><%=intPage %></font>/<%=intPageCount %>页
132             <%if(intPage>1){%><a href="newsgl.jsp?page=<%=intPage-1%>&keyword=<%=keyword%>">上一页</a><%}%>
133             <%if(intPage<intPageCount){%><a href="newsgl.jsp?page=<%=intPage+1%>">下一页</a><%}%>
134             跳到第&nbsp;<input type=text size=3 name="page" value="" class="button1">&nbsp;页
135               <input type="hidden" name="keyword" value="<%=keyword%>">
136             <input name="imageField" type="image" src="go.gif" border="0" align="absmiddle">
137           </div></td>
138         </tr>
139       </form>
140     </table></td>
141   </tr>
142 </table>

 

        其中33-98行是分页数据产生代码;99-115行是循环展示的HTML代码;129-137行是翻页代码。

三、访问数据库:

        windows下访问access数据库有2个方法:jdbc-odbc方式和jdbc方式。windows下的jdbc-odbc方式很简单,直接用getConnection即可(至少在我的机器上无需调用Class.forName("xxdriver").newInstance()),linux下应该是没有jdbc-odbc方式吧。jdbc方式需要Access_JDBC30.jar。

        1、access的jdbc-odbc方式:

String dburl="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=e:/Projects/workspace.win/qyjskf/WebContent/WEB-INF/qysjkf.mdb"
Connection con=DriverManager.getConnection(dburl) ; 
    PreparedStatement stmt = con.prepareStatement("select * from magazines where qkll=? and journals=?");
    stmt.setInt(1,yid);
    stmt.setInt(2,jid);
    ResultSet rst=stmt.executeQuery();
    int c = 0;
    while(rst.next()){
        //do something
    }
    rst.close();
    stmt.close();
    con.close();

        2、常用的jdbc方式,使用DriverManager.getConnection()获取连接:

//Access 数据库 jdbc驱动
try{
    Class.forName("com.hxtt.sql.access.AccessDriver").newInstance();
}catch(Exception ex){
    out.println("[错误] 加载数据库驱动出错");
}
String dburl="jdbc:Access:///c:/test.mdb";

//SQL Server数据库 jtds驱动
try{
    Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
}catch(Exception ex){
    out.println("[错误] 加载数据库驱动出错");
}
String dburl = "jdbc:jtds:sqlserver://127.0.0.1:7788/test;user=dbuser;password=dbpassword";

//SQL Server数据库  Microsoft jdbc驱动
try{
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
}catch(Exception ex){
    out.println("[错误] 加载数据库驱动出错");
}
String dburl = "jdbc:microsoft:sqlserver://127.0.0.1:7788; DatabaseName=test;user=dbuser;password=dbpassword";
 
//Oracle数据库  Oracle jdbc驱动
try{
    Class.forName("oracle.jdbc.OracleDriver").newInstance();
}catch(Exception ex){
    out.println("[错误] 加载数据库驱动出错");
}
String dburl = "jdbc:oracle:thin:@host:1521:testdb";

//jdbc-odbc桥模式访问Access
//String dburl="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=c:/test.mdb"; 

四、OLE数据读写:

        OLE数据的读写很简单:

FileInputStream inf = null;
inf = new FileInputStream(uploadpath+"/"+file.getFileName());
int length = inf.available();
stmt = con.prepareStatement("update magazines set title=?,abstracts=?,author=?,year=?,journals=?,filename=?,filetype=?,topic=? where mid=?");
stmt.setBinaryStream(8,inf,length);
int rst=stmt.executeUpdate();
inf.close();

        读取就用getBinaryStream方法。详情可参考http://blog.csdn.net/kevinliuu/article/details/836202

五、上传下载文件:

        上传文件方法很多,大多用到组件。这里用的是jspsmart,功能很简单,但是够用了。可参考http://wenku.baidu.com/view/5781fad7b9f3f90f76c61b86.htmlhttp://developer.51cto.com/art/200907/134497.htm

        上传文件代码:

 1 SmartUpload su = new SmartUpload();//必须最先调用
 2 su.initialize(pageContext);//必须先初始化
 3 //设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。  
 4 su.setAllowedFilesList("doc,txt,pdf");  
 5 //jsp,htm,html扩展名的文件和没有扩展名的文件。  
 6 su.setDeniedFilesList("exe,bat,jsp,htm,html");
 7 // 上传文件  
 8 su.upload();
 9 // 将上传文件全部保存到指定目录 
10 int count = su.save(uploadpath);//,SmartUpload.SAVE_VIRTUAL);  
11 com.jspsmart.upload.Request mrequest = su.getRequest();
12 //利用Request对象获取参数之值  
13 String act = mrequest.getParameter("act")==null?"":mrequest.getParameter("act");
14 String title = mrequest.getParameter("d_title")==null?"":mrequest.getParameter("d_title");
15 String abstracts = mrequest.getParameter("d_abstracts")==null?"":mrequest.getParameter("d_abstracts");
16 String author = mrequest.getParameter("d_author")==null?"":mrequest.getParameter("d_author");
17 int year = 2012;
18 try{
19     year = Integer.parseInt(mrequest.getParameter("d_year"));
20 }catch(Exception ex){
21     year = 2012;
22 }
23 int journals = 1;
24 try{
25     journals = Integer.parseInt(mrequest.getParameter("d_journals"));
26 }catch(Exception ex){
27     journals = 1;
28 }
29 int mid = 1;
30 try{
31     mid = Integer.parseInt(mrequest.getParameter("mid"));
32 }catch(Exception ex){
33     mid = 0;
34 }
35 
36 // 逐一提取上传文件信息,同时可保存文件。  
37 if(su.getFiles().getCount() >0)
38 {  
39     com.jspsmart.upload.File file = su.getFiles().getFile(0);  
40     try{
41         Connection con=DriverManager.getConnection(dburl) ;
42         PreparedStatement stmt;
43         int rst = 0;
44         FileInputStream inf = null;
45         inf = new FileInputStream(uploadpath+"/"+file.getFileName());
46         int length = inf.available();
47         if(mid>0){//update old news
48             stmt = con.prepareStatement("update magazines set title=?,abstracts=?,author=?,year=?,journals=?,filename=?,filetype=?,topic=? where mid=?");
49             stmt.setString(1,title);
50             stmt.setString(2,abstracts);
51             stmt.setString(3,author);
52             stmt.setInt(4,year);
53             stmt.setInt(5,journals);
54             stmt.setString(6,file.getFileName());
55             stmt.setString(7,file.getFileExt());
56             stmt.setBinaryStream(8,inf,length);
57             stmt.setInt(9,mid);
58             //out.println("<script>alert('do update')</script>");
59         }else{//add new news
60             stmt = con.prepareStatement("insert into magazines(title,abstracts,author,year,journals,filename,filetype,topic) values(?,?,?,?,?,?,?,?)");
61             stmt.setString(1,title);
62             stmt.setString(2,abstracts);
63             stmt.setString(3,author);
64             stmt.setInt(4,year);
65             stmt.setInt(5,journals);
66             stmt.setString(6,file.getFileName());
67             stmt.setString(7,file.getFileExt());
68             stmt.setBinaryStream(8,inf,length);
69             //out.println("<script>alert('do insert')</script>");
70         }
71         rst=stmt.executeUpdate();
72         inf.close();
73         java.io.File myDelFile=new java.io.File(uploadpath+"/"+file.getFileName()); 
74         if(myDelFile.exists()) 
75         { 
76             myDelFile.delete();
77         } 
78 
79         if(rst>0){
80             out.println("<script>alert(\"修改成功\");</script>");
81         }else{
82             out.println("<script>alert(\"修改失败\");</script>");
83         }
84         stmt.close();
85         con.close();
86         //response.sendRedirect("qkgl.jsp");
87     }catch(Exception ex){
88         ex.printStackTrace();
89     }
90 }  

        下载文件代码:

 1 int mid = 0;
 2 String title="";
 3 try{
 4     mid = Integer.parseInt(request.getParameter("mid"));
 5 }catch(Exception ex){
 6     mid = 0;
 7 }
 8 if(mid==0){
 9     out.println("<script>alert('无此文档');</script>");
10 }else{
11     try{
12         Connection con=DriverManager.getConnection(dburl) ;
13         PreparedStatement stmt = con.prepareStatement("select * from magazines where mid=?");
14         stmt.setInt(1,mid);
15         ResultSet rst = stmt.executeQuery();
16         if(rst.next()){
17             String fn = rst.getString("filename");
18             if(fn==null){
19                 out.println("</script>alert('无此文件');</script>");
20             }else{
21                 String filename = URLEncoder.encode(fn,"UTF-8");
22                 //response.addHeader("Content-Disposition", "attachment;filename=" + filename);
23                 java.io.File temp = java.io.File.createTempFile("temp","."+rst.getString("filetype"));
24                 InputStream infile = rst.getBinaryStream("topic");
25                 FileOutputStream file = null;
26                 file = new FileOutputStream (temp);
27                 int chunk;
28                 while ((chunk = infile.read()) != -1)
29                     file.write(chunk);
30                 file.close();
31                 infile.close();
32                 
33                 SmartUpload su = new SmartUpload();
34                 // 初始化
35                 su.initialize(pageContext);
36                 // 设定contentDisposition为null以禁止浏览器自动打开文件,
37                 //保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
38                 //doc时,浏览器将自动用word打开它。扩展名为pdf时,
39                 //浏览器将用acrobat打开。
40                 su.setContentDisposition(null);
41                 // 下载文件
42                 su.downloadFile(temp.getAbsolutePath());
43                 out.clear();
44                 out = pageContext.pushBody();
45                 //out.println(temp.getAbsolutePath());
46                 //out.println(fn);
47                 temp.delete();
48             }
49         }
50     }catch(Exception ex){
51         ex.printStackTrace();
52     }
53 }

六、热部署(与此jsp无关):

        Tomcat6的部署很简单,把war包复制到webapps下面,tomcat能自动部署(生成一个同名的目录),不过要记得删掉那个war包,否则可能会被下载。另外,如果直接修改目录下的jsp文件也能生效,class文件未测试。

        此外,通过修改配置文件也能进行部署,有很多文章介绍,可参见http://www.chysoft.net/files/article_305.htm,另外,有篇写得我看不懂的也附上,http://space.itpub.net/?uid-23071790-action-viewspace-itemid-702545

        对于已经部署的应用,如需修改部署名,可以修改web.xml文件的<display-name>appname</display-name>

七、配置oracle的jndi数据源(与此jsp无关):

        主要是修改配置文件:server.xml

<GlobalNamingResources>
    <Resource
            name="jdbc/test"
            type="javax.sql.DataSource"
            maxActive="200"
            maxIdle="10"
            username="username"
            maxWait="5000"
            driverClassName="oracle.jdbc.OracleDriver"
            password="password"
            url="jdbc:oracle:thin:@127.0.0.1:1521:test"/>
</GlobalNamingResources>

        另外还要配置content.xml:       

<ResourceLink global="jdbc/test" name="jdbc/test" type="javax.sql.DataSource"/>

          在程序中的访问方法:

 1     public static Connection getJNDIConnection(String jndiname)
 2     {
 3         if((jndiname==null)||(jndiname.equals("")))
 4             jndiname= "java:comp/env/jdbc/test";
 5         Connection Conn=null;
 6         if(Conn==null)
 7         {
 8             try{
 9                 Context ctx = new InitialContext();
10                 if (ctx==null){
11                     return null;
12                 }
13                 DataSource ds = (DataSource) ctx.lookup(jndiname);
14                 if (ds != null) {
15                     Conn = ds.getConnection();
16                 }
17             }
18             catch(Exception ex)
19             {
20                 Conn = null;
21                 System.out.println(new java.util.Date().toLocaleString()+" [错误] 无法新建数据库连接,jndi:"+jndiname+"-"+ex.getMessage());
22                 return Conn;
23             }
24         }
25         return Conn;
26     }

 

posted @ 2012-04-24 22:31  badwood  阅读(803)  评论(0编辑  收藏  举报
Badwood's Blog