2 telen0928 telen0928 于 2013.08.12 08:03 提问

servlet部署到服务器上运行的时候,在网页里一直显示failed,下面是代码

package com.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**

  • Servlet implementation class LoginServlet
    */
    public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**

    • @see HttpServlet#HttpServlet() */ public LoginServlet() { super(); // TODO Auto-generated constructor stub }

    /**

    • @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
      */
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      // TODO Auto-generated method stub
      Connection conn;
      PreparedStatement sql;
      ResultSet rs;
      try
      {
      Class.forName("com.mysql.jdbc.Driver");
      }
      catch (Exception e)
      {
      System.out.print(e);
      }
      String username = request.getParameter("username");
      String password = request.getParameter("password");
      response.setContentType("text/html");
      response.setCharacterEncoding("utf-8");
      PrintWriter out = response.getWriter();
      String msg = null;
      String uri="jdbc:mysql://localhost:3306/monitordb?"+"user=root&password=123456";
      String selectsql = "select username,password from user where username=? and password=?";

      if(username!=null&&password!=null)
      {
      msg = "success";

      try
      {
      //String url = "jdbc:mysql://localhost:8080/monitordb";
      String insertSql = "insert into user values(?,?)";
      conn = DriverManager.getConnection(uri);
      sql = conn.prepareStatement(insertSql);
      sql.setString(1,username);
      sql.setString(2,password);
      int status = sql.executeUpdate();
      if(status!=0)
      {
      System.out.print("添加数据成功!");
      }else
      {
      System.out.print("添加数据失败");
      }
      conn.close();
      }
      catch (SQLException e)
      {
      System.out.print(e);
      }
      }else
      {
      msg = "failed";
      }
      out.print(msg);
      out.flush();
      out.close();
      }

    /**

    • @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response);

    }

}

2个回答

u011603124
u011603124   2013.08.12 09:01

也许是你的用户名和密码根本就没有从数据库获取到;
PreparedStatement sql;我感觉有问题
我是这样做的PreparedStatement sql=null;

jinandmei
jinandmei   2013.08.12 10:00

一般像连接数据库这样的,你可以放在init里面进行初始化,关于问题就是failed应该是有后台日志的。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!