JavaServlet handling SQL errors - mysql

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out=res.getWriter();
res.setContentType("text/html");
Connection conn = null;
final String id = UUID.randomUUID().toString();
Map m = req.getParameterMap();
Set s = m.entrySet();
Iterator it = s.iterator();
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "username", "password");
String sqlStr = "insert into transactions (LogID,KeyName,KeyValue) "
+ "values (?,?,?)";
while(it.hasNext()){
Map.Entry<String,String[]> entry = (Map.Entry<String,String[]>)it.next();
String key = entry.getKey();
String[] value = entry.getValue();
try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
stmt.setString(1, id);
stmt.setString(2, key);
stmt.setString(3, value[0].toString());
out.println("<html><head><title>Callback Script</title></head><body>");
out.println("<h3>Inserted into the database:</h3>");
out.println("<p>Parameter: " + key + " and Value = " + value[0].toString() + "</p>");
int updateCount = stmt.executeUpdate();
for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
String paramName = en.nextElement();
String paramValue = req.getParameter(paramName);
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
out.close();
try {
if (conn != null) conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
If some error happens with the MySQL Database like wrong credentials, any SQL syntax error at all should be handled and displayed but it is not displaying at all.
Any advice on this or am I coding it wrong?
Cheers

What you have will only print to the logs. To print to the page, use out.print
catch (SQLException ex)
{
ex.printStackTrace(); //print to log
out.print("<br/>Error: " + ex.getMessage()); //print to page
}
On credentials errors you won't want to print the actual message to the page, as it might include the credentials. So you should isolate the part the opens the connection with its own try-catch, which can be nested inside this one.
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "username", "password");
}
catch(Exception ex_connError)
{
out.print("<br/>Error making db connection");
}

Related

JSP: How to increase a value of a database in JSP? Error when i click the button

------ 2 DAYS AGO --------
"I made a database only for the "likes" of a website. The database has a table (Likes) with several fields (Like1, Like2, etc ...)
In a JSP file I made the connection and show the value of a field (Like1).
But what I want to do is: by clicking on a certain text, the value increases by one, updating that value in the database from Like1 to Like1 + 1."
--- EDIT ---
When i click the button, show me this:
ERROR
When I refresh, the data does not change. So I think if I did not show the error, it would work.
What I want is, when you press the button, the DB data increment by 1.
Structure:
Structure
index.jsp:
<body>
<div class="col-lg-12">
<form method="post" action="likeCount">
<button type="submit" name="click"><b style="color:#ff5858;font-size: 24px;">❤</b></button>
<% try {
Connection conn = DBConnect.connect();
PreparedStatement pstmt = conn.prepareStatement("SELECT Like1 from Likes");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {%>
<input type="text" hidden name="counts" value="<%=rs.getInt("Like1")%>" />
</form>
<span style="font-weight: bold"><%=session.getAttribute("count")==null)?rs.getInt("Like1"):(session.getAttribute("count"))%></span><% }
} catch (SQLException ex) {
System.out.println("Error in select: " + ex.getMessage());
}%>
</div>
</body>
DBConnect.java:
package myPack;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnect {
public static Connection connect() throws SQLException {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/Likes";
String username = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error : " + e.getMessage());
}
return conn;
}
}
likeCount.java:
package myPack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class likeCount {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
/*check whether the button is clicked*/
if (request.getParameter("click") != null) {
try {
/*getting the number of likes*/
String x = request.getParameter("counts");
int c = Integer.parseInt(x);
int count = c;
count = count + 1; //increment the value
Connection conn = DBConnect.connect();
PreparedStatement ps = conn.prepareStatement("UPDATE Likes SET Like1 = ?");
ps.setInt(1, count);
int num = ps.executeUpdate();
if (num > 0) {
HttpSession session = request.getSession();
session.setAttribute("count", count);
response.setIntHeader("Refresh", 3);
response.sendRedirect("index.jsp");
}
} catch (SQLException e) {
System.out.println("Error in update :" + e.getMessage());
}
}
}
}
In this case you will need a servlet and a database connection classes.
First, this is the database connection class. DBConnect.java
public class DBConnect {
public static Connection connect() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/likes";
String username = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error : "+e.getMessage());
}
return conn;
}
}
Next, this will be the index.jsp form
<body>
<div class="col-lg-2">
<form method="post" action="likeCount">
<button type="submit" name="click">TEXTO DONDE QUISIERA QUE INCREMENTE AL HACER CLICK.</button>
<% try {
Connection conn = DBConnect.connect();
PreparedStatement pstmt = conn.prepareStatement("SELECT Like1 from Likes");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {%>
<input type="text" hidden name="counts" value="<%=rs.getInt("Like1")%>" />
</form>
<span style="font-weight: bold"><%=(session.getAttribute("count")==null)?rs.getInt("Like1"):(session.getAttribute("count"))%></span>
<% }
} catch (SQLException ex) {
System.out.println("Error in select: " + ex.getMessage());
}%>
</div>
</body>
And finally, the servlet. likeCount.java
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*check whether the button is clicked*/
if (request.getParameter("click") != null) {
try {
/*getting the number of likes*/
String x = request.getParameter("counts");
int c = Integer.parseInt(x);
int count = c;
count = count + 1; //increment the value
Connection conn = DBConnect.connect();
PreparedStatement ps = conn.prepareStatement("UPDATE Likes SET Like1 = ?");
ps.setInt(1, count);
int num = ps.executeUpdate();
if (num > 0) {
HttpSession session = request.getSession();
session.setAttribute("count", count);
response.setIntHeader("Refresh", 3);
response.sendRedirect("index.jsp");
}
} catch (SQLException e) {
System.out.println("Error in update :" + e.getMessage());
}
}
}
Hope it would work.

