sql statement not working in jsp - java

This is the Code i have , I think its the Sql string that is not working correctly. im able to view the table and cick on the edit field but im only able to update the first row. i want to be able to select a row and than edit it according to its id .
//Database View
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<html>
<head>
<title>Inventory</title>
</head>
<body>
<%
Connection connect = null;
Statement s = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/client", "rootroot", "rootroot");
s = connect.createStatement();
String sql = "SELECT * FROM client ORDER BY id ASC";
ResultSet rec = s.executeQuery(sql);
%>
<table width="600" border="1">
<tr>
<th width="91"> <div align="center">id </div></th>
<th width="198"> <div align="center">Email </div></th>
<th width="97"> <div align="center">CountryCode </div></th>
<th width="59"> <div align="center">Budget </div></th>
<th width="71"> <div align="center">Edit </div></th>
</tr>
<%while((rec!=null) && (rec.next())) { %>
<tr>
<td><div align="center"><%=rec.getString("id")%></div></td>
<td><%=rec.getString("first_name")%></td>
<td><%=rec.getString("last_name")%></td>
<td><div align="center"><%=rec.getString("blood_type")%></div></td>
<td align="right"><%=rec.getString("gender")%></td>
<td align="center"> Edit</td>
</tr>
<%}%>
</table>
<%
} catch (Exception e) {
// TODO Auto-generated catch block
out.println(e.getMessage());
e.printStackTrace();
}
try {
if(s!=null){
s.close();
connect.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
out.println(e.getMessage());
e.printStackTrace();
}
%>
</body>
</html>
//Edit Page
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<html>
<head>
<title>ThaiCreate.Com JSP Tutorial</title>
</head>
<body>
<%
Connection connect = null;
Statement s = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/client", "rootroot", "rootroot");
s = connect.createStatement();
String sql ="SELECT * FROM client";
ResultSet rec = s.executeQuery(sql);
if(rec != null) {
rec.next();
%>
<form name="frmUpdate" method="post" action="SaveEdit.jsp?id=<%=rec.getString("id")%>">
Update Form
<table width="428" border="1">
<tr>
<th width="181">
<div align="left">Product ID </div></th>
<td width="231"><%=rec.getString("id")%></td>
</tr>
<tr>
<th width="181">
<div align="left">Name </div></th>
<td><input type="text" name="txtName" size="20" value="<%=rec.getString("first_name")%>"></td>
</tr>
<tr>
<th width="181">
<div align="left">Email </div></th>
<td><input type="text" name="txtEmail" size="20" value="<%=rec.getString("last_name")%>"></td>
</tr>
<tr>
<th width="181">
<div align="left">CountryCode </div></th>
<td><input type="text" name="txtCountryCode" size="2" value="<%=rec.getString("blood_type")%>"></td>
</tr>
<tr>
<th width="181">
<div align="left">Budget </div></th>
<td><input type="text" name="txtBudget" size="5" value="<%=rec.getString("gender")%>"></td>
</tr>
</table>
<input type="submit" value="Save">
</form>
<% }
} catch (Exception e) {
// TODO Auto-generated catch block
out.println(e.getMessage());
e.printStackTrace();
}
try {
if(s!=null){
s.close();
connect.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
out.println(e.getMessage());
e.printStackTrace();
}
%>
</body>
</html>
// save page
<%# page import="java.sql.ResultSet" %>
<%# page import="java.sql.SQLException" %>
<%# page import="java.sql.Statement" %>
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<%
Connection connect = null;
Statement s = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/client", "rootroot", "rootroot");
s = connect.createStatement();
String strCustomerID = request.getParameter("id");
String strName = request.getParameter("txtName");
String strEmail = request.getParameter("txtEmail");
String strCountryCode = request.getParameter("txtCountryCode");
String strBudget = request.getParameter("txtBudget");
String sql = "UPDATE client " +
"SET first_name = '"+ strName + "' " +
", last_name = '"+ strEmail + "' " +
", blood_type = '"+ strCountryCode + "' " +
", gender = '"+ strBudget + "' " +
" WHERE id = '" + strCustomerID + "' ";
s.execute(sql);
out.println("Record Update Successfully");
} catch (Exception e) {
// TODO Auto-generated catch block
out.println(e.getMessage());
e.printStackTrace();
}
try {
if(s!=null){
s.close();
connect.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
out.println(e.getMessage());
e.printStackTrace();
}
%>
</body>
</html>

please try s.executeUpdate(sql); instead of s.execute(sql);

First of all +1 for what Elliott Frisch says. Such spaghetti code is very bad practice.
Anyway, if I understand correctly your use case, then you need to obtain at the Edit page the id parameter from URL/request and add into the select appropriate condition so it looks something like
"SELECT * FROM client WHERE id = '" + clientId + "' "
If you don't put the condition in there, it will always return whole table and based on your code you're just taking the first row and ignoring the rest. Which is very inefficient way to work with DB.
Another thing you should consider are binds and something what is called preparedStatement - try to google it and learn something about it. The main reason to use it is to avoid SQL injection using which somebody can easily mess up or compromise your database data.
I personally would also replace * by listing of all columns which you really need.

Related

request.getParameter in jsp returns null or empty string

I made an html textbox for an input and want to connect this to database.
But everytime I make an input to the textbox and move on to the result page, the result only shows the name of the attribute but not any tuples.
I think the request.getParameter() returns null or empty string. I did several tries but cannot find any solution.
Here's my code.
This's selectTestForm.jsp
<%# page contentType="text/html; charset=utf-8" %>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Select the game</title>
</head>
<body>
<p>Input opponent team</p>
<form name="form1" method="get" action="result.jsp">
<p>Opponent team : <input type="text" name="oppon"></p>
<p><input type="submit" name="Submit" value="send"></p>
</form>
</body>
</html>
And this's the result.jsp
<%# page contentType="text/html; charset=utf-8" %>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Find the game</title>
</head>
<body>
<table width="500" border="1">
<tr>
<td width="100">Game ID</td>
<td width="100">Opponent Team</td>
<td width="100">Start Date</td>
</tr>
<%
String opponent = (String) request.getParameter("oppon");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
System.out.println("Driver loading error");
}
try{
String jdbcUrl = "jdbc:oracle:thin:#localhost:1521:xe";
String userId = "sports_booking";
String userPass = "jade";
con = DriverManager.getConnection(jdbcUrl, userId, userPass);
String sql = "select * from game where opponent=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "opponent");
rs = pstmt.executeQuery();
while( rs.next() ) {
String game_id = rs.getString("game_id");
String start_date = rs.getString("start_date");
%>
<tr>
<td width="100"><%= game_id %></td>
<td width="100"><%= opponent %></td>
<td width="100"><%= start_date %></td>
</tr>
<%
}
}catch(SQLException e){
e.printStackTrace();
if(rs != null) {
try {
rs.close();
}catch(SQLException sqle) {}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException sqle) {}
}
if(con != null) {
try {
con.close();
}catch(SQLException sqle) {}
}
}
%>
</table>
</body>
</html>
I'd appreciate if you help my problem thanks!
The problem is line pstmt.setString(1, "opponent");, as you set a const "opponent" string instead of the variable.
pstmt.setString(1, "opponent"); -> pstmt.setString(1, opponent); should work now.

