关闭

java 从零开始,学习笔记之基础入门<数据库连接配置>(二十八)

标签: java从零开始入门基础学习笔记
1240人阅读 评论(2) 收藏 举报
分类:

数据库连接配置

配置方式一:

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的配置

 

 <!-- 引用conf\context.xml中所配置的jndi服务 -->

 <resource-ref>

    <description>jndi</description>

    <res-ref-name>sqlconn</res-ref-name>

    <res-type>javax.sql.DataSource</res-type>

    <res-auth>Container</res-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<UFile> getFileList(){

        DataSource ds=null;

        Connection conn=null;

        Statement stmt=null;

        ResultSet rs=null;

        List<UFile> list=null;

        try {

            //获得数据源

            ds=DataSourceFactory.getDataSource();

            conn=ds.getConnection();

            stmt=conn.createStatement();

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

           

            list=new ArrayList<UFile>();

            //循环读取数据  并封装到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<UFile> 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. <br>

     */

    public void destroy() {

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

        // Put your code here

    }

 

    /**

     * The doGet method of the servlet. <br>

     *

     * 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<UFile> 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. <br>

     *

     * 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println(<HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println(<BODY>");

        out.print("    This is ");

        out.print(this.getClass());

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

        out.println(</BODY>");

        out.println("</HTML>");

        out.flush();

        out.close();

    }

 

    /**

     * Initialization of the servlet. <br>

     *

     * @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<UFile> list=(ArrayList)request.getAttribute("filelist");

%>

 

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

<html>

  <head>

   

    <title>My JSP 'showfile.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>

 

  <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('<img style="border:1px solid gray;" src="' + this.src + '" />').show();   

    }).mouseout( function(){

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

    })

   

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

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

       $("#showimg").html('<img id="img1" name="img1" width="120" height="60" src="' + $("#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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

        out.println("<HTML>");

        out.println(<HEAD><TITLE>A Servlet</TITLE></HEAD>");

        out.println(<BODY>");

        out.print("    This is ");

        out.print(this.getClass());

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

        out.println(</BODY>");

        out.println("</HTML>");

        out.flush();

        out.close();

    }

 

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

       

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

       

       

        try {

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

            List<FileItem> 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>dbconfig</param-name>

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

 </context-param>

 

<!--

 <filter>

  <filter-name>CharacterFilter</filter-name>

  <filter-class>com.ibm.filter.CharacterFilter</filter-class>

 </filter>

  -->

 

<!--

 <filter>

  <filter-name>IPFilter</filter-name>

  <filter-class>com.ibm.filter.IPFilter</filter-class>

 </filter>

-->

 

 <!-- 针对所有的请求都拦截 -->

<!--

 <filter-mapping>

  <filter-name>CharacterFilter</filter-name>

  <url-pattern>/*</url-pattern>

 </filter-mapping>

 -->

 

 <!-- 针对所有的请求都拦截 -->

<!--

 <filter-mapping>

  <filter-name>IPFilter</filter-name>

  <url-pattern>/*</url-pattern>

 </filter-mapping>

 -->

 

 <!-- 注册监听器 -->

 <!--

 <listener>

  <listener-class>com.ibm.listenter.SessListenter</listener-class>

 </listener>

 -->

 

 <!--

 <listener>

    <listener-class>com.ibm.listenter.FindFileListener</listener-class>

 </listener>

 -->

 

 

 <servlet>

  <description>This is the description of my J2EE component</description>

  <display-name>This is the display name of my J2EE component</display-name>

  <servlet-name>ReadConfigAction</servlet-name>

  <servlet-class>com.ibm.action.ReadConfigAction</servlet-class>

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

 </servlet>

 

 <servlet>

  <description>This is the description of my J2EE component</description>

  <display-name>This is the display name of my J2EE component</display-name>

  <servlet-name>LoginAction</servlet-name>

  <servlet-class>com.ibm.action.LoginAction</servlet-class>

 </servlet>

 

 <servlet>

  <description>This is the description of my J2EE component</description>

  <display-name>This is the display name of my J2EE component</display-name>

  <servlet-name>LogOutAction</servlet-name>

  <servlet-class>com.ibm.action.LogOutAction</servlet-class>

 </servlet>

 

 

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>ShowFileAction</servlet-name>

    <servlet-class>com.ibm.action.ShowFileAction</servlet-class>

  </servlet>

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>UploadAction</servlet-name>

    <servlet-class>com.ibm.action.UploadAction</servlet-class>

  </servlet>

 

 

 

 <servlet-mapping>

  <servlet-name>LoginAction</servlet-name>

  <url-pattern>/login</url-pattern>

 </servlet-mapping>

 <servlet-mapping>

  <servlet-name>LogOutAction</servlet-name>

  <url-pattern>/LogOutAction</url-pattern>

 </servlet-mapping>

 <servlet-mapping>

  <servlet-name>ReadConfigAction</servlet-name>

  <url-pattern>/read</url-pattern>

 </servlet-mapping>

  <servlet-mapping>

    <servlet-name>ShowFileAction</servlet-name>

    <url-pattern>/showfile</url-pattern>

  </servlet-mapping>

  <servlet-mapping>

    <servlet-name>UploadAction</servlet-name>

    <url-pattern>/upload</url-pattern>

  </servlet-mapping>

 

 <!-- 配置session "1"是一分钟的意思-->

 <session-config>

  <session-timeout>1</session-timeout>

 </session-config>

  

 

 <welcome-file-list>

  <welcome-file>index.jsp</welcome-file>

 </welcome-file-list>

 

 <!-- 引用conf\context.xml中所配置的jndi服务 -->

 <resource-ref>

    <description>jndi</description>

    <res-ref-name>sqlconn</res-ref-name>

    <res-type>javax.sql.DataSource</res-type>

    <res-auth>Container</res-auth>

 </resource-ref>

 

 

 <login-config>

  <auth-method>BASIC</auth-method>

 </login-config>

</web-app>

 

 


2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:88497次
    • 积分:1575
    • 等级:
    • 排名:千里之外
    • 原创:54篇
    • 转载:19篇
    • 译文:0篇
    • 评论:52条
    文章分类