java - jsp update database row via form on submit - java

Hi im trying to update data from database using submit button , witch is located on a jsp page that shows data based on name and surname that you entered in login.jsp..
validationForDatabase.jsp shows data from the table pacijent,based on name and surname are entered in another jsp page. Fields name and surname are readonly so you can chage everything except those fileds, and when you make chages and press button Update it should redirect you to update.jsp. If the update is successful you sholud be redirected back to validationForDatabase.jsp but instead of doing that it shows me Badly entered data from else section.
Could you please guide me on how to fix this problem or maybe another way to do this.
Thanks in advance
validationForDatabase.jsp
`
<%
try{
String name= request.getParameter("name");
String surname= request.getParameter("surname");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/sth","root","");
PreparedStatement pst = conn.prepareStatement("Select name,surname from pacijent where name=? and surname=?");
pst.setString(1, name);
pst.setString(2, surname);
ResultSet rs = pst.executeQuery();
if(rs.next())
{
out.println("Name of the patient : "+name);
out.println("<br/>Surname of the patient : "+surname);
HttpSession sesija = request.getSession();
sesija.setAttribute("name", name);
sesija.setAttribute("surname", surname);
%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String connectionUrl = "jdbc:mysql://localhost:3306/sth";
try {Class.forName("com.mysql.jdbc.Driver");}
catch (ClassNotFoundException e) {e.printStackTrace();}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<form action="Update.jsp" method="get">
<%
try{
connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/sth","root","");
statement=connection.createStatement();
String sql ="SELECT name,father,surname,birth,adress,phone,email,notes "+ "FROM pacijent where name='"+sesija.getAttribute("name")+"'and surname='"+surname+"';";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<p align="center"><%= sesija.getAttribute("name")%><%= sesija.getAttribute("surname")%></p>
<p><label class="uname">name</label><input name="name" readonly value="<%=sesija.getAttribute("name") %>"/></p>
<p><label class="uname">father</label><input name="father" value="<%=resultSet.getString("father") %>"/></p>
<p><label class="uname">surname</label><input name="surname" readonly value="<%=sesija.getAttribute("surname") %>"/></p>
<p><label class="uname">birth</label><input name="birth" value="<%=resultSet.getString("birth") %>"/></p>
<p><label class="uname">Adress</label><input name="adress" value="<%=resultSet.getString("adress ") %>"/></p>
<p><label class="uname">phone</label><input name="phone" value="<%=resultSet.getString("phone") %>"/></p>
<p><label class="uname" > E-mail</label><input name="email" value="<%=resultSet.getString("email") %>"/></p>
<p><label for="usernamesignup" class="uname">info</label>
<textarea name="notes" id="a" class="a" rows="4" cols="60"
textareaObject.value="text" ><%= resultSet.getString("notes") %></textarea></p>
<input type="submit" name="Submit" value="Update" />
</form>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
sesija.invalidate();
%>
<%
}
else{
%>
<br/><br/><br/><br/><br/><h1 align="center">Badly entered data</h1>
<%}
}
catch(Exception e){
out.println("Error "+e);
}
%>`
Update.jsp works in redirecting back but it wont update data.
Update.jsp
`
<%
String name=request.getParameter("name");
String father=request.getParameter("father");
String surname=request.getParameter("surname");
String birth=request.getParameter("birth");
String adress =request.getParameter("adress ");
String phone=request.getParameter("phone");
String email=request.getParameter("email");
String notes=request.getParameter("notes");
try {
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sth", "root", "");
Statement st1 = null;
st1 = conn.createStatement();
HttpSession sesija = request.getSession();
sesija.setAttribute("name", name);
System.out.println(sesija.getAttribute(name));
st1.executeUpdate("UPDATE pacijent SET name= '"+name+"',father= '"+father+"',"
+ "surname= '"+surname+"',birth= '"+birth+"',adress = '"+adress +"',"
+ "phone= '"+phone+"',email = '"+email+"',notes = '"+notes+"'"
+ "WHERE name="+sesija.getAttribute(name));
response.sendRedirect("validationForDatabase.jsp");
} catch (Exception e) {
out.println("Error : " + e);
}
%>`
Thanks a lot.

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.

