Servlet doGet not work if string is null - java

I'm doing the logic below using Servlet and and JSP
However if I pass the order with value, and uncomment the lines in the Servlet it works, but if the order is null, nothing happen and the exception generate a "null" message, simple as it is.
The code like is below is working, however if I uncomment the lines, it stopped if order is null. Hope I'm clear here, if not, let me know.
<td class="headerindex">Code ready date:</td>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection = DbUtil.getConnection();
try {
Statement statement = connection.createStatement();
String query = "";
String order = "";
order = request.getParameter("order");
System.out.println("Order is: "+order);
//if (order.equals("code_ready_date")) {
//query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE')";
//}
//else if (order != null) {
//query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
//}
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
System.out.println("Query is: "+query);
ResultSet rs = statement.executeQuery(query);
List<Code> codes = new ArrayList<Code>();
while (rs.next()) {
Code code = new Code();
code.setEpic_project(rs.getString("epic_project"));
code.setReleases(rs.getString("releases"));
code.setJira_tickets(rs.getString("jira_tickets"));
code.setApplications(rs.getString("applications"));
code.setComponents(rs.getString("components"));
code.setCode_ready_date(rs.getString("code_ready_date"));
code.setRtb_code_deploy(rs.getString("rtb_code_deploy"));
code.setOrt_code_deploy(rs.getString("ort_code_deploy"));
code.setProd_code_deploy(rs.getString("prod_code_deploy"));
code.setProd_deploy_state(rs.getString("prod_deploy_state"));
code.setProd_launch_date(rs.getString("prod_launch_date"));
code.setDependencies(rs.getString("dependencies"));
code.setId(rs.getString("id"));
codes.add(code);
}
request.setAttribute("code", codes);
RequestDispatcher disp = request.getRequestDispatcher("ListCodes.jsp");
disp.forward(request, response);
rs.close();
statement.close();
} catch (Exception e) {
System.out.println("Exception is: " + e.getMessage());
}
}

Your getting a null pointer exception when you try and call the equals method on a null reference. When a reference is null there is no object to call the equals method on. So you need to check for null first. Try the following:
if (order == null) {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
}else if (order.equals("code_ready_date")) {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE')";
} else {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
}

Related

Can I use a value passed through ajax to make a database search using a prepared statement?

