2

I'm currently doing a project on java eclipse IDE. I have a servlet shown below with the functionality of password change. As you can see, there are various errors I have programmed it to return based on user input, e.g. "Passwords do not match". But, this is always printed at the top of the screen. Is there any way I can output these errors as an actual formatted error? Maybe in the form of a popup box or at least position it in a proper place?

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class NewPassword extends HttpServlet { 
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();

                String oldpassword = request.getParameter("oldpassword"); 
                String newpassword = request.getParameter("newpassword"); 
                String confirmpassword = request.getParameter("confirmpassword"); 

                int newpass = newpassword.length(); 

                HttpSession session = request.getSession(false);
                String employeeid = ""; 

                if(session != null) { 
                    employeeid = (String)session.getAttribute("employeeid"); 
                }

                boolean st = false; 
                try { 
                    Class.forName("com.mysql.jdbc.Driver").newInstance(); 
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", ""); 
                    PreparedStatement ps = con.prepareStatement("SELECT pwd FROM payroll_system.employee_login WHERE employeeID = ?");
                    ps.setString(1, employeeid);
                    ResultSet rs = ps.executeQuery(); 
                    st = rs.next(); 
                    String currentpassword = rs.getString("pwd"); 
                    if(st) { 

                        if((currentpassword.equals(oldpassword)) && newpassword.equals(confirmpassword) && newpass >= 8) { 
                            PreparedStatement pd = con.prepareStatement("UPDATE payroll_system.employee_login SET pwd = ? where employeeID = ?" ); 
                            pd.setString(1, newpassword);
                            pd.setString(2, employeeid);
                            int updated = pd.executeUpdate(); 
                            if(updated > 0){
                                out.println("Password Successfully Updated");
                                RequestDispatcher rd = request.getRequestDispatcher("changePassAdmin.html");
                                rd.include(request, response);
                            }
                        }

                        else if(oldpassword.equals("") || newpassword.equals("")  || confirmpassword.equals("") ) { 
                            out.println("Fields cannot be left blank.");
                            RequestDispatcher rd = request.getRequestDispatcher("changePassAdmin.html");
                            rd.include(request, response);
                        }
                        else if(!currentpassword.equals(oldpassword) && !newpassword.equals(confirmpassword)) { 
                            out.println("Old password is incorrect and passwords do not match, please try again.");
                            RequestDispatcher rd = request.getRequestDispatcher("changePassAdmin.html"); 
                            rd.include(request, response); 
                        }
                        else if(!currentpassword.equals(oldpassword)) { 
                            out.println("Old password entered incorrectly, please try again.");
                            RequestDispatcher rd = request.getRequestDispatcher("changePassAdmin.html");
                            rd.include(request, response);
                        }
                        else if(!newpassword.equals(confirmpassword)) { 
                            out.println("Passwords do not match, please try again.");
                            RequestDispatcher rd = request.getRequestDispatcher("changePassAdmin.html");
                            rd.include(request, response);
                        }
                        else if(newpass < 8 ) {
                            out.println("New Password must be atleast 8 characters in length.");
                            RequestDispatcher rd = request.getRequestDispatcher("changePassAdmin.html");
                            rd.include(request, response);
                        }



                    }
                }catch(Exception e)
                 {
                     e.printStackTrace();
                 }
               out.close();
       }
   }
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Programmer
  • 1,266
  • 5
  • 23
  • 44
  • 1
    is this a webapplication? – Stultuske Jan 22 '16 at 09:34
  • @Stultuske Hi! Yes it is a web application. – Programmer Jan 22 '16 at 09:37
  • Are you storing your passwords as clear text? – Tobb Jan 22 '16 at 09:38
  • @Tobb I have a html file with form action = *this servlet*. Within this html, the variables existing password, new password, confirm password as set to input type = password. However, if you are referring to database storage then probably yes, this is just a high school project and I'm not sure about too much technicality in password storage. – Programmer Jan 22 '16 at 09:41
  • @javaprogrammer so use css. – Stultuske Jan 22 '16 at 09:42
  • @javaprogrammer OK for school projects, just remember to never do something like this in a system that is going to be used for anything :) – Tobb Jan 22 '16 at 09:45
  • @Tobb Alright Tobb, I'll keep that in mind if I get a career in IT/Comp Science. Thanks! But is there a way I can print these errors in an appropriate position or atleast as a popup box? :/ – Programmer Jan 22 '16 at 09:47
  • You could add the error message as a payload in your response, and then retrieve it with the callback in your html/javascript.. Others have answered.. – Tobb Jan 22 '16 at 09:49
  • Generally the server passes the data and the *client* deals with making it look pretty. If you return the information that password change didn't work, the client can do what it wants with that information, including not showing any error at all. Usually when a request fails, you'd add a response.setStatus(HttpServletResponse.SC_BAD_REQUEST) to indicate that the input was invalid. – Neil Jan 22 '16 at 09:52
  • @Neil How would this be implemented in the servlet? – Programmer Jan 22 '16 at 09:54
  • @javaprogrammer You just add that line when you know something has gone wrong in your servlet, in this case you'd add that line in every if condition in your code indicating that the input is not correct. You could add another status in your catch, but the proper status for that is HttpServletResponse.SC_INTERNAL_SERVER_ERROR. – Neil Jan 22 '16 at 09:59
  • @Neil Ok, I did that. What exactly does that do? It doesn't output anything now. I replaced my out.println statements with that line response.setStatus(HttpServletResponse.SC_BAD_REQUEST) – Programmer Jan 22 '16 at 10:04
  • @javaprogrammer An http response put very simply is a standard number code indicating status and its content. The setStatus sets the number code and the out.println was writing the content. If you set the status and don't output the content, then your http response won't have the error text, just the code. That's fine so long as the client side checks for it, though in order for it to work with existing code, you should have both lines. Don't just set the status. Are you using ajax? – Neil Jan 22 '16 at 10:13
  • @Neil Not using Ajax. And I don't really think it's very user friendly to send a server error to the user just because their new password isn't 8 characters long or something. – Programmer Jan 22 '16 at 10:14
  • @Neil I think I will try with dialogbox (JOptionPane) – Programmer Jan 22 '16 at 10:16
  • @javaprogrammer A server request without ajax means you navigate to a new page, and the page contents are precisely what the server writes. You write just the message and so the browser shows you only that. You should probably write an entire error page that can show the error in a nice dialog, *or* you could use ajax and handle server requests on the same page. Suffice to say, web applications are complicated. ;) – Neil Jan 22 '16 at 10:17
  • Please add your html code also. – Ketan G Jan 22 '16 at 12:44