how to use datatable in jsp ? after retriving data in table form from database

I have created a jsp file which fetchs data from the database in table form now i have to use datatable so please someone suggest how to do it . in output it shows table which contains data in form of row and column but my sir asked to use datatable in it . so it will be a great help if someone can answer
CODE -
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("userId");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "xyz";
String userId = "1234";
String password = "1234";
try {
Class.forName(driverName);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<body>
<h2 align="center">Fetch Data From Database in Jsp</h2>
<table id="details" class="display" align="center" cellpadding="5" cellspacing="5" border="1">
<thead>
<tr>
<th><b>First Name</b></th>
<th><b>Last Name</b></th>
<th><b>Address</b></th>
</tr>
</thead>
<%
try{
connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);
statement=connection.createStatement();
String sql ="SELECT * FROM details";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tbody>
<tr>
<td><%=resultSet.getString("firstname")%></td>
<td><%=resultSet.getString("lastname") %></td>
<td><%=resultSet.getString("Address") %></td>
</tr>
</tbody>
<%
}
connection.close();
} catch (Exception ex) {
ex.printStackTrace();
}
%>
</table>
</body>
</html>

JSP search option

i have been trying to make it work for a long time now. but none of the reference works. so far these are my latest code regarding search. hopefully someone can help. i am new in jsp and this is final graduation project. so badly need help.
code:
index.jsp:
<div class="container">
<form class="form-inline" method="post" action="search.jsp">
<input type="text" name="roll_no" class="form-control" placeholder="Search roll no..">
<button type="submit" name="save" class="btn btn-primary">Search</button>
</form>
search.jsp:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "hospital";
String userid = "hospital";
String password = "hospital";
String NAME=request.getParameter("NAME");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<body>
<h1>Search Data</h1>
<table border="1">
<tr>
<td>CODE</td>
<td>NAME</td>
<td>PRICE</td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from product where NAME="+NAME+"' ";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("CODE") %></td>
<td><%=resultSet.getString("NAME") %></td>
<td><%=resultSet.getString("PRICE") %></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>

