update database record through html page using servlets - java

my request is going to update query in the else if condition but the records are not updating in the database
help me out of this situation
I didn't get any errors after clicking on update button the database record is not inserted in the database
// imports ...
public class RequestData extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<html>");
out.print("<title>DataRetreving</title>");
out.print("<body>");
out.print("<table border=5 width=50% height=50% bgcolor=magenta align=center>");
out.print("<tr>");
out.print("<th><b>id</b></th>");
out.print("<th><b>name</b></th>");
out.print("<th><b>address</b></th>");
out.print("<th><b>action</b></th>");
out.print("<th><b>actionupdate</b></th>");
out.print("</tr>");
Driver driver = new OracleDriver();
try {
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE", "system",
"india124");
Statement pst = connection.createStatement();
if(request.getParameter("action")!=null && "delete".equals(request.getParameter("action")))
{
int id=Integer.parseInt(request.getParameter("id"));
pst.executeUpdate("delete from employee where id="+id);
}
else if(request.getParameter("id") != null
&& request.getParameter("name") != null
&& request.getParameter("address") != null
&& request.getParameter("update") != null
&& !"update".equals(request.getParameter("actionupdate")))
{
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String address = request.getParameter("address");
pst.executeQuery("insert into employee(id,name,address)"+"values("+id+",'"+name+"','"+address+"')");
}
else if(request.getParameter("actionupdate")!=null
&& "update".equals(request.getParameter("actionupdate"))) {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String address =request.getParameter("address");
pst.executeUpdate("update employee set address='"+address+"',name='"+name+"'where id="+id+"");
}
ResultSet rst=pst.executeQuery("select *from employee");
while (rst.next())
{
out.print("<tr>");
out.print("<td align=center bgcolor=yellow><b> " + rst.getInt("id") + "</b></td>");
out.print("<td align=center><b>" + rst.getString("name") + "</b></td>");
out.print("<td align=center><b>" + rst.getString("address") + "</b></td>");
out.print("<form align=center action=\"./requestdata\">");
out.print("<td align=center bgcolor=yellow><a href=\"http://localhost:8082/RequestDataDemo/requestdata?id="
+rst.getInt("id")+"&action=delete\">DELETE</a></td>");
out.print("<td align=center bgcolor=yellow><a href=\"http://localhost:8082/RequestDataDemo/requestdata?id="
+rst.getInt("id")+"&name="+rst.getString("name")+"&address="+rst.getString("address")+"&actionupdate=update\">UPDATE</a></td>");
out.print("</tr>");
}
out.print("</table>");
out.print("<br><br>");
if(request.getParameter("actionupdate")!=null && "update".equals(request.getParameter("actionupdate"))) {
out.print("<form align=center action=\"./requestdata\">");
out.print("enter id :<input type=\" text\" name = \" id \" value="+request.getParameter("id")+"><br><br>");
out.print("enter name: <input type=\"text\" name = \"name\" value="+request.getParameter("name")+"><br><br>");
out.print("enter address:<input type=\"text\" name = \"address \" value="+request.getParameter("address")+"><br><br>");
out.print(" <input type=\"submit\" value =\"update\"><br><br>");
out.print("</form>");
}
else
{
out.print("<form align=center action=\"./requestdata\">");
out.print("eneter id :<input type=" + "text" + " name = " + "id><br><br>");
out.print("eneter name: <input type=" + "text" + " name = " + "name><br><br>");
out.print("eneter address:<input type=" + "text" + " name = " + "address><br><br>");
out.print(" <input type=" + "submit" + " value = " + "submit><br><br>");
out.print(" <input type=" + "reset><br><br>");
/* out.print("<input type='submit' value='delete'>"); */
out.print("</form>");
}
out.print("</body>");
out.print("</html>");
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
out.close();
}
}
my request is going to update but the records are not updating in the database
help me out of this situation
I didn't get any errors after clicking on update button the database record is not inserted in the database

I agree to all the comments that you should refactor this code. But for a first try I guess it is important to see it working.
I think you have a bit of a logical problem here: What exactly do you send when you insert a new record? I couldn't find that part.
I am guessing you want the insert block to run, so this condition:
else if(request.getParameter("id") != null&&request.getParameter("name")!=null&&request.getParameter("address")!=null &&request.getParameter("update")!=null &&!"update".equals(request.getParameter("actionupdate") ))
to be true. But if you look at the end of the line you want the "update" parameter to be present and "actionupdate" to be different than "update". But you are not setting these in your code. So this condition will always be false, hence the insert is never called.
When you press a submit button a parameter submit="" is sent to the server. This way you can tell which button was clicked. So maybe add a submit button with value="insert" and test if that is present to enter in the INSERT block.
Again, try to make this work by revisiting all your conditions and parameters and see when/if they are set and when they are true or not. And after that absolutely spend some time refactoring and practicing better techniques.

