连接池、数据源、文件上传

java连接池


首先在tomcat中的conf中的context.xml文件中找到 中加入代码

导入的包

<%@page import="javax.naming.InitialContext"%>
<%@page import="javax.naming.Context"%>


jsp中的代码
<%
    Context ctx= new InitialContext();
    String name= (String)ctx.lookup("java:comp/env/tjndi");
    out.print(name);
      %>


连接池资源





        maxActive="100" maxIdle="30" maxWait="10000" username="newsu"
      password="123456" driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://127.0.0.1:3306/newsmanagersystem?
              useUnicode=true&characterEncoding=utf-8" />



baseDao中代码


package com.bdqn.dao;


import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
  * 连接池
  * @author Administrator
  *
  */
public class BaseDao {
//数据源,获取数据连接
public Connection getConnection(){
Connection connection=null;
try {
Context cxt=new InitialContext();

DataSource ds=(DataSource) cxt.lookup("java:comp/env/jdbc/dept");
connection = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}

return connection;
}
//关闭资源
public void close(Connection connection,Statement st,ResultSet rs){
try {
if(rs != null){
rs.close();
}
if (st !=null) {
st.close();
}
if (connection !=null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}








servlet文件上传

当前页(index.jsp)

      用户名
      文件
     
     



跳转页(login.jsp)

<%@page import="java.io.File"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>




<%
//设置编码格式
request.setCharacterEncoding("UTF-8");

//上传文件的路径

String uploadPath=request.getSession().getServletContext().getRealPath("upload");


//检查请求类型
boolean flag = ServletFileUpload.isMultipartContent(request);


if (flag) {
//创建Item文件工厂
FileItemFactory fileItemFactory = new DiskFileItemFactory();
//文件上传API的类
ServletFileUpload servletFileUpload = new ServletFileUpload(
fileItemFactory);
//获取文件上传的一个集合
List list = servletFileUpload.parseRequest(request);

//将集合转化为迭代器
Iterator iterator = list.iterator();

while(iterator.hasNext()){
//上传数据
FileItem fileItem=iterator.next();

//判断数据类型(是否是文件类型)
if(fileItem.isFormField()){

}else{
//创建文件对象,传参数
File file=new File(fileItem.getName());
//将文件存入相应的地址中
File uploadFile=new File(uploadPath,file.getName());

//将页面读取的文件存到upload文件下

fileItem.write(uploadFile);

}
}

}else{
out.print("上传失败");
}
%>

你可能感兴趣的:(jdbc,java,jsp)