How to use where clause with session value in servlet - mysql

I have passed a value into servlet using a session.then assign the value to a variable call 'ms'. now i want to select data using that variable with 'where' clause. but it does not work.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession ses=request.getSession(false);
String ms = ses.getAttribute("ma").toString();
try {
dbconn = new DatabaseConnection();
conn = dbconn.setConnection();
stmt = conn.createStatement();
query = "select * from person where Email ="+ms;
res = dbconn.getResult(query, conn);
while(res.next()){
lst.add(res.getString("Username"));
lst.add(res.getString("Title"));
lst.add(res.getString("Fname"));
lst.add(res.getString("Lname"));
}
res.close();
}catch(Exception e){
RequestDispatcher rd =request.getRequestDispatcher("myAccount.jsp");
rd.forward(request, response);
}finally{
request.setAttribute("EmpData", lst);
RequestDispatcher rd =request.getRequestDispatcher("myAccount.jsp");
rd.forward(request, response);
lst.clear();
out.close();
}

It's your query causing the exception.
Instead of
query = "select * from person where Email ="+ms;
You should quote the email parameter.
query = "select * from person where Email ='"+ms+"'";
But your code is vulnerable to SQL injection. It is better to use PreparedStatement for this.
By the way, it is also better to print the stack trace on catch clause, you could spot what exactly going wrong easily.

Related

SyntaxError Exception

#Override
public void start(Stage primaryStage) throws Exception{
try{
String fxmlName;
Connection con = DriverManager.getConnection("url","root","password");
Statement st = con.createStatement();
String qry = "select UpdateT from schema.update";
ResultSet rs = st.executeQuery(qry);
fxmlName = rs.getString("UpdateT");
// System.out.println(fxmlName);
st.close();
Parent root = FXMLLoader.load(getClass().getResource(fxmlName));
primaryStage.setScene(new Scene(root));
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
}
catch (Exception e){
System.out.println(e);
}
}
Hey guys this is my code and its my first time on stack overflow and why I am getting this exception?
java.sql.SQLException: Before start of result set
UPDATE is a reserved word, so your DB objects should not use it. You can:
change the table name (i 'd prefer this)
use quotes every time to refer to that table

How to troubleshoot problems when tomcat servlet connects to mysql

Tomcat servlet gets connection to mysql with getConnection(). Just fetch data from db test table shop.Connection to mysql is successful, but browser doesn't still show any data from backend. JavaScript shows request.status is 200 and request.readyState is 2 or 3. How can I find the problem? I even don't see any exceptions in tomcat log file.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println("ok");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "***");
Statement statementQuery = connection.createStatement();
ResultSet set = statementQuery.executeQuery("select * from shop");
// connection.commit(); Error appears here(should be commented):
out.println("<div>");
while (set.next()) {
out.println("ok");
out.println(set.getInt(1) + " ");
out.println(set.getString(2) + " ");
out.println(set.getDouble(3));
}
} catch (Exception e) {
e.printStackTrace();
}
out.println("</div>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
EDIT:
connection.commit() is wrong. Comment that line and it works.
Change Oracle driver to Mysql driver
Class.forName("com.mysql.jdbc.Driver");
SQL statements are executed sequentially. Change the order of execution to:
int ret = statement.executeUpdate("insert into shop values (53, 'fjd', 43.2)");
ResultSet s1 = statement.executeQuery("select * from shop");
Execute also a commit on the connection
connection.commit();
And add a finally to close statement and connection
}finally{
statement.close();
connection.close();
}

An Error Occurred: Syntax Error: Unexpected token y

