简体   繁体   English

在java中生成随机否的问题

[英]problem generating random no in java

i have written a code like this but it is giving exceptions.actually i want to generate a random value.save into the database and return the same to the user 我写了这样的代码,但它给出了exceptions.actually我想生成一个随机值。保存到数据库中并将其返回给用户

import java.math.BigInteger;
import java.security.SecureRandom;

public static String recoverpassword(String uid,String ans) {
    try {
        verifyans.setString(1,uid);
        verifyans.setString(2,ans);
        ResultSet resultSet = verifyans.executeQuery();

        if (resultSet.next()) {
            SecureRandom random = new SecureRandom();
            String newpass = new BigInteger(130, random).toString(32);
            resetpass.setString(1,newpass);
            resetpass.setString(2,uid);
            resetpass.executeUpdate();                          
            return newpass;
        } else {
            return "xxx";
        }

    } catch(Exception e) {
        System.out.println("exception" +e);
        e.printStackTrace();
        return "xxx";
    }
}

im getting null pointer exceptions like: 我得到空指针异常,如:

com.ibm.lims.Users@1d193c9]
exceptionjava.lang.NullPointerException
java.lang.NullPointerException
    at org.tranql.connector.jdbc.ConnectionHandle.connectionError(ConnectionHandle.java:103)
    at org.tranql.connector.jdbc.PreparedStatementHandle.executeUpdate(PreparedStatementHandle.java:105)
    at com.ibm.lims.LimsHandler.recoverpassword(LimsHandler.java:940)
    at org.apache.jsp.recoverpasswordresult_jsp._jspService(recoverpasswordresult_jsp.java:78)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.geronimo.tomcat.valve.DefaultSubjectValve.invoke(DefaultSubjectValve.java:56)
    at org.apache.geronimo.tomcat.GeronimoStandardContext$SystemMethodValve.invoke(GeronimoStandardContext.java:406)
    at org.apache.geronimo.tomcat.valve.GeronimoBeforeAfterValve.invoke(GeronimoBeforeAfterValve.java:47)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:567)
    at org.apache.geronimo.tomcat.valve.ThreadCleanerValve.invoke(ThreadCleanerValve.java:40)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    at java.lang.Thread.run(Unknown Source)

hey i tested the code removing those securerandom class call.i just passed a string value in double quotes like "sample" and it worked. 嘿,我测试了删除那些securerandom类call.I的代码,我只是在双引号中传递了一个字符串值,例如“ sample”,并且它起作用了。 means the problem is with the securerandom class.i think the value is going as an integer in a string value field so database server is sending exception. 意味着问题出在securerandom类上。我认为该值在字符串值字段中以整数形式出现,因此数据库服务器正在发送异常。 plz give me some code to generate random string alternatively – 请给我一些代码来生成随机字符串-

There are several problems playing a role here. 有几个问题在这里起作用。

First the root cause of the NPE: 首先,NPE的根本原因是:

java.lang.NullPointerException
    at org.tranql.connector.jdbc.ConnectionHandle.connectionError(ConnectionHandle.java:103)

This is clearly a bug in the TranQL JDBC driver. 这显然是TranQL JDBC驱动程序中的错误。 There was some unexpected null pointer during the ConnectionHandle#connectionError() method so that it was unable to handle the actual connection error. ConnectionHandle#connectionError()方法期间,出现了一些意外的空指针,因此它无法处理实际的连接错误。 To fix this particular problem (so that you don't get a NPE, but a more clear and driver-specific SQLException ), either upgrade the driver or replace it by a more decent one (I've never heard of TranQL before). 要解决此特定问题(以免获得NPE,而是获得更清晰和特定于驱动程序的SQLException ),请升级驱动程序或将其替换为更合适的驱动程序(之前我从未听说过TranQL)。

As to the real cause of the whole problem; 至于整个问题的真正原因; judging from the stacktrace it look like that there's no means of an active connection. 从stacktrace来看,看起来好像没有活动的连接。 Judging from the non-threadsafe code it look like that the preparedStatement was already used before and has somehow implicitly been closed / detached from the connection. 从非线程安全的代码来看,似乎prepareStatement之前已经使用过,并且已隐式关闭/从连接分离。

