如何在eclipse中连接servlet程序和数据库(mysql)?

时间:2015-02-16 17:15:52

标签: java html eclipse servlets jdbc

import java.sql.*;

import java.io.*;

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 java.awt.*;



@WebServlet("/JDBCServlet")

public class JDBCServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;



    public JDBCServlet() {

        super();

        // TODO Auto-generated constructor stub

    }


protected void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        String uname,pwd;

        uname=request.getParameter("t1");

        pwd=request.getParameter("t2");

        PrintWriter out=response.getWriter();

        response.setContentType("text/html");

        try{

            Class.forName("com.mysql.jdbc.Driver").newInstance();

            Connection con=DriverManager.getConnection
                    ("jdbc:mysql//localhost:3306/school","t1","t2");

            System.out.println("driver is connected");

            Statement st=con.createStatement();

            ResultSet rs=st.executeQuery("select * from student");

        out.println("<html><head><title>DATABASE_RESULT</title></head><body>");

out.println("<tr><td>ROLL_NO=</td><td>FIRST_NAME</td><td>LAST_NAME</td><td>"+"CLASS_NAME</td></tr>");

                while(rs.next()){

                    out.println("<tr><td>"+rs.getInt(1)+"</td></tr>");

                    out.println("<tr><td>"+rs.getString(2)+"</td></tr>");

                    out.println("<tr><td>"+rs.getString(3)+"</td></tr>");

                    out.println("<tr><td>"+rs.getInt(4)+"</td></tr>");

                }

                out.println("</body></html>");

        }catch (Exception e){
             System.out.println("exception occured");
            e.printStackTrace();

            }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse 
response) throws ServletException, IOException {

    }



}

和html标签是

在此处插入标题

<form method="get" action="JDBCServlet">

    USER_NAME<input type="text" name="t1" value="" ><br>

    USER_PASSWORD<input type="password" name="t2" value = ""><br>

    <input type="submit" name="login" value="login">

</form>

输出(例外) - &gt;

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at JDBCServlet.doGet(JDBCServlet.java:32)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

我已经编写了单独的db程序和servlet程序,但是当我在单个程序中编写它时却没有。请回答。

4 个答案:

答案 0 :(得分:0)

您尚未说明您获得的例外情况,这对任何人来说都非常重要。 假设异常是ClassNotFound / NoClassDefFoundError,那么 可能性是你没有在类路径中设置mysql-connector jar。如果您这样做,它可能会解决问题。 祝你好运。

答案 1 :(得分:0)

中删除.newInstance()

Class.forName("com.mysql.jdbc.Driver").newInstance();

因为它不是必需的,并且还记得你在类路径中有mysql-connecter.jar

答案 2 :(得分:0)

这可能对您有所帮助

首先是jsp页面

<%@ page language="java" 
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
    <title>Login Page</title>
</head>

<body>
    <form action="LoginServlet">

        Please enter yopur username         
        <input type="text" name="un"/><br>      

        Please enter your password
        <input type="text" name="pw"/>

        <input type="submit" value="submit">            

    </form>
</body>

LoginServlet

package examplepackage;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

 /**
 * Servlet implementation class LoginServlet
 */
 public class LoginServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response) 
                   throws ServletException, java.io.IOException {

try
{       

 UserBean user = new UserBean();
 user.setUserName(request.getParameter("un"));
 user.setPassword(request.getParameter("pw"));

// user = UserDAO.login(user);
 UserDAO obj=new UserDAO();
 int k=obj.loginCheck(user);
 if(k==1)
 {
     response.sendRedirect("userLogged.jsp"); //logged-in page    

 }
 else
 {

      response.sendRedirect("invalidLogin.jsp"); //error page 
 }

 /*
  if (user.isValid())
  {

      HttpSession session = request.getSession(true);       
      session.setAttribute("currentSessionUser",user); 
      response.sendRedirect("userLogged.jsp"); //logged-in page             
  }

  else 
      response.sendRedirect("invalidLogin.jsp"); //error page 

*/
 } 


 catch (Throwable theException)         
{
 System.out.println(theException); 
 }
   }
 }

和豆

package examplepackage;

public class UserBean {

private String username;
private String password;
public String getPassword() {
   return password;
}

public void setPassword(String newPassword) {
   password = newPassword;
}


public String getUsername() {
   return username;
        }

public void setUserName(String newUsername) {
   username = newUsername;
        }
}

DAO

 public class UserDAO   
 {

Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;

public UserDAO()
{
    try{

        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost/db_sampleservlet","root","root");




    }catch(Exception e)
    {

        System.out.println("Error in connection"+e);
    }
}
    public int loginCheck(UserBean bean)
    {

        String u=bean.getUsername();
        String p=bean.getPassword();
        int flag=0;

        try{
            ps=con.prepareStatement("select * from tbl_login where username=? and password=?");
            ps.setString(1, u);
            ps.setString(2, p);
            rs=ps.executeQuery();
            while(rs.next())
            {

                flag=1;
            }

        }catch(Exception e){

            System.out.println("Error in loginCheck"+e);
        }
        return flag;

    }
  }

注意:驱动程序类加载所需的MysqlConnector .jar文件(com.mysql.jdbc.Driver)

这是一个非常简单的架构,这可能对你有帮助

答案 3 :(得分:0)

我犯了很多错误。

1&GT; Connection con = DriverManager.getConnection                     ( “JDBC:MySQL的本地主机//:3306 /学校”, “T1”, “T2”);  代替“t1”和“t2”将有uname和pwd。 而且我错过了':'。 因此声明将是

Connection con = DriverManager.getConnection                     ( “JDBC:MySQL的://本地主机:3306 /学校”,UNAME,PWD);

2 - ;我也没有正确导入驱动程序         在这里,我错过了复制mysql.jar并将其捕获到WebContent / WEB-INF / lib中。

感谢朋友的支持.........