Can't parse JSON data from URL with only username authentication

I'm using an url in order to read json data but it doesn't work because there is an authentication requested to get access to it using only the username (no login, no password only username). so my code show me the error :
java.io.IOException: Server returned HTTP response code: 401 for URL
My code is working using another URL with no authentication.
Could someone help me or give me and example that do the same thing.
many thanks to you in advance
package javaapplication3;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import org.json.JSONArray;
import org.json.JSONException;
public class JSONREST {
public static String callURL(String myURL) {
System.out.println("Requested URL:" + myURL);
StringBuilder sb = new StringBuilder();
URLConnection urlConn = null;
InputStreamReader in = null;
try {
URL url = new URL(myURL);
urlConn = url.openConnection();
if (urlConn != null) {
urlConn.setReadTimeout(60 * 1000);
}
if (urlConn != null && urlConn.getInputStream() != null) {
in = new InputStreamReader(urlConn.getInputStream(),
Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(in);
if (bufferedReader != null) {
int cp;
while ((cp = bufferedReader.read()) != -1) {
sb.append((char) cp);
}
bufferedReader.close();
}
}
in.close();
} catch (Exception e) {
throw new RuntimeException("Exception while calling URL:" + myURL, e);
}
return sb.toString();
}
public static void main(String[] args) {
String jsonString = callURL("MY URL");
System.out.println("\n\njsonString: " + jsonString);
try {
JSONArray jsonArray = new JSONArray(jsonString);
System.out.println("\n\njsonArray: " + jsonArray);
}
catch (JSONException e) {
e.printStackTrace();
}
}
}

how do i use select statment

I want to use select max from a table. I want to use a PreparedStatement. I have a composite primary key which consists of the t.v series and the epo number. When I add new epo it will for table and bring the t.v series code from guidline table the content of all the programs and the code for each and then add to the new table. I want it to get the last epo by getting the max and then increment +1 "an automation app".
So how can I select max where id =??
If you get me its like
pstm2=con.prepareStatement(max);
String max="select MAX(epono) as eponoo from archieve wwhere id like ? ";
This program would be helpful
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SelectRecordsUsingPreparedStatement {
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:databaseName";
String username = "name";
String password = "password";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) {
ResultSet rs = null;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String query = "select deptno, deptname, deptloc from dept where deptno > ?";
pstmt = conn.prepareStatement(query); // create a statement
pstmt.setInt(1, 1001); // set input parameter
rs = pstmt.executeQuery();
// extract data from the ResultSet
while (rs.next()) {
int dbDeptNumber = rs.getInt(1);
String dbDeptName = rs.getString(2);
String dbDeptLocation = rs.getString(3);
System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

login example using jsp and servlet along with mysql

I have a login example working already which has one sql table . This is my user table which gets the general information about the user. Now i want to insert another table in my database - details , and then connect these two together.
i already created a different POJO class for my details table along with the one i already had for the user table.
package com.shreya.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import com.shreya.model.User;
import com.shreya.util.DbUtil;
public class UserDao {
private Connection connection;
public UserDao() {
connection = DbUtil.getConnection();
}
public void addUser(User user) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ? )");
// Parameters start with 1
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteUser(int userId) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("delete from users where userid=?");
// Parameters start with 1
preparedStatement.setInt(1, userId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateUser(User user) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("update users set firstname=?, lastname=?, dob=?, email=?" +
"where userid=?");
// Parameters start with 1
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.setInt(5, user.getUserid());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from users");
while (rs.next()) {
User user = new User();
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setDob(rs.getDate("dob"));
user.setEmail(rs.getString("email"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
public User getUserById(int userId) {
User user = new User();
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from users where userid=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setDob(rs.getDate("dob"));
user.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
this is the one i wrote for the connectivity.
i tried adding the same stuff for the details table . but its just not working .
help would be appreciated.

Constructor must be called super error in JSP, JDBC, servlet and forms

I'm creating a registration form for my web application and I'm getting the following error when I try to access register a new user:
java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this() java.lang.VerifyError: (class: eBooks/Data/UserDB, method: <init> signature: ()V) Constructor must call super() or this()
at eBooks.controller.RegisterUserServlet.doPost(RegisterUserServlet.java:62)
This is the UserDB class:
package eBooks.Data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import eBooks.business.User;
import eBooks.util.DBUtil;
public class UserDB {
public static int insert(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query =
"INSERT INTO User (fName, lName, email_address, password, dataOfBirth, phone,"
+ " address, city, state, country, zipcode, accountType)"
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int update(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET"
+ "fName = ?"
+ "lName = ?"
+ "password = ?"
+ "dateOfBirth = ?"
+ "phone = ?"
+ "address = ?"
+ "city = ?"
+ "state_or_Region = ?"
+ "country = ?"
+ "zip = ?"
+ ""
+ "WHERE email_address= ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getfName());
ps.setString(2, user.getlName());
ps.setString(3, user.getEmailAddress());
ps.setString(4, user.getPassword());
ps.setString(5, user.getDateOfBirth());
ps.setString(5, user.getPhone());
ps.setString(6, user.getAddress());
ps.setString(7, user.getCity());
ps.setString(8, user.getCountry());
ps.setString(9, user.getState());
ps.setString(10, user.getZipcode());
//ps.setString(11, user.getAccountType()); -- Ask Jassin
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static int delete(User user)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "DELETE FROM User" +
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, user.getEmailAddress());
return ps.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
return 0;
}
finally
{
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static boolean emailExists(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT email_address FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
return rs.next();
}
catch(SQLException e)
{
e.printStackTrace();
return false;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static User selectUser(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM User"+
"WHERE email_address = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
User user = null;
if (rs.next())
{
user = new User();
user.setfName(rs.getString("fName"));
user.setlName(rs.getString("lName"));
user.setEmailAddress(rs.getString("emailAddress"));
user.setPassword(rs.getString("password"));
user.setPhone(rs.getString("phone"));
user.setDateOfBirth(rs.getString("dateOfBirth"));
user.setAddress(rs.getString("address"));
user.setCity(rs.getString("city"));
user.setCountry(rs.getString("country"));
user.setState(rs.getString("state"));
user.setZipcode(rs.getString("zip"));
// user.setAccountType(rs.getString("accountType")); -- Ask Jassin
}
return user;
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
This is the RegisterUserServlet:
package eBooks.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Cookie;
import eBooks.business.User;
import eBooks.business.Account;
import eBooks.Data.UserDB;
public class RegisterUserServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
HttpSession session = request.getSession();
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String emailAddress = request.getParameter("emailAddress");
String password = request.getParameter("password");
String dateOfBirth = request.getParameter("dateOfBirth");
String phone = request.getParameter("phohe");
String address = request.getParameter("address");
String city = request.getParameter("city");
String country = request.getParameter("country");
String state = request.getParameter("country");
String accountType = request.getParameter("accountType");
//TO DO: Account acctTypeList = request.getParameter("acctTypeList"); add this an object first
User user = new User();
user.setfName(fName);
user.setlName(lName);
user.setEmailAddress(emailAddress);
user.setPassword(password);
user.setDateOfBirth(dateOfBirth);
user.setAddress(address);
user.setCity(city);
user.setCountry(country);
user.setState(state);
user.setZipcode(phone);
//TODO: user.setAccountType(accTypeList); -- Ask Jassin
// Add information to the database
if(UserDB.emailExists(emailAddress))
UserDB.update(user);
else
UserDB.update(user);
session.setAttribute("User", user);
Cookie emailCookie = new Cookie("emailCookie", emailAddress);
emailCookie.setMaxAge(60*60*24*365*2);
emailCookie.setPath("/");
response.addCookie(emailCookie);
String url = "WEB-INF/view/registration_confirmation.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
I'm new to web development and I just need a push in the right direction to fix this issue.
I'm using glassfish and mysql.
Just fixed the problem – moved all the files to a new project and manually created the web.xml and it's is working fine now. Thanks #ErnestFriedman-Hill