package com.study.blog;import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;public class GetBlogServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id"); DataSource ds = null;
try {
Context ctx = new InitialContext(); // 得到初始化上下文
Object obj = ctx.lookup("java:/comp/env/jdbc/mysqlds");// 查找连接池
ds = (DataSource) obj;
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} String sql = "select id,title,label,categoryid,textarea,createdtime from createblog where id ="
+ id;
QueryRunner qr = new QueryRunner(ds);
try {
List<Blog> list = (List<Blog>) qr.query(sql, new BeanListHandler(
Blog.class)); Blog blog = list.get(0);
                        //显示Blog的内容
System.out.println(blog.getId());
System.out.println(blog.getTitle());
System.out.println(blog.getLabel());
System.out.println(blog.getCategoryId());
System.out.println(blog.getTextArea());
System.out.println(blog.getCreatedTime());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Blog类的定义:package com.study.blog;import java.util.Date;public class Blog {
private int id;
private String title;
private String label;
private String categoryId;
private String textArea;
private Date createdTime; public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getLabel() {
return label;
} public void setLabel(String label) {
this.label = label;
} public String getCategoryId() {
return categoryId;
} public void setCategory(String categoryId) {
this.categoryId = categoryId;
} public String getTextArea() {
return textArea;
} public void setTextArea(String textArea) {
this.textArea = textArea;
} public Date getCreatedTime() {
return createdTime;
}}
结果是这样的:
16
第一片博客
博客 心情
null
<p>我是</p>
null每次categoryId和createdTime都是为NULL,但其他几个值是正常的,数据库里都是有值的。想了很久还是没找出原因,大家帮忙看看吧。谢了。。