运行Servlet时收到错误消息(第1行:'密码'附近的语法错误。)

时间:2012-05-08 09:02:38

标签: java java-ee

我正在使servlet与J2ME一起工作,但每当运行这个时都会收到以下错误消息。

错误:

  

java.sql.SQLException:[Microsoft] [ODBC SQL Server驱动程序] [SQL   服务器]第1行:'密码'附近的语法不正确。)

public class GetNpostServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) 
                     throws ServletException, IOException
{
// Same code appears in doPost()
// Shown both places to emphasize that data is received thru
// different means (environment variable vs stream), 
// yet processed the same inside the servlet
String acct = req.getParameter("account"),
        pwd = req.getParameter("password");    

String balance = accountLookup(acct, pwd);

if (balance == null)
{
  res.sendError(HttpServletResponse.SC_BAD_REQUEST, 
 "Unable to locate  account.");            
  return;
}

res.setContentType("text/plain");    
PrintWriter out = res.getWriter();
out.print(balance);
out.close();
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) 
                    throws ServletException, IOException
{
// Same code appears in doGet()
// Shown both places to emphasize that data is received thru
// different means (stream vs environment variable), 
// yet processed the same inside the servlet
String acct = req.getParameter("account"),
        pwd = req.getParameter("password");    

String balance = accountLookup(acct, pwd);

if (balance == null)
{
  res.sendError(HttpServletResponse.SC_BAD_REQUEST, 
"Unable to locate account.");            
  return;
}

res.setContentType("text/plain");    
PrintWriter out = res.getWriter();
out.print(balance);
out.close();
}

/*--------------------------------------------------
 * Lookup bank account balance in database
 *-------------------------------------------------*/
private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuilder msgb = new StringBuilder("");

try
{
  // These will vary depending on your server/database      
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");  
  con = DriverManager.getConnection("jdbc:odbc:acctInfo");

  Statement stmt = con.createStatement();
  ResultSet rs = stmt.executeQuery(
                     "Select balance from acctInfo where account = " +
                     acct + "and password = '" + pwd + "'");      

  if (rs.next())
    return rs.getString(1);
  else
    return null;
   }
   catch (Exception e)
   {                  
    return e.toString();
    }
    }

    }

1 个答案:

答案 0 :(得分:5)

最直接的问题:你没有引用acct字符串,之后没有空格,所以你最终会得到类似的结果:

Select balance from acctInfo where account = fredand password = 'bloggs'

更多重要的问题:您不应该首先在SQL中包含值。您应该使用参数化SQL。目前,您的代码向SQL injection attacks开放。

进一步的安全问题:您的代码表明密码是以纯文本形式保存的。请不要这样做。

设计问题:

  • 您似乎将帐户余额视为字符串。那很奇怪。 BigDecimal将是一种更自然的表现形式。
  • 您正在捕捉Exception而不是特定的例外
  • 您正在返回异常字符串表示,就像它是帐户余额一样。哎呀!你可能实际上只是让SQLException冒泡到呼叫者
  • 您永远不会关闭连接,声明或结果集