Related

Servlet in Java. How to retrieve attributes?

I am really struggling with this problem. I am storing names and addresses of users as session variables on the server. In the else if statement, I want to search through previously entered names to match a name that is entered (with the address field blank), to the corresponding address that was entered for that name.
For example:
First entered details: Name=John, Address=Ireland,
Second entered details: Name=Mary, Address=France,
Third entered details: Name=John, Address=null,(EMPTY FIELD)
When these third details are entered for 'John', I want to retrieve the address for John (ie:Ireland) that was previously entered for that user. Can't figure out why it won't work. Any help is appreciated. Thanks
#WebServlet("/Test2") // tells server under which URL to offer this servlet
public class UserRegistration extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" + "<head><title>Online Shopping Directory</title></head>");
//Get the identifier of the book to display
out.println("<body bgcolor=\"#ffffff\">"
+ "<h2>Please enter your name:</h2>" + "<form method=\"get\">"
+ "<input type=\"text\" name=\"username\" size=\"25\">"
+ "<p></p>"
+ "<h2>Please enter your address:</h2>" + "<form method=\"get\">"
+ "<input type=\"text\" name=\"useraddress\" size=\"25\">"
+ "<p></p>"
+ "<input type=\"submit\" value=\"Submit\">"
+ "<input type=\"reset\" value=\"Reset\">"
+ "</form>");
String name = request.getParameter("username");
String address = request.getParameter("useraddress");
HttpSession session = request.getSession(true);
if ((name != null) && (name.length() > 0) && (address != null) && (address.length() > 0)) {
session.setAttribute("username", address);
out.println("The username " + name + " has been saved for "
+ "this session. The address of this user is "
+ (String) session.getAttribute("username"));
} else if ((name.equals("username")) && (address == null)) {
out.println("The username " + name + " is already saved. "
+ "The address of this user is "
+ (String) session.getAttribute("username"));
}
out.println("</body></html>");
out.close();
}
}
you have to do something like the following :
if ((name != null) && (name.length() > 0) ){
session.setAttribute("username", name);
out.println("The username " + name );
}else {
out.println("The username " + (String) session.getAttribute("username") );
}
if ((address != null) && (address.length() > 0)){
session.setAttribute("address", address);
out.println("The address " + adress );
}else {
out.println("The address " + (String) session.getAttribute("address") );
}
and please give me some feedback .
Hope That helps .
If you want a list to pop up, if the user enters a certain prefix to an already entered text, you have to store text first. Use a list object to add the information when it is submitted to the server and store it in the user's session. Keep in mind, that when the session times out or is removed, your list will not longer be available. To store the list of entered information in a more persistent manner, you could use a database instead.
When the user requests the page, where the information should be entered, you retrieve the list from her session and write it to the page (look for auto suggestion box to find out, how to do it using javascript).
You are actually creating a new session instance evertime, you should get the session instance associated with the request while you need to retrieve the attributes
Use request.getSession(false); this will return the associated session with the request or return null. you should be careful in handling sessions while managing sessions, that is when to create a new one or retrieve the session that had been created for the user

how to add value listbox with another listbox java struts?