Dynamic dropdown returns a null from jsp

I have written a dropdown list which is populated by the database. This is my dropdown code in JSP file.
<td>Category:</td>
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
String cname = rs.getString("category_name");
String id = rs.getString("category_id");
System.out.println(id);
%>
<option value="<%= id%>"><%= cname%></option>
<%
}
%>
</select>
<%
} catch (SQLException sqe) {
out.println(sqe);
}
%>
</td>
The relevant servlet code is;
String id = request.getParameter("category");
In the sout of the dropdown in JSP it prints all the IDs in the category. But when it comes to the servlet it returns a null. How to resolve this issue?
I didn't find any <form> tag neither submit button in your code ,try below code :
<td>Category:</td>
<form method="post" action="yourservleturl">//form tag for submitting data
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
%>
<option value="<%=rs.getString("category_id")%>"><%=rs.getString("category_name")%></option> // printing option values
<%
}
%>
</select>
<%
} catch (SQLException sqe) {
out.println(sqe);
}
%>
<input type="submit" value="submit">///submit btn
</form>
</td>
also get, dropdown value by String id = request.getParameter("category"); .it should worked .
The local variable should be sound out of while loop, because you need that value after while loop.
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
String cname = null;
String id = null;
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
cname = rs.getString("category_name");
id = rs.getString("category_id");
System.out.println(id);
%>
Besides, I suggest you use Expression Language instead of <%= id%>
change
<option value="<%= id%>"><%= cname%></option>
to
<option value="${id}">${name}</option>
And don't forget submit button.

Image saved into database not showing