I don't know why I am getting this. Here is some of the code where I try to retrieve some information from database and send it as response to a Jersey resource mapped to a certain URL. I don't know what that y is theerror referring to:
public String myInformation(String theName){
String infoQuery = "Select * from bookinfo where name= \'theName\'";
ResultSet result = null;
conn = newConnection.dbConnection();
try
{
preparedStatement = conn.prepareStatement(infoQuery);
result = preparedStatement.executeQuery(infoQuery);
}
catch (SQLException e)
{
e.printStackTrace();
}
StringBuilder information = new StringBuilder();
try
{
if(result != null){
while(result.next()){
// Build the string which is returned from this
// method and sent as json response for a URL of a resource
I read columns from database and use StringBuilder to store it. At the end I convert it to String and pass it to Jersey resource.
}
else{
System.out.println("No result");
}
}
catch (SQLException e)
{
e.printStackTrace();
}
String someInformation = information.toString();
return someInformation;
}
In my resource:
#GET
#Path("/allSome/{theName}")
#Produces(MediaType.APPLICATION_JSON)
public Response getSomeInfo(#PathParam("theName") String theName){
System.out.println("Name is: "+ theName);
BookInformation bookInfo = new BookInformation();
String bookInformation =bookInfo.bookInformation(bookName);
ResponseBuilder responseBuilder = Response.status(Status.OK);
responseBuilder.entity(bookInformation);
Response response = responseBuilder.build();
return response;
}
Edit
My method is returning a String. On Postman client and I am receiving data back from database but it is coming back as a string with no spaces between them. I think I need to convert that string to JSON so that my resource can send it back to client for displaying on page.
Any help is appreciated. Thanks.
The 'y' must be in the theName parameter, along with some quotes. You should be using PreparedStatement properly, with a placeholder parameter:
String infoQuery = "Select * from bookinfo where name = ?";
// ...
preparedStatement = conn.prepareStatement(infoQuery);
preparedStatement.setString(1, theName);
// ...
Your code is poorly structured. Code that depends on the success of a try block should be inside the try block.

Query MySQL using JSP and Servlet POST method

I'm not sure if I'm trying to "print" my result correctly. What I'm trying to do is use JSP to take in the variable and then pass it to the servlet where it will query the database and then display the result. I tested querying my database in a different java file and I had no trouble with that. Any advice would be greatly appreciated!
JSP file:
<form method="post" action="HelloServlet"/>
Enter your name:<input name = "exName"/><br>
<input type = "submit" />
</form>
JAVA file (servlet):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//response.setContentType("text/html; charset=ISO-8859-1");
PrintWriter out = response.getWriter();
java.sql.Connection con = null;
java.sql.PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/masters";
String user = "christine";
String password = "password";
try{
String exName = request.getParameter("exName");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name ='"+exName+"';");
rs = pst.executeQuery();
while (rs.next()){
String name = rs.getString("description_txt");
out.print(exName);
out.print(name);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
There are few things you need to change in your code.
As #BalusC mentioned do not suppress exception. Write exception to browser using out.println(ex); or throw new ServletException(ex). This will help you in finding the cause of problem.
Add Class.forName("com.mysql.jdbc.Driver"); before DriverManager.getConnection().
As you are already using PreparedStatement use
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name =?");
pst.setString(1, exName);
rs = pst.executeQuery();

How to retrieve series of images from mysql and display them in JSP

I'm trying to build an array by fetching data from mysql. The array include text and pictures. So far everything went good but now I have no idea how to display these picture from the memolist on the JSP page. All I can see are just bunch of bytes. Let's see:
My DBQueries looks like this:
public static ArrayList<Memo> selectAllMemoList()
{
DBConnectionPool pool = DBConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT Users.picture, Users.username, Messages.subject, Messages.date, Messages.msg_id " +
"FROM Messages, Users " +
"WHERE Messages.uid_fk = Users.uid " +
"ORDER BY date DESC";
try
{
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
ArrayList<Memo> memolist = new ArrayList<Memo>();
String dbSqlTimestamp = "";
while (rs.next()) {
m.setUserpicture(rs.getString("picture"));
m.setUsername(rs.getString("username"));
m.setSubject(rs.getString("subject"));
m.setDate(dbSqlTimestamp = new SimpleDateFormat("dd-MM-yy HH:mm").format(rs.getTimestamp("date")));
m.setMessageid(rs.getInt("msg_id"));
memolist.add(m);
}
return memolist;
}
catch (SQLException e){
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
My MemoShowAll looks like this:
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
HttpSession session = request.getSession();
ArrayList<Memo> memolist = DBQueries.selectAllMemoList();
request.setAttribute("listmemo", memolist);
String url = "/restricted/MemoList.jsp";
// forward the request and response to the view
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
MemoList.jsp
<z:rows>
<core:forEach var="each" items="${listmemo}">
<z:row>
<img src="${each.userpicture}" border=0 >
<z:label value="${each.username}"/>
<z:label value="${each.subject}"/>
<z:label value="${each.date}"/>
</z:row>
</core:forEach>
</z:rows>
Cheers,
BB
The way that i bypass this issue is by using a servlet to expose the image to the client. For this to work, you should store the image bytes retrieved from the database to the user's session object.
In the html i have < img src="/imageRender?id=someimageid"/ >
Therefore when the browser will try to render the image, it will make a call to /imageRender where my servlet listens to. And the servlet will read the input parameter and then render the image from the session object based on the parameter.
Some helpful links are:
1) Display servlet as img src using session attribute
2) Writing image to servlet response with best performance
Pay special attention to link 2 #BalusC answer to the place where it says In the ImageDAO#find() you can use ResultSet#getBinaryStream() to get the image as an InputStream from the database.
In your case you can create a List of DAO objects that will represent each row from db.