i want to use two listbox (multiple) on java struts enviroment. first listbox is listed personel names and second listbox is blank at first. With add and remove buttons fill up second listbox with value from selected first listbox. But i don t know how to use this?
value is string array or collection to getter/setter? and how to use?
furthermore i know javascript code how is making but struts is complex.
my code is:
JSP :
first listbox and second listbox
< td class="formitem">
< html:select multiple="true" size="4" styleClass="textField" >
< html:options collection="pName" property="deger" labelProperty="pers"/>
</html:select>
</td>
<td class="formitem">
<html:select property="personelName" styleClass="textField" >
<html:options collection="personelList" property="deger" labelProperty="xxx"/>
</html:select>
</td>
my form code is
private String[] pName = null; is string array or another type?
public String[] getpName() {
return pName;
}
public void setpName(String[] pName) {
this.pName = pName;
}
model class
public static Collection personelFill(String x) {
{
Connection connection = null;
PreparedStatement pst = null;
ResultSet rs = null;
ArrayList personelList = null;
try {
connection = DBFactory.getConnection();
String sql =
"select p.adi || ' ' || p.soyadi isim, p.tckimlikno , p.subeno, p.daireno " +
"from personel p " +
"where p.listedegorunsun = 1 "
+ x
+ "order by nlssort(p.adi||' '||p.soyadi,'NLS_SORT = TURKISH')";
pst = DBFactory.getPreparedStatement(connection, sql);
rs = pst.executeQuery();
personelList = new ArrayList();
PersonelForm pForm = null;
while (rs.next()) {
pForm = new PersonelForm();
//fill form setter
personelList.add(pForm);
}
return personelList;
} catch (Exception e) {
throw new BDException(e.getMessage());
} finally {
DBFactory.closeConnection(connection, pst, rs);
}
}
}
It's nothing to do with serverside. It can be done on the client side using javascript or jquery
see the following jsfiddle and original post.
http://jsfiddle.net/RbLVQ/62/
$('#btnRight').click(function(e) {
var selectedOpts = $('#lstBox1 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});

Chat app popup a window at client

I made a simple chat app. It uses database, this is not efficient cause the client queries database every few sec. Any way, I achieved what i needed, There are good ways out there like polling and commet, I will implement those later. Please take time to read abt this, I have few probs with this.
1) Consider two users 100 and 101, When 100 sends a msg to 101, i am saving the id as 100_101 in DB
2) When 101 send back msg to 100 it is saved as 101_100 in DB.
3) I am able to get the messages in order.
Problem-
1) Users should keep tht particular window open.
I want popup to open when there is new message. How to achieve that.
2) When a user(100) is typing user(101) should see the text as "100 is typing" if 101 chat window with 100 is open only. This should not involve any database stuff.
Work I have done. I can send data to server when user(100) starts typing to server. How to send data, i.e how to push data to user(101).
My presnt code is below.
ajax
$.ajax( {
type : "POST",
data : "uName=" + uName +"&opName=" + opName + "&msg=" + msg + "&colorCode="
+ colorCode,
url : "<%= path %>/chat/SaveChat",
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
},
success : function(data) {
// alert(data);
$("#chat-area").html(data);
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
}
});
Servlet
try {
String newline = System.getProperty("line.separator");
String uName = req.getParameter("uName");
String opName= req.getParameter("opName");
String msg = req.getParameter("msg");
String colorCode = req.getParameter("colorCode");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String dat =dateFormat.format(date);
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO chatmessage"
+ "(message,username,msgtime,colorselected) "
+ " VALUES(?,?,?,?)");
ps.setString(1,msg);
ps.setString(2,uName+"_"+opName);
ps.setString(3,dat);
ps.setString(4,colorCode);
ps.executeUpdate();
ps.close();
ps = db.conn.prepareStatement("select * from chatmessage where username=? or username=? order by id asc");
ps.setString(1,uName+"_"+opName);
ps.setString(2,opName+"_"+uName);
ResultSet rs=ps.executeQuery();
String temp[];
StringBuilder sb = new StringBuilder();
while(rs.next())
{
temp=rs.getString("username").split("_");
/* out.println(newline);
out.print(temp[0]+":");
out.print(rs.getString("message"));
out.println(newline);*/
sb.append("<span style='background:#"
+ rs.getString("colorselected") + "'>" + temp[0]
+ "</span>" + rs.getString("message") + "<br/><br/>");
}
db.conn.close();
out.print(replaceEmoticons(sb.toString()));
//out.print("success");
}
catch(Exception ce){
out.println("<font size='30' color='red'>Error Code 004</font>");
// RequestDispatcher rd = req.getRequestDispatcher("../status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
}catch(Exception e){}
}
Thankyou any easy and valid ideas are appreciated.

Creating a random password generates a password with length 0: Blame JavaScript or Java Servlet?