At least it clearly boils down to the non-threadsafe and non-resourceleak-safe JDBC code you have there. 至少它显然可以归结为您拥有的非线程安全和非资源泄漏安全的JDBC代码。 The normal JDBC idiom is that you should always acquire and close the Connection , PreparedStatement and ResultSet in the shortest possible scope . 通常的JDBC习惯是,您应始终在尽可能短的范围内获取关闭ConnectionPreparedStatementResultSet Thus, already inside the very same (non-static!) method block. 因此,已经在非常相同的(非静态!)方法块中。 The statement and resultset should never be shared among threads. 决不要在线程之间共享该语句和结果集。 The connection can be, but you shouldn't take it in your own hands. 连接可以,但您不应该自己掌握。 Use a decent connection pool API for this, eg C3P0. 为此,使用一个体面的连接池API,例如C3P0。

Here's an example according the ideal JDBC idiom: 这是根据理想的JDBC习惯用法的示例:

public String recoverPassword(Long userId, String answer) throws SQLException {
    Connection connection = null;
    PreparedStatement verifyAnswer = null;
    ResultSet resultSet = null;
    String newPassword = null;
    PreparedStatement resetPassword = null;

    try {
        connection = database.getConnection();
        verifyAnswer = connection.prepareStatement(SQL_VERIFY_ANSWER);
        verifyAnswer.setLong(1, userId);
        verifyAnswer.setString(2, answer);
        resultSet = statement.executeQuery();

        if (resultSet.next()) {
            SecureRandom random = new SecureRandom();
            newPassword = new BigInteger(130, random).toString(32);
            resetPassword = connection.prepareStatement(SQL_RESET_PASSWORD);
            resetPassword.setString(1, newPassword);
            resetPassword.setLong(2, userId);
            resetPassword.executeUpdate();                          
        }
    } finally {
        // Always free resources in reversed order.
        if (resetPassword != null) try { resetPassword.close(); } catch (SQLException logOrIgnore) {}
        if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
        if (verifyAnswer != null) try { verifyAnswer.close(); } catch (SQLException logOrIgnore) {}
        if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
    }

    return newPassword;
}

Note that I hinted the userId to be a Long . 请注意,我提示userIdLong You really don't want to have String ID's in both your code and datamodel. 您确实不希望在代码和数据模型中都具有String ID。 You can find more information, hints and other examples about writing solid JDBC code here . 您可以在此处找到有关编写可靠JDBC代码的更多信息,提示和其他示例。

That said, the following part of the stacktrace 也就是说,堆栈跟踪的以下部分

at com.ibm.lims.LimsHandler.recoverpassword(LimsHandler.java:940)
at org.apache.jsp.recoverpasswordresult_jsp._jspService(recoverpasswordresult_jsp.java:78)

implies that you're writing raw Java code in a JSP file using the old-fashioned scriptlets. 这意味着您正在使用老式脚本集在JSP文件中编写原始Java代码。 To save future maintenance and debugging problems, I would strongly recommend you not to do so, but just use a Servlet class for that. 为了节省将来的维护和调试问题,我强烈建议您不要这样做,而只需使用Servlet类即可。

Have you tried stepping through this with a debugger? 您是否尝试过使用调试器逐步解决此问题?

From the code posted it looks like maybe uid is being passed in as null at the top of the method. 从发布的代码来看,似乎在方法顶部将uid作为null传入。

You also shouldn't store passwords as plain text in the database, you should use a salted one-way hash of the password instead. 您也不应将密码以纯文本格式存储在数据库中,而应使用密码的盐化单向哈希值。

The problem you have is not related to random gen of number. 您遇到的问题与随机数生成无关。 You might take a look at you DB connection parameters, at the sql request you are trying to execute, ... But please, be more specific "I'm getting NPE" is not a question :) 您可能会看一下您的数据库连接参数,正在尝试执行的sql请求,但是,请更具体地讲“我正在获得NPE”不是问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM