package com.hailong.link;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetAllCitys extends HttpServlet{
/**
* 尹海龙
*/
private static final long serialVersionUID = 1L;
private String dbUser = "root";//声明数据库用户名
private String dbPassword = "1234";//声明数据库连接密码
private String dbDriver = "com.mysql.jdbc.Driver";//声明数据库驱动
private String dbConnection = "jdbc:mysql://localhost:3306/pclink";//声明数据库连接
private Connection con;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
System.out.println("没有发现数据库驱动程序!");
}
try {
con = DriverManager.getConnection(dbConnection,dbUser,dbPassword);
System.out.println("数据库驱动加载成功!");
} catch (SQLException e) {
System.out.println("创建数据库连接失败!");
}
}
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String idStr = request.getParameter("parent_id");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
int parent_id;
if(idStr != null && !"".equals(idStr)){
parent_id = Integer.parseInt(idStr);
}else{
parent_id = 1;
}
String sql = "select id,content from pclink where parent_id = ?";
try {
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1,parent_id);
ResultSet rs = pstmt.executeQuery();
StringBuffer allCitys = new StringBuffer();
response.setContentType("text/xml");
allCitys.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
allCitys.append("<allCitys>");
while (rs.next()) {
allCitys.append("<city>");
allCitys.append("<cityId>"+rs.getInt("id")+"</cityId>");
allCitys.append("<cityName>"+rs.getString("content")+"</cityName>");
allCitys.append("</city>");
}
allCitys.append("</allCitys>");
out.print(allCitys.toString());
} catch (SQLException e) {
System.out.println("执行出现异常!");
}
}
public void destroy() {
super.destroy();
}
}
- 1
- 2
- 3
- 4
- 5
前往页