java 从零开始,学习笔记之基础入门(二十八)

数据库连接配置

配置方式一:

1.        在tomcat中输入地址http://localhost:8080/admin进入管理控制台,找到service节点中的host节点,在此节点中查找需要使用jndi服务的工程,并对其配置jndi服务。

2.        在工程中只需要使用服务即可,无需进行其他配置

 

 

Action中新建一个显示文件列表信息的servlet,ShowFileAction.

Showfile.jsp是此应用的视图,

 

 

ShowFileAction中需要调用FileOpenDAO来获得具体的数据

 

配置方式二:

context.xml

context.xml

xml version="1.0" encoding="UTF-8"?>

<Context>

 

    <Resource name="sqlconn"

              auth="Container"

              type="javax.sql.DataSource"

              driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"

              url="jdbc:sqlserver://192.168.12.35:1433;databasename=j1201" 

              username="sa"

              password="123"

              maxAction="20"

              maxIdle="10"

              maxWait="10000"

      />

 

Context>

 

Xml配置文件中部分关于jndi的配置

 

 

 <resource-ref>

    <description>jndidescription>

    <res-ref-name>sqlconnres-ref-name>

    <res-type>javax.sql.DataSourceres-type>

    <res-auth>Containerres-auth>

 resource-ref>

 

 

DataSourceFactory.java

DataSourceFactory.java

package com.ibm.factory;

 

import javax.naming.Context;

import javax.naming.InitialContext;

import javax.sql.DataSource;

 

public class DataSourceFactory {

   

   

    private static DataSource ds = null;

   

    public static DataSource getDataSource(){

        try{

           

            Context context = new InitialContext();

            //第一步:找到Java服务器中的系统环境变量

            Context jceContext=(Context)context.lookup("java:comp/env");

            //第二步“从系统环境变量中 搜寻JNDI

            ds=(DataSource)jceContext.lookup("sqlconn");

           

            if(ds!=null){

                System.out.println("从web服务器上找到数据源了");

            }

           

           

        }catch (Exception e){

            e.printStackTrace();

        }

        return ds;

       

    }

   

 

}

 

 

FileOpenDAO.java

FileOpenDAO.java

  package com.ibm.dao;

 

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

import javax.sql.DataSource;

import com.ibm.dto.UFile;

import com.ibm.factory.DataSourceFactory;

 

/**

 * 文件表操作

 * @author 123

 *

 */

public class FileOpenDAO {

   

   

    public List getFileList(){

        DataSource ds=null;

        Connection conn=null;

        Statement stmt=null;

        ResultSet rs=null;

        List list=null;

        try {

            //获得数据源

            ds=DataSourceFactory.getDataSource();

            conn=ds.getConnection();

            stmt=conn.createStatement();

            rs=stmt.executeQuery("select * from filetb");

           

            list=new ArrayList();

            //循环读取数据  并封装到list中

            while(rs.next()){

                UFile file=new UFile();

                file.setFileId(rs.getInt("fileid"));

                file.setFiName(rs.getString("finame"));

                list.add(file);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }finally{

            try{

            if(conn!=null){

                conn.close();

            }

            }catch(Exception e){

                e.printStackTrace();

            }

           

        }

        return list;

       

    }

   

//  public static void main(String[] args) {

//      FileOpenDAO ds= new FileOpenDAO();

//      List list=ds.getFileList();

//     

//      for(UFile file:list){

//        System.out.println(file.getFiName());

       

//      System.out.println(list.get(0).getFileId());

       

//      for (int i = 0; i < list.size(); i++) {

//          System.out.println(list.get(i).getFileId()+list.get(i).getFiName());

//      }

//  }

//  }

}

 

 

UFile.java

UFile.java

package com.ibm.dto;

/**

 * 用户文件类

 * @author 123

 *

 */

public class UFile {

   private int fileId;

   private String fiName;

public int getFileId() {

    return fileId;

}

public void setFileId(int fileId) {

    this.fileId = fileId;

}

public String getFiName() {

    return fiName;

}

public void setFiName(String fiName) {

    this.fiName = fiName;

}

  

}

 

 

 

ShowFileAction.java

ShowFileAction.java

package com.ibm.action;

 

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 com.ibm.dao.FileOpenDAO;

import com.ibm.dto.UFile;

 

public class ShowFileAction extends HttpServlet {

 