Guys I been struggling with this issue quite a bit, I'm a novice in using ajax calls and jdbc related functions. Moving on to the point, I'm passing a datepicker value to the servlet side by using an ajax function, the function works right, I'm printing the value in a random div just to see if its working and it does work. Now how can I take that value and use it in a prepared statement to search on my database data depending on the date picked by the user, can this be done at all?
heres some code to add more context
$.ajax({
type:'POST',
data:{dateinput:dateinput},
url:'/Rest/sales?action=param2',
dataType: 'json',
success:function(result){
$('#altdate').html(result);
},
error: function (error) {
console.log(error);
}
});
});
I have a prepared statement with a static value just to see if it was working (it does) but here is where I can't make progress, how do I declare that value?
ConnectionPool pool = ConnectionPool.getInstance(DatosGeneral.DATABASE);
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String[] ids = null;
double[] prices = null;
try{
String query = "SELECT * FROM [" + GeneralData.DATABASE + "].[dbo].[SalesDetails] "
+ "WHERE [Branch] = '" + GeneralData.bra + "' "
+ "AND [UpDate] = ?" ; //previous value 20190521
System.out.println(query);
ps = connection.prepareStatement(query,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
rowcount = rs.getRow();
rs.beforeFirst();
}
ids = new String[rowcount];
prices = new double[rowcount];
for (int i = 0; rs.next(); i++) {
if (rs.getString("Type").replaceAll("\\s+", "").equals("PROD")) {
ids[i] = rs.getString("ProductCode").replaceAll("\\s+", "");
prices[i] = rs.getDouble("Price");
}
}
Lastly my dopost function where I'm requesting the parameters
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action= request.getParameter("action");
if(action.equals("param1")){
int i = Integer.parseInt(request.getParameter("branch"));
GeneralData.bra = GeneralData.branches[i];
GeneralData.braName = GeneralData.braNames[i];
System.out.println(GeneralData.bra);
}else if (action.equals("param2")){
String altdate = request.getParameter("dateinput");
PrintWriter out = response.getWriter();
out.print(altdate);
}
any help would be appreciate it
Well I solved it, the only thing I did was to declare a variable where I could store the value passed through the ajax call(the value of the datepicker) and assign it with the doPost method. Something like this:
private String datePickerValue=null;
doPost method:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
datePickerValue=altdate;
}
and lastly in the query of the prepared statement just specified that variable as the parameter used to get the data from the db:
try{
String query = "SELECT * FROM [" + GeneralData.DATABASE + "].[dbo].[SalesDetails] "
+ "WHERE [Branch] = '" + GeneralData.bra + "' "
+ "AND [UpDate] = '" + datePickerValue +"'" ; //previous value 20190521

SQL query in eclipse

I have my connection class like this:
public class Codb {
public static Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" +
"localhost:3306/bd1";
String user = "root";
String passwd = "root";
Connection conn = (Connection) DriverManager.getConnection(url, user, passwd);
//Création d'un objet Statement
Statement state = conn.createStatement();
//L'objet ResultSet contient le résultat de la requête SQL
ResultSet result = state.executeQuery("SELECT * FROM consomateur");
//On récupère les MetaData
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
System.out.println("\n**********************************");
//On affiche le nom des colonnes
for (int i = 1; i <= resultMeta.getColumnCount(); i++)
System.out.print("\t" + resultMeta.getColumnName(i).toUpperCase() + "\t *");
System.out.println("\n**********************************");
while (result.next()) {
for (int i = 1; i <= resultMeta.getColumnCount(); i++)
System.out.print("\t" + result.getObject(i).toString() + "\t |");
System.out.println("\n---------------------------------");
}
result.close();
/*state.close();*/
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The user enter the id and I want to know if the id is in the database, I created a servletin which I declared this:
static Statement St;
public ResultSet rs;
and then I have this method that verifies if the id exists or not, but it doesn't work for me.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String req = "select id from db1.consomateur ";
try {
St = (Statement) Codb.Con.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
rs = (ResultSet) St.executeQuery(req);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet id = rs;
String un = request.getParameter("id");
String msg = " ";
if (un.equals(id)) {
msg = "Hello " + un + " your login is sucess";
} else {
msg = "Hello " + un + " your login is unsucess";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font siez='6' color=red>" + msg + "</font>");
}
Two ways to improve your code.
1. One simple thing, just iterate over the results in result set and check for the id that you are querying. What your are doing is, you are comparing id (referred as un your code) with result set (referred as id in your code) which is wrong. Result Set is a complex data structure which contains the sql query result data and meta data about it. Your comparison of ResultSet id with query parameter id is wrong. So one way is to iterate over the result set and compare the value of id of every row with query parameter id value and break the loop when match is found. Example: Taking over from your code
ResultSet id = rs;
String un = request.getParameter("id");
boolean flag = false;
while (id.next()) {
String i = id.getString("id");
if(un.equals(i)){
flag = true;
break;
}
}
if(flag){
msg="Hello "+ un + " your login is sucess";
}
else{
msg="Hello "+un + " your login is unsucess";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>"+ msg+ "</font>");
So what I did is, i iterate over the result set and for each value of result set, I compared it with query parameter that u sent. If it is matched, I got a hit and I set my flag to true which mean found and I break my loop as there is no point in looking ahead. Otherwise, my loop will eventually end when all the result set entries are exhauted and nothing matches. Therefore, my flag will remain false and later I used that flag variable to set corresponding message for the case.
2. The first way is way too time consuming as the number of comparisons happening is far too much if your database contains lot of rows. On the other hand, if we modify our query a bit and use the sql where clause we can let databse handle the matching and we will enjoy the ease of programming at our end. I hope the id field in db1.consomateur is primary key, then we can use this peice of code to make our life easy.
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String id = request.getParameter("id");
String req = "select id from db1.consomateur where id = "+id;
boolean flag = false;
try{
Connection c = Codb.connect();
Statement st = (Statement) c.createStatement();
ResultSet rs =(ResultSet)st.executeQuery(req);
if(rs != null){
if(rs.next())
flag = true;
}
}
if(flag){
msg="Hello "+ un + " your login is sucess";
}
else{
msg="Hello "+un + " your login is unsucess";
}
catch(Exception e){
msg = e.getMessage();
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>"+ msg+ "</font>");
}
So, if query get executed and we have result set not equal to null i.e. we have some data, we can check whether rs contains any rows. Since, id is a primary key, rs will contain only one row and rs.next will point to that row. Therefore, it will be our match and we have set our flag there. Otherwise flag will be false. In this case database itself take care of matching the ids and returning only the matching row to us. So, it will be faster as database create index over primary keys and we need not to create a loop which saves time.
Also, do not make Statement object static in second case as the query for each execution will be different based on id passed as parameter.

java.sql.SQLException: Operation not allowed after ResultSet closed MySQL Java [duplicate]

This question already has answers here:
Operation not allowed after ResultSet closed
(5 answers)
Closed 1 year ago.
I keep getting this whenever I try to use this method.
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7077)
at server.util.Plimus$1.run(Plimus.java:77)
This is on line 77: while (resultSet.next()) {
public static void process(final Player c, final String playerName) {
if (connection == null && connectionStatus == 0)
createConnection();
else if (connectionStatus != 0)
return;
new Thread() {
#Override
public void run() {
try {
String username = playerName.replaceAll(" ", "_");
String query = "SELECT * FROM donations WHERE username = '" + username + "' AND received = '0' LIMIT 1;";
ResultSet resultSet = query(query);
while (resultSet.next()) {
int[] contractIds = {3178768, 1}; //put all of your contract ids in here.
int contractId = Integer.parseInt(resultSet.getString("contract")), id = Integer.parseInt(resultSet.getString("id"));
query("UPDATE donations SET received = '1' WHERE username = '" + username + "' AND id = '" + id + "';");
if (contractId == contractIds[0]) { //first contract id in array.
c.getItems().addItem(962, 1);
} else if (contractId == contractIds[1]) { //second contract id in array.
c.getItems().addItem(962, 1);
}
}
} catch (Exception e) {
e.printStackTrace();
processMethod(0, true, true, false);
}
}
}.start();
}
Here is the query method that is requested.
/**
* Creates query function.
*/
public static ResultSet query(String s) throws SQLException {
try {
if (s.toLowerCase().startsWith("select")) {
ResultSet resultSet = statement.executeQuery(s);
return resultSet;
} else {
statement.executeUpdate(s);
}
return null;
} catch (Exception e) {
e.printStackTrace();
processMethod(0, true, true, false);
}
return null;
}
While iterating through your ResultSet, you are reusing the Statement object for updating the data (inside your query method), which closes the ResultSet from the query.
See the ResultSet documentation:
"A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results."
You should create separate Statements for the query and the update, and pass them to your query method:
public ResultSet query(String s, Statement statement) throws SQLException {
...
}
I assume that statement is declared static inside your class - there is usually no need for that: create the two statements for query and update in the constructor of your class, and either pass them to the query() method or use the one or the other depending on the statement.

When injecting into a sql query using java, gets an error

public ArrayList<Message> searchMessages(String word) throws DaoException{
ArrayList<Message> messages = new ArrayList<>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = getConnection();
//String query = "SELECT * FROM messages WHERE text LIKE %?% order by date";
String query = "SELECT * FROM messages WHERE text LIKE '%?%'";
ps = con.prepareStatement(query);
ps.setString(1,word);
rs = ps.executeQuery();
while (rs.next()) {
int messageId = rs.getInt("messageId");
String text = rs.getString("text");
String date = rs.getString("date");
int memberId2 = rs.getInt("memberId");
Message m = new Message(messageId,text,date,memberId2);
messages.add(m);
//Company c = new Company(companyId, symbol, companyName, sharePrice, high, low);
//companies.add(c);
}
} catch (SQLException e) {
throw new DaoException("searchMessages(): " + e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
freeConnection(con);
}
} catch (SQLException e) {
throw new DaoException("searchMessages(): " + e.getMessage());
}
}
return messages;
}
Just explain the code a little first.It simply just searches the messages table and its field of text for whatever is supplied.I use a prepared statement to insert it into the query and run it.No matter what string i supply it gives this error
oow_package.DaoException: searchMessages(): Parameter index out of range (1 > number of parameters, which is 0).
No idea why it isn't working in the slightest. Would appreciate any help.
You can't use such a parameter in a prepared statement. The query should be
SELECT * FROM messages WHERE text LIKE ?
And you should use
ps.setString(1, "%" + word + "%");
I'm no expert, but i'd say your prepared statement is recognized with no parameters, and you still insert one (word)... maybe the trouble comes from the % sign?
EDIT: agree with the guy above... seems legit.

JDBC Null pointer Exception thrown

Hi I'm getting nullpointerexception at rs.next() or rs.getString(1)
it is really weird that sometimes rs.next() works fine and it throws nullpointerexception at rs.getString("PRODUCTCODE"),sometimes it throws npe at rs.getString("PRODDATE")
i dont understand why rs.getString() thows npe while rs.next() works fine
Here is my code
{
ResultSet rs = null;
String query = "";
BarcodeBean bi = null;
try {
query = "SELECT * FROM TABLE(GET_BARCODEINFO('"barcode.trim()"'))";
statement = connection.createStatement();
Logger.getInstance().getLogger().logInfo(query);
rs = statement.executeQuery(query);
bi = new BarcodeBean();
if (rs == null){
if(rs.next()){
bi.setUrunKodu(rs.getString("PRODUCTCODE"));
bi.setImalatMakineKodu(rs.getString("PRODMACHINECODE"));
bi.setOperatorSicilNo(rs.getString("OPERATORID"));
bi.setImalatTarihi(rs.getString("PRODDATE"));
bi.setImalatVardiyasi(rs.getString("PRODSHIFT"));
bi.setSeriNumarasi(rs.getString("SERIALNUMBER"));
bi.setSirtTarihi(rs.getString("SIRTTARIHI"));
}
}
} catch (SQLException e) {
e.printStackTrace();
throw e;
} catch (Exception e) {
e.printStackTrace();
} finally {
DatabaseUtility.close(rs);
DatabaseUtility.close(statement);
}
}
probably you want:
if (rs != null) {
if (rs.next()) {
or even better:
if (rs != null && rs.next()) {
Your test is simply wrong.
Statement#executeQuery() never returns null. The whole nullcheck is superfluous. The normal idiom is the following:
public Entity find(Long id) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Entity entity = null;
try {
connection = database.getConnection();
preparedStatement = connection.prepareStatement(SQL_FIND);
preparedStatement.setLong(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setName(resultSet.getString("name"));
// ...
}
} finally {
close(connection, preparedStatement, resultSet); // In reversed order.
}
return entity;
}
Your actual problem lies somewhere else. This is clearly a misinterpretation of the stacktrace. To nail it correctly down, you need to lookup the line number of the first line in the stacktrace and point us the exact code at this line number.
From Statement javadocs:
public ResultSet executeQuery(String sql) throws SQLException
Returns: a ResultSet
object that contains the data produced
by the given query; never null
So, you don't need to verify whether rs == null.
The standard way to proceed resultset rows is:
while (rs.next ()) {
doSmth (rs);
}
You made a wrong notation in if condition,
So change it as,
if(rs!=null){
......
.......}

Categories