如何从servlet显示包含数据库信息的网页?

时间:2016-01-05 10:11:37

标签: java html servlets web-applications

我试图从数据库中检索并打印名字,姓氏和地址,然后显示它。我有下面的servlet,有人可以帮助我,谢谢:)我是否必须使用html?

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class PersonalInfoOutput extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();

            String firstname = request.getParameter("firstname");
            String lastname = request.getParameter("lastname");
            String address = request.getParameter("address");
            boolean st = false;
            try { 
                Class.forName("com.mysql.jdbc.Driver").newInstance(); 
                Connection con =    DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", ""); 
                PreparedStatement ps = con.prepareStatement("select FirstName, LastName, Address from payroll_system.employee_info where employeeID = 1234"); 
                ResultSet rs = ps.executeQuery(); 
                st = rs.next(); 
                if(st){
                out.println(firstname);

                }
             }catch(Exception e)
              {
                  e.printStackTrace();
              }
            out.close();
    }
}

我收到的输出是:

null

1 个答案:

答案 0 :(得分:-1)

使用特殊处理。关闭对象。请查看以下示例并尝试调试更多:http://www.javawebtutor.com/articles/servlets/servlet_db_example.html