Servlet in Java. How to retrieve attributes? - java

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

Related

update database record through html page using servlets

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.

Java How to dispaly no data found when the user input no reach the condition

If the user key in 4 I wish to pop up a message to inform the user that is no data found for user id "4" in the array list.
But when the user key in 4 there is 3 no data found appear.
User usr1 = new User(1,"Ken", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Mark", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Ong", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
String answer ="";
do{
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter user ID");
int userid = scan.nextInt();
for(User uid: ulist){
if(userid == uid.getUID()){
System.out.println(uid.getUID() +", " + uid.getName() +", " + uid.getAge() +" years old, " + uid.getWeight() +"kg");
}else{
System.out.println("no data found");
}
}
System.out.println("Continue(Y/N)");
answer = scan.next();
}while(answer.equalsIgnoreCase("y"));
current result:
no data found
no data found
no data found
Result that i wish:
no data found
Remove else { System.out.println("no data found"); } from the loop and put it outside. The for loop intent is to find, to lookup the correct user.
Once found you may use it: you have to declare a variable of type User before loop, initialized to null and if it's null after lookup, you have to print the message 'not found'.
You get no data found 3 times because you print it in the cycle: for every user in the list, if his id doesn't match specified id, System.out.println("no data found"); You can avoid this modifying your cycle or writing a method that fidns user by id.
User found;
for (User uid : ulist) {
if (userid == uid.getUID()) {
found = uid;
break; // assuming that ids are unique
}
}
if (found != null) {
System.out.println(found.getUID() +", " + found.getName() +", " + found.getAge() +" years old, " + found.getWeight() +"kg");
} else {
System.out.println("no data found");
}
You have problem in your logic.
in your for loop you should have a break statement, in case there is no data found.
else {
System.out.println("no data found");
break;
}

Pass field/attributes values from java to RTC using JAZZ API's

I am trying to create work item in RTC through java application using the jazz api's.
My connection to the repository is successful. Now i need to set all the required fields through java code in order to save/run the workitem. Really dont know how to set those values in below codes.
String repositoryURI= args[0];
String userId= args[1];
String password= args[2];
String projectAreaName= args[3];
String typeIdentifier= args[4];
String summary= args[5];
String categoryName= args[6];
ITeamRepository teamRepository= TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(null);
IProcessClientService processClient= (IProcessClientService) teamRepository.getClientLibrary(IProcessClientService.class);
IAuditableClient auditableClient= (IAuditableClient) teamRepository.getClientLibrary(IAuditableClient.class);
IWorkItemClient workItemClient= (IWorkItemClient) teamRepository.getClientLibrary(IWorkItemClient.class);
URI uri= URI.create(projectAreaName.replaceAll(" ", "%20"));
IProjectAreaHandle projectArea= (IProjectAreaHandle) processClient.findProcessArea(uri, null, null);
//IProjectAreaHandle projectArea = teamArea.getProjectArea();
if (projectArea == null) {
System.out.println("Project area not found.");
return false;
}
//IWorkItemType workItemType = service.findWorkItemType(projectArea, "defect", monitor);
IWorkItemType workItemType= workItemClient.findWorkItemType((IProjectAreaHandle) projectArea, typeIdentifier, null);
// findWorkItemType(projectArea, typeIdentifier, null);
if (workItemType == null) {
System.out.println("Work item type not found.");
return false;
}
System.out.println("Category not found.: " + categoryName );
List path= Arrays.asList(categoryName.split("/"));
System.out.println("Category not found.: " + path );
ICategoryHandle category= workItemClient.findCategoryByNamePath((IProjectAreaHandle) projectArea, path, null);
//ICategoryHandle category=
if (category == null) {
System.out.println("Category not found.: " + category );
return false;
}
WorkItemInitialization operation= new WorkItemInitialization(summary, category);
IWorkItemHandle handle= operation.run(workItemType, null);
IWorkItem workItem= auditableClient.resolveAuditable(handle, IWorkItem.FULL_PROFILE, null);
System.out.println("Created work item " + workItem.getId() + ".");
teamRepository.logout();
While running the codes i am receiving the below errors. Because of mandatory fields are not assigned. Can any one help me to pass the attribute values (Contact Phone) from java to jazz.
ERROR received:
Severity: ERROR
Summary: Attribute 'Contact Phone #' not set
Description: The 'Contact Phone #' attribute needs to be set (work item <09:13:03>).

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.

Categories

Resources