Что не так с SQL statmenr в методе isuservalid и if (valid ==true) statment
Когда я запускаю файл, он продолжает говорить null, когда их значения в базе данных. Кроме того, Кис говорит, что недопустимо в консоли, когда используется допустимый тег, он продолжает выводить недопустимый на консоль. Можете ли вы дайте мне знать, в чем проблема, пожалуйста.
Смотрите код ниже;
*/ // Creating web servlet for RFIDDao and creating public class which extends HttpServlet @WebServlet("/RFIDDao") public class RFIDDao extends HttpServlet { // Creating private static final serialVersionUID private static final long serialVersionUID = 1L; // Declaring GSON utility object // Connection = null and statement. Gson gson = new Gson(); Connection conn = null; static Statement stmt; public static final String userid = "16038287"; // change this to be your student-id // Creating topic for the server public static final String TOPIC_SERVER = userid + "/server"; public static final String BROKER_URL = "tcp://iot.eclipse.org:1883"; //private MqttClient client; // Creating public void init method for ServletConfig which throws ServletException public void init(ServletConfig config) throws ServletException { // init method is run once at the start of the servlet loading // This will load the driver and establish a connection super.init(config); // Adding the mysql workbench username and assword, in order to connect to the database String user = "rashidd"; String password = "rooSedef6"; // Usiing port 6306 instead of 3306 and connecting to the mudfoot server String url = "jdbc:mysql://mudfoot.doc.stu.mmu.ac.uk:6306/rashidd"; // Loading the database driver try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { System.out.println(e); } // close catch exception e // Creating try to get a connection with the user/pass try { conn = DriverManager.getConnection(url, user, password); // Print messages out onto the console System.out.println("Sensor to DB server is up and running\n"); System.out.println("Upload sensor data with http://localhost:8080/IOTServer/RFIDDao?sensorname=xxx&sensorvalue=nnn"); System.out.println("View last sensor reading at http://localhost:8080/IOTServer/RFIDDao?getdata=true\n\n"); // System.out.println("DEBUG: Connection to database successful."); stmt = conn.createStatement(); //System.out.println("debug: Statement created " + stmt); } catch (SQLException se) { se.printStackTrace(); System.out.println(se); System.out.println("\nDid you alter the lines to set user/password in the sensor server code?"); } // Close catch sql exception } // init() // Creating destroy method public void destroy() { try { conn.close(); } catch (SQLException se) { System.out.println(se); } // Close catch sql exception se } // destroy() /*** * Creating rfiddao method, * Super is a method which is used inside a sub-class method, to call a method in the super class. * Private method of the super-class would not be called. * Only public and protected methods can be called by the super keyword. * It is also used by class constructors to invoke constructors of its parent class. */ public RFIDDao() { // Calling the super method super(); /*try { client = new MqttClient(BROKER_URL, userid+"-server_publisher"); // create mqtt session MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); options.setWill(client.getTopic(userid + "/LWT"), "I'm gone :(".getBytes(), 0, false); client.connect(options); } catch (MqttException e) { System.out.println("mqtt"); e.printStackTrace(); System.exit(1); }*/ } // Close public RFIDDao method /** * Creating do get method, to insert data into the database. * Then retrieve the data, depending on sensorname * Creating suser valid method which would then check if valid user is using valid tag to open the door. * getAllDoorLockStatus * Retrieve all RFID Data. * @return * @throws SQLException */ // doGet is a method which supports the servlet HTTP GET requests protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setStatus(HttpServletResponse.SC_OK); // Declare a SensorData object to hold the incoming data SensorData oneSensor = new SensorData("unknown", "unknown"); // Check to see whether the client is requesting data or sending it String getdata = request.getParameter("getdata"); ServletRequest req = null; // SensorData sensordata = null; // if no getdata parameter, client is sending data if (getdata == null) { // getdata is null, therefore it is receiving data // Extracting the parameter data holding the sensordata String sensorJsonString = request.getParameter("sensordata"); // Extracting the parameter data holding the sensorname String data = request.getParameter("sensorname"); // Creating boolean for is user valid boolean valid = isUserValid(data); // If valid userhas been used return valid user/tag and door open if (valid == true) { System.out.println("valid user/tag"); // Creating new sensor data object oneSensor = new SensorData(data, "Door open", "16038287"); // send command to open the door PrintWriter writer = new PrintWriter(response.getOutputStream()); writer.write("true"); // Writer = true writer.close(); } // Otherwise, return invalid user/tag and door closed else { System.out.println("invalid user/tag"); oneSensor = new SensorData(data, "Door closed", "16038287"); } // Close else // Problem if sensordata parameter not sent, or is invalid json if (sensorJsonString != null) { // Converting the json string to an object of type SensorData // Also, calling the sensordata class oneSensor = gson.fromJson(sensorJsonString, SensorData.class); // Update sensor values and send back response PrintWriter out = response.getWriter(); // Calling the updateSensorTable method try { updateSensorTable(oneSensor); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } out.close(); // close out } // endif sensorJsonString not null } // end if getdata is null else { // Otherwise retrieve and return data in json format // retrive data sensor by sensorname parameter String sensorname = request.getParameter("sensorname"); if (sensorname != null) { PrintWriter out = response.getWriter(); out.println(retrieveSensorData(sensorname)); out.close(); } } // CLose else } // CLose protected void doget method // Creating do post method //doPost is used for HTTP POST requests protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Post is same as Get, so pass on parameters and do same doGet(request, response); } // CLose protected void dopost /** * Creating boolean to check if a valid user is trying to open the door, using specific sensor name (tagid) = 1600ee15e9 * Selecting everything from the door lock valid table where the id is '1600ee15e9' * This will then check in the second table if its valid user or not and then reutrn success message. * A tag data object is an instance of a class. * @param sensorname * @return */ public boolean isUserValid(String sensorname) { // Creating tag data object TagData oneSensor = new TagData("1600ee15e9", "VALID TAG", "Room101"); try { // select everything from the door lock valid table where the sensorname is valid tag 9sensorname) // String sql = "SELECT sensorname FROM doorlockValid WHERE sensorname = '"+sensorname+"'"; String sql = "SELECT * FROM doorlockValid WHERE sensorname=+sensorname"; // execute sql query //stmt.executeUpdate(sql); stmt.executeQuery(sql); System.out.println("DEBUG: statement correct" +stmt); System.out.println(sql); // print the query result System.out.println(">> Debug: All RFID data displayed"); ResultSet resultset = null; // If sensor name is 1600ee15e9 then it's valid user and returns true if (resultset.getString("sensorname").equals(sensorname)) return true; } catch (SQLException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } // CLose catch // Otherwise return false if invalid user is trying to open the door return false; } // CLose buplic booelan is user valid method // Creating static update sensor table to insert the status of the door lock to the database public static void updateSensorTable(SensorData oneSensor) throws Exception { try { // Creating the INSERT statement from the parameters // set time inserted to be the current time on database server String updateSQL = "insert into doorlock(userid, sensorname, sensorvalue, timeinserted) " + "values('" + oneSensor.getUserid() + "','" + oneSensor.getSensorname() + "','" + oneSensor.getSensorvalue() + "'," + "now());"; // Print out debug message to the console System.out.println("DEBUG: Update: " + updateSQL); // Execute query stmt.executeUpdate(updateSQL); //publish_to_Android(oneSensor); // Print debug message to the console System.out.println("DEBUG: Update successful "); } catch (SQLException se) { // Problem with update, return failure message System.out.println(se); System.out.println("\nDEBUG: Update error - see error trace above for help. "); return; } // CLose catch sql exception // all ok, return return; } // Close private void update sensor table method /** * Creating private string to retrieveSensorData * Declaring a string to hold the sql select, set its value to a select * statement that will retrieve all values from the doorlock table * where the sensorname equals the parameter supplied "where sensorname='" + sensorname + "'". * Then adding the qualifier " order by timeinserted asc" to the sql * statement to ensure that the data is returned in ascending order * (i.e. newest last). * http://localhost:8080/IOTServer/RFIDDao?getdata&sensorname=4d004a5587 * http://localhost:8080/IOTServer/RFIDDao?getdata&sensorname=1600ee15e9 * @param sensorname * @return */ private String retrieveSensorData(String sensorname) { //SELECT from mudfoot server where sensorname = the sensorname inserted // String selectSQL = "select * from rashidd.doorlock where sensorname = \"" + sensorname + "\""; String selectSQL = "select * from rashidd.doorlock where sensorname='" + sensorname + "' order by timeinserted asc"; //String selectSQL = "select * from rashidd.doorlock"; ResultSet rs = null; // creating variable for result set // Creating array list of sensor data ArrayList<SensorData> s = new ArrayList<>(); // Declaring a Result set called rs // rs = ((java.sql.Statement) statement).executeQuery(selectSQL);//RESULT FROM // QUERY // Creating try to declare ArrayList of SensorData called allSensors to hold results, // and initialise it try { /** * iterate over the result set created by the select for each of * the columns in the table, putting them into oneSensor with * the corresponding set method for sensorname, sensorvalue, userid, timeinserted, using either * getString or getDouble and then execute query. */ rs = conn.createStatement().executeQuery(selectSQL); System.out.println("DEBUG: statement correct" +selectSQL); // Creating while resultset while (rs.next()) { // String sensorname, String sensorvalue, String userid, String sensordate SensorData oneSensor = new SensorData(rs.getString("sensorname"), rs.getString("sensorvalue"), rs.getString("userid"), rs.getString("timeinserted")); s.add(oneSensor); // add the data } // CLose while loop for rs.next } catch (SQLException ex) { System.out.println("Error in SQL " + ex.getMessage()); } // Close catch sql exception e // Return the responce in json format return new Gson().toJson(s); } // Close private string retrieve sensor data // Creating public void publish to android to publish the sensor data to the application, in order to view the data on the appication // public void publish_to_Android(SensorData a)throws Exception // { // // Gson g = new Gson(); // final MqttTopic motorTopic = client.getTopic(TOPIC_SERVER); // motorTopic.publish(new MqttMessage(g.toJson(a).getBytes())); // // // } } // Close public class sensor server db
Что я уже пробовал:
Я пробовал отлаживать код еще ничего, а также проверял различные операторы в моем sql и тестировал их. Они работают в моем sql workbench, но не в eclipse.