    /**

     * Constructor of the object.

     */

    public ShowFileAction() {

        super();

    }

 

    /**

     * Destruction of the servlet.

     */

    public void destroy() {

        super.destroy(); // Just puts "destroy" string in log

        // Put your code here

    }

 

    /**

     * The doGet method of the servlet.

     *

     * This method is called when a form has its tag value method equals to get.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        FileOpenDAO fod = new FileOpenDAO();

        List list=fod.getFileList();

       

        //将文件列表信息存放在request对象中

        request.setAttribute("filelist", list);

       

    RequestDispatcher rd = request.getRequestDispatcher("showfile.jsp");

    //服务器内部转发 将文件列表信息传递到showfile.jsp页面

    rd.forward(request, response);

 

    }

 

    /**

     * The doPost method of the servlet.

     *

     * This method is called when a form has its tag value method equals to post.

     *

     * @param request the request send by the client to the server

     * @param response the response send by the server to the client

     * @throws ServletException if an error occurred

     * @throws IOException if an error occurred

     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out

                .println("");

        out.println("");

        out.println(A Servlet");

        out.println(");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the POST method");

        out.println(");

        out.println("");

        out.flush();

        out.close();

    }

 

    /**

     * Initialization of the servlet.

     *

     * @throws ServletException if an error occurs

     */

    public void init() throws ServletException {

        // Put your code here

    }

 

}

 

 

 

showfile.jsp

showfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@page import="com.ibm.dto.UFile"%>

<%

    List list=(ArrayList)request.getAttribute("filelist");

%>

 

DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

   

    <title>My JSP 'showfile.jsp' starting pagetitle>

   

    <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">

   

 

  head>

 

  <body>

    <%for(UFile file:list){ %>

        <%=file.getFiName() %>

    <%} %>