When my users forget their passwords, they are sent to the page shown below. I generate a random password in JavaScript, encrypt it, and send both the plain text and md5 hash to a Servlet. The Servlet then e-mails the password to the user and stores the md5 hash in my database. This process works fine most of the time. But for some reason frequently generates an error where the generated password has length 0.
I tested my JavaScript code separately and had it generate hundreds of passwords. None had length 0. So where is this error coming from?
Here is the HTML form:
//This method returns a randomly generated mathy password.
function randomPassword(theForm) {
first = ["Euler", "Erdos", "Newton", "Eucl1d", "Gauss", "H1lb3rt", "Cantor", "Bernoulli", "PascaL"];
second = ["Const", "Number", "Theorem", "Prime", "Ratio", "Lemma", "Postulate", "Method", "Algorithm"];
symbol = ["!","#","#","$","%","^","&","*","_","+","-","?"];
a = Math.floor(Math.random() * first.length);
b = Math.floor(Math.random() * second.length);
n = Math.floor(Math.random() * 10);
style = Math.floor(Math.random() * 3); //0,1, or 2
if(style==0) password = first[a] + n + second[b];
else if(style==1) password = first[a] + second[b] + n;
else password = first[a] + second[b] + symbol[n];
theForm['newPass'].value = password;
theForm['passwordLog'].value = "style="+style + " a=" + a + ", b=" + b+ ", n=" + n;
hashField = theForm['passHash'];
hashField.value = hex_md5(password);
theForm.submit();
}
<body>
<h2>You can reset your password below.</h2>
<form action="ResetPassword" method="post" >
Enter your e-mail address:
<input type="text" name="eMail" id="eMail" size="20"/> <br />
<input type="button" value="Reset Password" onclick="randomPassword(this.form);" />
<input type="hidden" id="passHash" name="passHash" />
<input type="hidden" id="newPass" name="newPass" />
<input type="hidden" id="passwordLog" name="passwordLog" />
</form><br/>
<strong>Attention Coaches: If you are having trouble logging into this system,
please contact the scorekeeper: llaspina#bethpage.ws </strong>
</body>
And here is the Servlet that receives the form data sent from the above file:
#WebServlet(name = "ResetPasswordServlet", urlPatterns = {"/ResetPassword"})
public class ResetPasswordServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ConnectionPool pool = ConnectionPool.getInstance();
java.sql.Connection con = pool.getConnection();
String emailAddress = request.getParameter("eMail");
String newPass = request.getParameter("newPass");
String passHash = request.getParameter("passHash");
String log = request.getParameter("passwordLog");
try {
Coach coach = null;
ArrayList<Coach> coachList = MathTeamDAO.getAllCoaches(con);
for(Coach c : coachList) {
if(c.email.equals(emailAddress) ) {
coach = c;
break;
}
}
out.println("<html><head><title>Scorekeeper Reset Password Servlet</title></head>");
out.println("<body>");
out.println("<h1>Reset Password Servlet</h1>");
if(coach==null) {
out.println("Your email address was not found in our database.<br/>" +
"Please contact the scorekeeper or the secretary to gain access to the sytem.");
}
else {
if(newPass == null || newPass.length()<3) {
out.print("An error occurred while generating a random password. The randomly generated password came back as ");
out.print(newPass);
out.println(" Please try to reset your password again.");
String errorMsg = "An error was encountered while attempting a password reset. ";
if(newPass==null)
errorMsg += "null newPass generated.";
else
errorMsg += " The newPass had length " + newPass.length() + " and =" + newPass;
if(log!=null)
errorMsg += ("\n" + log);
if(UtilityServlet.emailAnError(coach,errorMsg, this.getServletName() + " at " + this.getServletName()))
out.println("<br/>The scorekeeper was just informed of this error through email, so you do not need to report it.");
}
else {
out.println("<h3>Check your email for your new password and directions for signing into the scorekeeper system.</h3>");
out.print("Sending new password to " + coach.email + "<br/>");
ChangePasswordServlet.changePassword(con, coach.schoolID, passHash);
School herSchool = MathTeamDAO.getSchoolByCoach(con, coach);
String emailServerMessage = ChangePasswordServlet.sendPasswordEmail(coach, herSchool.shortName, newPass);
if(herSchool!=null) {
out.print("<br/>The username for " + herSchool.fullName);
out.print(" is <strong>");
out.print(herSchool.username);
out.println("</strong><br/>");
}
out.print(emailServerMessage);
}
out.flush();
}
out.println("<br/>Return to <a href=\"login.jsp\" >login page.</a>");
out.println("</body></html>");
}
catch(java.sql.SQLException utoh) { }
finally {
pool.freeConnection(con);
out.close();
}
}
Notice that I am having error messages sent to myself if the password is null or too short. This happens fairly regularly and they always have length 0. Why?
With the comment in the middle of this line:
else //if(style==2) password = first[a] + second[b] + symbol[n];
you are going to get undefined passwords in about a third of the cases...
else //if(style==2) password = first[a] + second[b] + symbol[n];
theForm['newPass'].value = password;
With the comment there, the else is now affecting theForm['newPass'].value = password;, meaning the value will not be set, causing an empty password.
This is why using {} is recommended even if you only have one statement.

Google books API searching by ISBN

