servlet+jdbc整合web工程
阿新 • • 發佈:2018-11-15
最基本的web工程,需要的jar包只有資料庫驅動
mysql-connector-java-5.1.21.jar
jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306\/test
username=root
passwd=123456
web.xml
webservlet 3.0之後兩種方式配置
1、原始的web.xml配置
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class >com.servlet.controller.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test/testServlet</url-pattern>
</servlet-mapping>
2、註解配置
@WebServlet(name=”testServlet”, urlPatterns={“/test/testServlet”},loadOnStartup=1)
public class HelloServlet extends HttpServlet
{}
注意:註解的方式在tomcat6下無效,換成tomcat7才可以,可能版本原因
持久化類
JdbcUtils
package com.servlet.dao;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql .ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class JdbcUtils
{
private String driver = "";
private String url = "";
private String username = "";
private String passwd = "";
private ResultSet rs = null;
private Connection coo = null;
JdbcUtils JdbcUtils = null;
public JdbcUtils()
{
System.out.println(System.getProperty("user.dir"));///D:\soft\tomcat-6.0.28\bin
System.out.println(this.getClass().getResource("").getPath());///D:/soft/tomcat-6.0.28/webapps/servletj/WEB-INF/classes/com/servlet/dao/
try
{
if(null==coo)
{
Properties properties = new Properties();
URL o = Thread.currentThread().getContextClassLoader().getResource("");
String path = o.getPath().replace("classes", "config");
BufferedReader bufferedReader = new BufferedReader(new FileReader(path+"/jdbc.properties"));
properties.load(bufferedReader);
//Class.forName("com.mysql.jdbc.Driver");
driver = properties.getProperty("driver");
Class.forName(driver);
url = properties.getProperty("url");
username = properties.getProperty("username");
passwd = properties.getProperty("passwd");
try {
coo = DriverManager.getConnection(url, username, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
catch(Exception e)
{
System.out.println("結果集解析出錯:"+e.getMessage());
}
}
//查詢
public List<Map<String,String>> queryCommand(String sql,String[] parameters)
{
List list = new ArrayList();
ResultSet rs = getRs(sql,parameters);
try
{
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
HashMap<String, String> map =new HashMap<String,String>();
for(int i=1;i<=rsmd.getColumnCount();i++)
{
map.put(rsmd.getColumnLabel(i), String.valueOf(rs.getObject(i)));
}
list.add(map);
}
} catch (SQLException e) {
System.out.println("結果集解析出錯:"+e.getMessage());
}
return list;
}
private ResultSet getRs(String sql,String[] parameters)
{
try {
PreparedStatement ps = coo.prepareStatement(sql);
if(parameters!=null)
{
for(int i=0;i<parameters.length;i++)
{
ps.setString(i+1, parameters[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e){
System.out.println("結果集解析出錯:"+e.getMessage());
}
return rs;
}
}
HelloDao
/**
*
*/
package com.servlet.dao;
import java.util.List;
import java.util.Map;
/**
* @author 44306
*
*/
public class HelloDao
{
JdbcUtils utils = new JdbcUtils();
public List<Map<String, String>> query()
{
String sql = "select * from users where id=?";
String[] parameters = {"1"};
List<Map<String, String>> map= utils.queryCommand(sql, parameters);
return map;
}
}
servlet類
/**
*
*/
package com.servlet.controller;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.servlet.dao.HelloDao;
/**
* @author 44306
*
*/
@WebServlet(name="testServlet", urlPatterns={"/test/testServlet"},loadOnStartup=1)
public class HelloServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
HelloDao dao = new HelloDao();
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
System.out.println("servlet初始化...");
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
List<Map<String, String>> list = dao.query();
PrintWriter out = null;
System.out.println("list:"+list.toString());
try {
out = response.getWriter();
out.write(list.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
out.flush();
out.close();
}
}