  body>

html>

 

 

 

上传附件功能代码

upload.html

<html >   

<head>   

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />   

<script type="text/javascript" src="js/jquery-1.3.2.js">script>//注意要导入Jquery的类库   

<script language="javascript">   

$(function(){

    var ei = $("#large");//获取Div   

    ei.hide();  

    $("#img1, img").mousemove(function(e){//img1是 显示 上传图片的缩略图   

//鼠标经过的时候 给div加上 图片

        ei.css({top:e.pageY,left:e.pageX}).html(' + this.src + '" />').show();   

    }).mouseout( function(){

        ei.hide();//否则 就隐藏   

    })

   

    $("#f1").change(function(){ //上传 控件 上传的 预览    

       // $("#img1").attr("src","file:///"+$("#f1").val());   

       $("#showimg").html(' + $("#f1").val() + '" />');

    })

});   

script>   

<style type="text/css">   

    #large{position:absolute;display:none;z-index:999;}   

style>   

head>   

<body>   

 

<form action="upload" method="post" name="upform" id="upform" enctype="multipart/form-data">

 

上传预览图片:<br>   

<input id="f1" name="f1" type="file" /><br>   

 

<input type="text" name="uname" id="uname"/>姓名

<br>

 

<input type="submit" value="上传图片"/>

form>

 

<div id="showimg">div>

<div id="large">div>         

 

body>   

html>

UploadAcion.java

package com.ibm.action;

 

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

 

public class UploadAction extends HttpServlet {

 

 

    public UploadAction() {

        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 {

 

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out

                .println("");

        out.println("");

        out.println(A Servlet");

        out.println(");

        out.print("    This is ");

        out.print(this.getClass());

        out.println(", using the GET method");

        out.println(");

        out.println("");

        out.flush();

        out.close();

    }

 

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

       

        ServletFileUpload upload=new ServletFileUpload(new DiskFileItemFactory());

       

       

        try {

            //获得上传表单中所有传过来的组件

            List list=upload.parseRequest(request);

           

            //组建个数是

            System.out.println("组件个数"+list.size());

           

            for(FileItem fileItem:list){

                //针对file组件的操作

                if(!fileItem.isFormField()){

                   

            System.out.println("文件组件中的文本值名:"+fileItem.getName());

//          System.out.println("组件值是:"+fileItem.getString());

           

            System.out.println("组件名"+fileItem.getFieldName());

           

            String imgupFile=this.getServletContext().getRealPath("myfile");

            System.out.println("文件上传路径:"+imgupFile);

           

            //获得上传的文件名

            String fileName=fileItem.getName();

            fileName=fileName.substring(fileName.lastIndexOf("\\")+1);

           

            //完整的文件存放地址

            String path=imgupFile+File.separator+fileName;

            System.out.println(path);

            //利用fileTtem中的write方法  将本地文件写入到服务器上

            fileItem.write(new File(path));

           

           

            } else{

                //非file组件的操作

//              System.out.println("组件名:"+fileItem.getFieldName());

//              System.out.println("组件值是:"+fileItem.getString());

            }

            }

        } catch (FileUploadException e) {

            e.printStackTrace();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

    public void init() throws ServletException {

        // Put your code here

        System.out.println("123");

    }

 

}

 

 

 

 

 

 

总配置文件

 

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">

 

 

 <context-param>

  <param-name>dbconfigparam-name>

  <param-value>/WEB-INF/db.propertiesparam-value>

 context-param>

 

 

 

 

 

 

 

 

 

 

 

 

 

 <servlet>

  <description>This is the description of my J2EE componentdescription>

  <display-name>This is the display name of my J2EE componentdisplay-name>

  <servlet-name>ReadConfigActionservlet-name>

  <servlet-class>com.ibm.action.ReadConfigActionservlet-class>

  <load-on-startup>1load-on-startup>

 servlet>

 

 <servlet>

  <description>This is the description of my J2EE componentdescription>

  <display-name>This is the display name of my J2EE componentdisplay-name>

  <servlet-name>LoginActionservlet-name>

  <servlet-class>com.ibm.action.LoginActionservlet-class>

 servlet>

 

 <servlet>

  <description>This is the description of my J2EE componentdescription>

  <display-name>This is the display name of my J2EE componentdisplay-name>

  <servlet-name>LogOutActionservlet-name>

  <servlet-class>com.ibm.action.LogOutActionservlet-class>

 servlet>

 

 

  <servlet>

    <description>This is the description of my J2EE componentdescription>

    <display-name>This is the display name of my J2EE componentdisplay-name>

    <servlet-name>ShowFileActionservlet-name>

    <servlet-class>com.ibm.action.ShowFileActionservlet-class>

  servlet>

  <servlet>

    <description>This is the description of my J2EE componentdescription>

    <display-name>This is the display name of my J2EE componentdisplay-name>

    <servlet-name>UploadActionservlet-name>

    <servlet-class>com.ibm.action.UploadActionservlet-class>

  servlet>

 

 

 

 <servlet-mapping>

  <servlet-name>LoginActionservlet-name>

  <url-pattern>/loginurl-pattern>

 servlet-mapping>

 <servlet-mapping>

  <servlet-name>LogOutActionservlet-name>

  <url-pattern>/LogOutActionurl-pattern>

 servlet-mapping>

 <servlet-mapping>

  <servlet-name>ReadConfigActionservlet-name>

  <url-pattern>/readurl-pattern>

 servlet-mapping>

  <servlet-mapping>

    <servlet-name>ShowFileActionservlet-name>

    <url-pattern>/showfileurl-pattern>

  servlet-mapping>

  <servlet-mapping>

    <servlet-name>UploadActionservlet-name>

    <url-pattern>/uploadurl-pattern>

  servlet-mapping>

 

 

 <session-config>

  <session-timeout>1session-timeout>

 session-config>

  

 

 <welcome-file-list>

  <welcome-file>index.jspwelcome-file>

 welcome-file-list>

 

 

 <resource-ref>

    <description>jndidescription>

    <res-ref-name>sqlconnres-ref-name>

    <res-type>javax.sql.DataSourceres-type>

    <res-auth>Containerres-auth>

 resource-ref>

 

 

 <login-config>

  <auth-method>BASICauth-method>

 login-config>

web-app>

 

 


你可能感兴趣的:(java基础学习)