I am trying to figure out how to search for a book by ISBN using the Google Books API. I need to write a program that searches for an ISBN then prints out the title, author, and edition. I tried using List volumesList = books.volumes.list(""); but that did not allow me to search by ISBN and I did not see a way to get the information I needed(when an ISBN was placed in it had no results) . What I have right now is:
JsonFactory jsonFactory = new JacksonFactory();
final Books books = new Books(new NetHttpTransport(), jsonFactory);
List volumesList = books.volumes.list("9780262140874");
volumesList.setMaxResults((long) 2);
volumesList.setFilter("ebooks");
try
{
Volumes volumes = volumesList.execute();
for (Volume volume : volumes.getItems())
{
VolumeVolumeInfo volumeInfomation = volume.getVolumeInfo();
System.out.println("Title: " + volumeInfomation.getTitle());
System.out.println("Id: " + volume.getId());
System.out.println("Authors: " + volumeInfomation.getAuthors());
System.out.println("date published: " + volumeInfomation.getPublishedDate());
System.out.println();
}
} catch (Exception ex) {
// TODO Auto-generated catch block
System.out.println("didnt wrork "+ex.toString());
}
If anyone has any suggestions about how to make this more efficient let me know.
New Code:
String titleBook="";
////////////////////////////////////////////////
try
{
BooksService booksService = new BooksService("UAH");
String isbn = "9780262140874";
URL url = new URL("http://www.google.com/books/feeds/volumes/?q=ISBN%3C" + isbn + "%3E");
VolumeQuery volumeQuery = new VolumeQuery(url);
VolumeFeed volumeFeed = booksService.query(volumeQuery, VolumeFeed.class);
VolumeEntry bookInfo=volumeFeed.getEntries().get(0);
System.out.println("Title: " + bookInfo.getTitles().get(0));
System.out.println("Id: " + bookInfo.getId());
System.out.println("Authors: " + bookInfo.getAuthors());
System.out.println("Version: " + bookInfo.getVersionId());
System.out.println("Description: "+bookInfo.getDescriptions()+"\n");
titleBook= bookInfo.getTitles().get(0).toString();
titleBook=(String) titleBook.subSequence(titleBook.indexOf("="), titleBook.length()-1);
}catch(Exception ex){System.out.println(ex.getMessage());}
/////////////////////////////////////////////////
JsonFactory jsonFactory = new JacksonFactory();
final Books books = new Books(new NetHttpTransport(), jsonFactory);
List volumesList = books.volumes.list(titleBook);
try
{
Volumes volumes = volumesList.execute();
Volume bookInfomation= volumes.getItems().get(0);
VolumeVolumeInfo volumeInfomation = bookInfomation.getVolumeInfo();
System.out.println("Title: " + volumeInfomation.getTitle());
System.out.println("Id: " + bookInfomation.getId());
System.out.println("Authors: " + volumeInfomation.getAuthors());
System.out.println("date published: " + volumeInfomation.getPublishedDate());
System.out.println();
} catch (Exception ex) {
System.out.println("didnt wrork "+ex.toString());
}
Are you using the deprecated data API?
With Books API v1 (from Labs) you could use the query
https://www.googleapis.com/books/v1/volumes?q=isbn:<your_isbn_here>
for example
https://www.googleapis.com/books/v1/volumes?q=isbn:0735619670
to query a book by its ISBN.
You may want to look at Googles example code: BooksSample.java
Can't you try like this as said in the developers guide developer guide if I did understand your task. You can do like this :
BooksService booksService = new BooksService("myCompany-myApp-1");
myService.setUserCredentials("user#domain.com", "secretPassword");
String isbn = "9780552152679";
URL url = new URL("http://www.google.com/books/feeds/volumes/?q=ISBN%3C" + isbn + "%3E");
VolumeQuery volumeQuery = new VolumeQuery(url);
VolumeFeed volumeFeed = booksService.query(volumeQuery, VolumeFeed.class);
// using an ISBN in query gives only one entry in VolumeFeed
List<VolumeEntry> volumeEntries = volumeFeed.getEntries();
VolumeEntry entry = volumeEntries.get(0);
Now using the VolumeEntry api look for your desired getXXXX() and use it in your code.I hope it will help you to solve your problem.
$("form").submit(
function(e) {
e.preventDefault();
var isbn = $('#ISBN').val();
var isbn_without_hyphens = isbn.replace(/-/g, "");
var googleAPI = "https://www.googleapis.com/books/v1/volumes?q=" + isbn_without_hyphens;
$.getJSON(googleAPI, function(response) {
if (typeof response.items === "undefined") {
alert("No books match that ISBN.")
} else {
$("#title").html(response.items[0].volumeInfo.title);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#publishedDate").html(response.items[0].volumeInfo.publishedDate);
}
});
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<strong>Enter ISBN:</strong> <input type="text" id="ISBN" value="9781407170671">
<input type="submit" id="submit">
</form>
Title: <span id="title"></span>
<br> Author: <span id="author"></span>
<br> Publication date: <span id="publishedDate"></span>

Categories

Resources