So i'm tryna save a blob image into database and display it once i click"view" href. But I don't know why the pic cannot be seen. It saves in mysql database tho...
retrieve_image.jsp:
<%# page import="java.sql.*,model.Upload,java.io.*,java.util.*" %>
<HTML>
<table border="1">
<tr><th>ID</th><th>Image</th></tr>
<%
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/backup","root","mysql");
Statement stmt=con.createStatement();
String strQuery = "select * from contacts";
ResultSet rs = stmt.executeQuery(strQuery);
while(rs.next()){
%>
<tr>
<td><%=rs.getInt("contact_id")%></td>
<td>
<img src="RetrieveImages.java?id=<%=rs.getInt(1)%>" width="100" height="100">
</a></td>
</tr>
<%
}
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
%>
</table>
</HTML>
RetrieveImages is a servlet which has request dispatcher that goes to...
<%#page import="java.sql.Blob"%>
<%#page import="java.io.OutputStream"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page import="model.Upload" %>
<%
String contact_id = request.getParameter("contact_id");
String dbURL = "jdbc:mysql://localhost/backup";
String dbUser = "root";
String dbPass = "mysql";
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbURL, dbUser, dbPass);
PreparedStatement ps = con.prepareStatement("select * from contacts where contact_id=?");
ps.setString(1, contact_id);
ResultSet rs = ps.executeQuery();
if(rs.next()){
Blob blob = rs.getBlob("photo");
byte byteArray[] = blob.getBytes(1, (int)blob.length());
response.setContentType("image");
OutputStream os = response.getOutputStream();
os.write(byteArray);
os.flush();
os.close();
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(con != null){
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
%>
In my java bean i have contact_id and photo as attribuites

Login jsp error in DWP (Eclipse)

i've to build a dynamic web project in Eclipse(Moon) with Tomcat 7.0 and mysql database (5.1). I've created a java class for users, a connector java class between jsp and mysql and the jsp pages with a login/registration forms.
This is the user.java class:
package cop;
public class Company {
public String name = "";
public String username = "";
public String password = "";
public String email = "";
public String country = "";
public String address = "";
public Company(String username, String password){
this.username = username;
this.password= password;
}
}
This is the connector .java class:
public static Company DB_login1(String user, String pass){
Company co = null;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/Mysql?user=root&password=root");
PreparedStatement pst = con.prepareStatement("SELECT username "
+ "FROM Companies "
+ "WHERE username = '"+user+"' AND password = '"+pass+"'");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
while (rs.next()){
String username = rs.getString("username");
String password = rs.getString("password");
co = new Company(username, password);
}
con.close();
}
catch (Exception e) {
System.out.println("Unable to connect to DB");
e.printStackTrace();
}
return co;
}
And at last this is the login.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="cop.*" import="java.util.*"%>
<!DOCTYPE html>
<html lang="en-US">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<div id="head">
<title>The Music Shop</title>
</div>
<div id="titles">
<text id="t1"> The Music Shop </text> <br>
<text id="t2"> The new way of buying is here </text>
</div>
<div id="login">
<form id="login_form" action="company-login.jsp" method="POST" accept-charset="utf-8">
<ul>
<li> <label for="user"> Username </label>
<input type="text" name="user" required></input></li>
<li> <label for="pass"> Password </label>
<input type="text" name="pass" required></input></li>
<li>
<input type="submit" value="Submit"> </li>
</ul>
</form>
</div>
<% String user = request.getParameter("user");
String pass = request.getParameter("pass");
Company co = Dbcon.DB_login1(user , pass);
if (co == null){
response.sendRedirect("home.jsp?err=1");
}
else{
response.sendRedirect("home.jsp");
}
%>
When i run the jsp page on Tomcat, immediately it redirects me to the "home.jsp?err=1" page, and it doesn't display the html page. Has anyone any suggestions to fix it?
Thanks in regard.
String user = request.getParameter("user");
String pass = request.getParameter("pass");
Company co = Dbcon.DB_login1(user , pass);
if (co == null){
response.sendRedirect("home.jsp?err=1");
}
else{
response.sendRedirect("home.jsp");
}
if you run your jsp page without passing any parameters(user,pass) , Dbcon.DB_login1(user , pass); will get null as both arguments . Your query will not return any results and co will remain assigned to null and so Dbcon.DB_login1(user , pass); returns null to your jsp. which then satisfies your if condition and the page gets redirected.
change
PreparedStatement pst = con.prepareStatement("SELECT username "
+ "FROM Companies "
+ "WHERE username = '"+user+"' AND password = '"+pass+"'");
to
PreparedStatement pst = con.prepareStatement("SELECT username "
+ "FROM Companies "
+ "WHERE username = '"+?+"' AND password = '"+?+"'");
Check your console, there must be some error trace.
Add System.out.println(e) as well so that if trace is disabled you can able to see the error in console
catch (Exception e) {
System.out.println("Unable to connect to DB");
System.out.println(e);
e.printStackTrace();
}

No output on browser from my jsp page?

second.jsp
<%#page import="java.sql.*" %>
<html>
<body>
<%
try{
String id2=(request.getParameter("ID1"));
String url="jdbc:ucanaccess://C:\\Users\\Asim Iqbal\\Documents\\IT.accdb";
Connection conn = DriverManager.getConnection(url);
String sql= "SELECT * FROM Student WHERE ID=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1,id2);
ResultSet rs = stmt.executeQuery();
if (rs.next())
{
int i=rs.getInt("ID");
String nam=rs.getString("Name");
String clas=rs.getString("Class");
String ph=rs.getString("Phone");
%>
<h1><%=i%></h1>
<h1><%=nam%></h1>
<h1><%=clas%></h1>
<h1><%=ph%></h1>
<%
}
} catch (SQLException e) {
e.printStackTrace();
}
%>
</body>
</html>
No output comes from DB in the browser..
Please give me suggestion where i am getting wrong...

Categories

Resources