Integrating Eclipse with MySQL

I am facing a problem while integrating a web application developed in eclipse with a mysql database (mysql workbench).
below are the jsp files I used and the database name.
database username -- root
password -- 1234
Login.jsp
<%--
Document : Login
Created on : 28 Feb, 2015, 8:50:26 AM
Author : Lahaul Seth
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Demo with JSP</title>
</head>
<body>
<form method="post" action="userdetail.jsp">
<center>
<table border="1" cellpadding="5" cellspacing="2">
<thead>
<tr>
<th colspan="2">Login Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" name="username" required/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" required/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" />
<input type="reset" value="Reset" />
</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
</html>
userdetail.jsp
<%# page language="java" %>
<%# page import="org.owasp.esapi.ESAPI" %>
<%# page import="org.owasp.esapi.codecs.Codec" %>
<%# page import="org.owasp.esapi.codecs.MySQLCodec" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%! Connection con= null; %>
<%! Statement stmt= null; %>
<%! ResultSet rs= null; %>
<%! MySQLCodec mc= null; %>
<html>
<head><title>List Users</title></head>
<%
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
String uid = request.getParameter("uid");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException ce){out.println(ce);}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "1234");
stmt = con.createStatement();
String sql = "select * from userdetail where id = "+Integer.parseInt(uid);
//out.println(sql);
rs = stmt.executeQuery(sql);
%>
<body>
<br>
<br>
<div align="center"><b>You have Successfully Logged In Mr/Ms<%=uname%>, Your Details are :-</b></div>
<br>
<br>
<br>
<form action="view.jsp">
<table align="center">
<% while(rs.next()) {%>
<tr><td>First Name</td><td><input type=text name="fname" value='<%=rs.getString("firstname")%>' ></td></tr>
<tr><td>Last Name</td><td><input type=text name="lname" value='<%=rs.getString("lastname")%>'></td></tr>
<tr><td>Email</td><td><input type=text name="email" value='<%=rs.getString("email")%>'></td></tr>
<tr><td>Phone</td><td><input type=text name="phone" value='<%=rs.getString("phone")%>'></td></tr>
<tr><td>Address</td><td><input type=text name="address" value='<%=rs.getString("address")%>'></td></tr>
<%
}
rs.close();
stmt.close();
con.close();
}catch(SQLException exception){
//out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
//out.println("-->");
}
%>
</table>
</form>
</body>
</html>
auth.jsp
<%# page language="java" %>
<%# page import="org.owasp.esapi.ESAPI" %>
<%# page import="org.owasp.esapi.codecs.Codec" %>
<%# page import="org.owasp.esapi.codecs.MySQLCodec" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%! Connection con=null; %>
<%! Statement stmt= null; %>
<%! ResultSet rs= null; %>
<%! MySQLCodec mc= null; %>
<html>
<head><title>This is a Jdbc Example</title></head>
<body>
<%
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}catch(ClassNotFoundException ce){out.println(ce);}
try{
con = DriverManager.getConnection("jdbc:mysql://localhost/test:3306","root", "1234");
stmt = con.createStatement();
//String sql = "select * from user_detail where uname='" + uname +"' and pass='" + pass + "'";
mc = new MySQLCodec(0);
String sql = "SELECT * FROM userdetail WHERE uname = '" + ESAPI.encoder().encodeForSQL( mc, uname) + "' and pass = '" + ESAPI.encoder().encodeForSQL( mc, pass) +"'";
out.println(sql);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
boolean loggedIn = true;
//response.sendRedirect("userdetail.jsp?uid=1");
out.println("Successfully logged in");
} else {
//response.sendRedirect("login.jsp");
out.println("Username and/or password not recognized");
}
rs.close();
stmt.close();
con.close();
}catch(SQLException exception){
//out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
//out.println("-->");
}
%>
</body>
</html>
MySQL datatbase
Error page
Well, this sounds to be a class path issue. Could you please check MySQLCodec class present in WEB-INF/classes or present in any jar in WEB-INF/lib path.
You can double check the tomcat war directory. It should be in the below sample folder structure.

