JSP search option - java

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>

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>

In my jsp page I am trying to insert values to database but I dont see any error, page refreshes and the data is not inserted

Here is my code.
<%--
Document : index
Created on : Jan 16, 2016, 2:49:24 PM
Author : Manoj
--%>
<%#page import="java.sql.*"%>
<% Class.forName("org.apache.derby.jdbc.ClientDriver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Inserting Data</title>
</head>
<body>
<h1>Inserting Data</h1>
<%!
public class Contact {
String URL = "jdbc:derby://localhost:1527/contact";
String USERNAME = "nbuser";
String PASSWORD = "nbuser";
Connection conn = null;
PreparedStatement pst = null;
Statement stm = null;
ResultSet rst = null;
public Contact(){
try{
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
pst = conn.prepareStatement(
"INSERT INTO contactinfo (name, address, mobile)"+" VALUES (?, ?, ?)");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public int setContact(String name, String address, String mobile)
{
int result =0;
try{
pst.setString(1, name);
pst.setString(2, address);
pst.setString(3, mobile);
result = pst.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
return result;
}
}
%>
<%
int result = 0;
if(request.getParameter("submit") != null){
String name = new String();
String address = new String();
String mobile = new String();
if (request.getParameter("name")!= null)
{
name = request.getParameter("name");
}
if (request.getParameter("address")!= null)
{
address = request.getParameter("address");
}
if (request.getParameter("mobile")!= null)
{
mobile = request.getParameter("mobile");
}
Contact contact = new Contact();
result = contact.setContact(name, address, mobile);
}
%>
<form name="myform" action="index.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="" size="30" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value="" size="50" /></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" value="" size="10" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="clear" />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
Kindly help me. This is the first time I am writing a JSP code.
The database I am using is Apache derby within Neatbeans 8.1. I tried all alternatives but could not find a solution. When I manually insert a row into the database it is inserting the values.
You can try to debug your code and check whether if(request.getParameter("submit") != null) is returning TRUE or FALSE.
As I doubt because you have used a
<input type="submit" value="Submit" name="submit" />
where value is with capital S

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.

sql statement not working in jsp

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.

Categories

Resources