3 Answers3

1

You can use ajax and js to deal with the error.Use ajax to communicate with the server and when get the error,use js function to show a dialog.This is just a solution.You can try this.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
hongbochen
  • 123
  • 6
  • Is there no way to do it in java? If possible I can even use out.println(html code). I can do html in java servlet. – Programmer Jan 22 '16 at 09:38
  • @javaprogrammer who has to see the error? the user right? where is the user using a webapp? in the client side... so... you can send a request to java to get the error text, but you have to show it via javascript or jquery in the client (view) side. – Jordi Castilla Jan 22 '16 at 09:42
  • @javaprogrammer you should not do html code in java. use jsp or jsf instead. – Stultuske Jan 22 '16 at 09:43
  • @Stultuske But still, if there is a way, can you share it please? :) – Programmer Jan 22 '16 at 09:46
  • @javaprogrammer you are looking for a 'good way to put your shoes on backwards'. No matter how good it is (I assume you'll be able to write your css just the way you write your html), it's never a good way. In the end, your feet 'll still hurt like hell, because you decided to put your shoes on the wrong way. – Stultuske Jan 22 '16 at 09:48
1

You can use spring-form tags with bean validation.

For instance, in jsp you can show error for specific field:

<form:form method="post" action="/change-password" modelAttribute="passwordChangeForm">
       <form:label path="password">New password</form:label>
       <form:input path="password"/>
       <form:errors path="password"/>
</form:form>
Mufanu
  • 534
  • 7
  • 18
0

You can use a logging framework like log4j. For example, in Log4j, there are logger, appenders and layout. With the help of a layout, you can design the format of your own error messages.

A short introduction to Log4j

Bernhard Colby
  • 311
  • 5
  • 17