Why no files found using file uploading in Struts 2

I am using org.apache.commons.*, org.apache.commons.disk.*, org.apache.commons.fileupload.servlet.* packages for file uploading in JSP program and there was no need of Struts and it was working great, data easily worked with this, but when I added Struts 2 core libraries into my web project using MyEclipse 8.5 it is not working and have no fields found. May be the program is with upload.parseRequest.
Frankly, I am unable to understand the problem, so I share my program too
AddCategory.jsp:
<html>
<head>
<meta http-equiv="refresh" content="30">
</head>
<script type="text/javascript">
function blank() {
if (document.cate.cat.value == "Enter New Category") {
alert(" Category must not be blanked !!!");
document.cate.cat.focus();
return false;
}
else if (!document.getElementById("file1").value) {
alert("No file selected");
return false;
}
else {
return true;
}
}
</script>
<form name="cate" action="CategoryAdded.jsp" method="post" enctype="multipart/form-data" onsubmit="return blank()">
<table width="100%" border="0">
<tr>
<th colspan="2" scope="col">
<div align="center">Create New Category</div>
</th>
</tr>
<tr>
<td width="50%">
<div align="right">Enter New Category:</div>
</td>
<td width="50%">
<input name="cat" type="text" id="cat" value="Enter New Category"
onFocus="if(this.value== 'Enter New Category'){ this.value='' ; this.style.background='white';}"
onBlur="if(this.value==''){this.value='Enter New Category'; this.style.background='lightyellow'}">
</td>
</tr>
<tr>
<td width="50%">
<div align="right">Upload photo:</div>
</td>
<td width="50%"><input name="file1" type="file" id="file1"></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" name="Submit" value="Add Category">
</div>
</td>
</tr>
</table>
</form>
</html>
CategoryAdded.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%#page import="java.io.*" %>
<%# page language="java" errorPage="" %>
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.io.*" %>
<%#page import="java.util.Iterator,java.util.List" %>
<%#page import="org.apache.commons.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*" %>
<%# page import="java.util.*" %>
<%#page import="org.apache.commons.fileupload.FileItemFactory" %>
<%#page import="org.apache.commons.fileupload.FileItem" %>
<%#page import="org.apache.commons.fileupload.FileUploadException" %>
<%#page import="p1.DBInfo" %>
<%#page import="p1.Identy" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<%
String pname = "";
Identy id = new Identy();
String cod = id.code();
boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
if (!isMultipartContent) {
System.out.println("No multipart found");
return;
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
System.out.println("No fields found");
return;
}
DBInfo obj = new DBInfo();
Connection cn = obj.getConn();
PreparedStatement ps = cn.prepareStatement("insert into category values(?,?,?)");
while (it.hasNext()) {
FileItem fileItem = it.next();
if (fileItem.getFieldName().equals("cat")) {
pname = fileItem.getString();
System.out.println("category name is " + pname);
}
boolean isFormField = fileItem.isFormField();
if (!isFormField) {
String s = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);
fileItem.write(new File("D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s));
System.out.println(s);
fileItem.getOutputStream().close();
ps.setString(3, "D:\\Practice\\ShoppingCart\\WebRoot\\images\\" + s);
}
}
ps.setString(1, pname);
ps.setString(2, pname + cod);
int i = ps.executeUpdate();
if (i == 1) {
%>
<head>
<script type="text/javascript">
function myFunction() {
var r = confirm("New Category Added Successfully!!!\nIf you Want to Add more New Category then Press Ok!!!");
if (r == true) {
window.location = "AddCategory.jsp";
}
else {
window.location = "Tryy.jsp";
}
}
</script>
</head>
<body onload="myFunction()">
</body>
<%
}
cn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</html>
The best thing is to rewrite the JSPs to remove scriptlets and move business logic to the action classes.
You could also use Struts2 <s:if> and <s:else> tags to render content conditionally.
The commons-fileUpload is the default implementation for uploading files in Struts2, to use it correctly you could run an example Struts2 project like struts-2-upload-multiple-files-example.

Categories

Resources