I am creating an online bank. On login, it created a session for that user. The user than has options to click on different transaction types.So when the user clicks on open an account button, it will go to openAccount.jsp page. I also have a form with a users first name, last name, and email in the openAccount.jsp. When the user clicks on the open account button and is redirected to the openAccount.jsp, I want the form to be prefilled from the database based. I am not sure how? Here is my code so far:
home-page.jsp
<div class="col-md-4">
<form name = "OpenAccount" action="open-account.jsp" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
open-account.jsp
<!DOCTYPE html>
<html>
<head>
<title>Open Account</title>
</head>
<body>
<h3>Please fill in the details</h3>
<form name="predifinedFields">
First Name: <input type="text" name="firstname" value= <%= request.getAttribute("firstname") %> > <br/><br/>
Last Name: <input type="text" name="lastname" value= <%= request.getAttribute("lastname") %>> <br/><br/>
Email: <input type="text" name="email" value= <%= request.getAttribute("email") %>> <br/><br/>
</form>
<form name="openAccount" action="OpenAccount" method="POST">
Select the type of account:
<select name="accounttype">
<option>Checking</option>
<option>Saving</option>
</select> <br/><br/>
Initial Deposit: $<input type="text" name="deposit"> <br/><br/>
Please check the box if everything above is complete:
Agree <input type="radio" name="agree" value="Agree">
Disagree <input type="radio" name="agree" value="Disagree">
<br/><br/>
<input type="submit" value="submit" name="Submit">
</form>
</body>
</html>
OpenAccount.java
public class OpenAccount extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = "";
HttpSession session = request.getSession(false);
if(session != null)
{
username = (String) session.getAttribute("username");
Users users = new Users();
users = DBConnection.getUsers(username);
request.setAttribute("firstname", users.getFirstName());
request.setAttribute("lastname", users.getLastName());
request.setAttribute("email", users.getEmail());
//request.setAttribute("username", users.getUsername());
}
// String firstName = (String) request.getParameter("firstname");
// String lastname = (String) request.getParameter("lastname");
String email = (String) request.getParameter("email");
String accountType = (String) request.getParameter("accounttype");
String accept = (String) request.getParameter("agree");
String deposit = (String) request.getParameter("deposit");
if(accept.equals("Agree"))
{
if(accountType.equals("Checking"))
{
DBConnection.newCheckingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
else if(accountType.equals("Saving"))
{
DBConnection.newSavingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
}
else
{
System.out.println("Please modify the changes");
RequestDispatcher dispatcher = request.getRequestDispatcher("open-account.jsp");
dispatcher.forward(request, response);
}
}
}
Database.java
public static Users getUsers(String username)
{
Users user = new Users();
try
{
DBConnection.connectToDB();
String query = "SELECT * FROM userlogin where username=?";
stmt = DBConnection.conn.prepareStatement(query);
stmt.setString(1,username);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
}
catch(Exception e)
{
System.out.println(e);
}
return user;
}
In your case (basic servlet), you should follow this logic :
->browser
->servlet which loads and prepares required data from database into request attributes as you have done and finally forwards to open-account.jsp
->open-account.jsp use request attributes to render dynamically fields with your data retrieved from your database.
For other use cases, try to keep this simple logic :
->browser
->servlet processing ....
->jsp rendering ....
Your form in home-page.jsp should post to the servlet (controller) :
<div class="col-md-4">
<form name = "OpenAccount" action="/OpenAccount" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
You should rename OpenAccount to OpenAccountServlet (keeping conventions is better) and configure correctly the servlet of OpenAccountServlet in your web.xml (or with annotations).
If you use web.xml file for the servlet configuration, the url posted in the previous jsp (action="/OpenAccount") should match with the value in <url-pattern>/OpenAccount</url-pattern>
The forward should do like that :
getServletContext().getRequestDispatcher("yourRequiredPath/open-account.jsp ").forward(request, response);
Related
I am writing a simple training application using spring hibernate where I save user data in parts, the user enters data during registration and in my account, I have a problem, I don’t know how to transfer data from the first form to the second on another jsp page, to transfer to another controller and save to database as data of one person
registration.jsp
<spring:form name="myForm" action="save-user" method="post"
modelAttribute="user" onsubmit="return validateForm()">
<spring:hidden path="id" />
<div class="center">
емайл: <br>
<spring:input path="userEmail" />
<br> <br>
</div>
<div class="center">
логин: <br>
<spring:input path="userLogin" />
<br> <br>
</div>
<div class="center">
пароль: <br>
<spring:input path="password" />
<br> <br>
</div>
<div class="center">
<input type="submit" value="зарегистрироваться">
</div>
</spring:form>
<form action="registration" method="post"></form>
RegistrationController{
#RequestMapping(value = "/save-user", method = RequestMethod.POST)
public ModelAndView saveUser(UserBean user) {
userService.saveUser(user);
Integer id = user.getId();
String email = user.getUserEmail();
String login = user.getUserLogin();
String password = user.getPassword();
Map<String, String> result = new HashMap<String, String>();
result.put("email", email);
result.put("id", String.valueOf(id));
result.put("login", login);
result.put("password", password);
return new ModelAndView("privateroom", result);
}
}
privateroom.jsp
<spring:form name="myForm_1" action="save-user-two" method="post"
modelAttribute="user" onsubmit="return validateForm()">
<spring:hidden path="${id}" />
<div class="center">
имя: <br>
<spring:input path="userName" />
<br> <br>
</div>
<div class="center">
фамилия: <br>
<spring:input path="userSurname" />
<br> <br>
</div>
<div class="center">
дата рождения: <br>
<spring:input path="userDateOfBirth" />
<br> <br>
</div>
<spring:hidden path="${email}"/>
<spring:hidden path="${login}"/>
<spring:hidden path="${password}"/>
<div class="center">
<input type="submit" value="дополнить данные">
</div>
</spring:form>
PrivateRoomController{
#RequestMapping(value = "/save-user-two", method = RequestMethod.POST)
public ModelAndView saveUser(UserBean user) {
userService.saveUser(user);
return new ModelAndView("privateroom");
}
}
In this case you can store the user information in Session every time the information submitted from the client (browser) to controller.
Note: I recommend not to send back the information to client browser to be stored in hidden fields, especially should not send back the password to client browser. You can send the remaining (email, id, login) if you really need to show them on the next page.
RegistrationController {
#RequestMapping(value = "/save-user", method = RequestMethod.POST)
public ModelAndView saveUser(UserBean user, HttpSession session) {
// Store user object in the user's session
session.setAttribute("user", user);
// Return back some information for showing purpose only
Map<String, String> result = new HashMap<String, String>();
result.put("email", user.getEmail());
result.put("id", String.valueOf(user.getId()));
result.put("login", user.getLogin());
return new ModelAndView("privateroom", result);
}
}
During the last submit, you can retrieve back the user information from Session and save it using userService.saveUser.
PrivateRoomController {
#RequestMapping(value = "/save-user-two", method = RequestMethod.POST)
public ModelAndView saveUser(UserBean user, HttpSession session) {
// Retrieve user object in the user's session
UserBean userFromSession = session.getAttribute("user");
// Update some additional values
userFromSession.setUserName(user.getUserName());
userFromSession.setUserSurename(user.getUserSurename());
userFromSession.setUserDateOfBirth(user.getUserDateOfBirth());
// Save to database at once
userService.saveUser(userFromSession);
return new ModelAndView("privateroom");
}
}
I am using net beans IDE to crate my Login form and the servlet. i used BCrypt hashing method to secure the password when it's storing in the database and it was successful. but when I going to login it always says "Invalid Credentials"
how can i solve this
here is my CompanyLoging.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body style="background-color: #666666;">
<%
Cookie[] cookies=request.getCookies();
String email = "", password = "",rememberVal="";
if (cookies != null) {
for (Cookie cookie : cookies) {
if(cookie.getName().equals("cookuser")) {
email = cookie.getValue();
}
if(cookie.getName().equals("cookpass")){
password = cookie.getValue();
}
if(cookie.getName().equals("cookrem")){
rememberVal = cookie.getValue();
}
}
}
%>
<div class="limiter">
<div class="container-login100">
<div class="wrap-login100">
<form class="login100-form validate-form" action="CompanyLogin" method="post">
<span class="login100-form-title p-b-43">
Login to continue
</span>
<div class="wrap-input100 validate-input" data-validate = "Valid email is required: ex#abc.xyz">
<input class="input100" type="text" name="email" >
<span class="focus-input100"></span>
<span class="label-input100">Email</span>
</div>
<div class="wrap-input100 validate-input" data-validate="Password is required">
<input class="input100" type="password" name="pass" autocomplete="off">
<span class="focus-input100"></span>
<span class="label-input100">Password</span>
</div>
<div class="flex-sb-m w-full p-t-3 p-b-32">
<div class="contact100-form-checkbox">
<label>Remember me?</label>
<input type="checkbox" name="remember_me" value="1" <%="1".equals(rememberVal.trim()) %>>
</div>
<div>
<a href="#" class="txt1">
Forgot Password?
</a>
</div>
</div>
<div class="container-login100-form-btn">
<button class="login100-form-btn">
Login
</button>
</div>
<div class="text-center p-t-46 p-b-20">
<span class="login100-form-btn2">
or sign up
</span>
</div>
</form>
<div class="login100-more" style="background-image: url('resources/Company/CompanyLogin/images/bg-01.jpg');">
</div>
</div>
</div>
</div>
</body>
</html>
here is my CompanyLog.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("pass");
String hashPass = BCrypt.hashpw(password, BCrypt.gensalt(12));
try
{
connection = Connector.ConnectDb();
PreparedStatement pst = connection.prepareStatement("SELECT * FROM Company WHERE Email= '"+email+"' AND Password='"+hashPass+"'");
ResultSet rs = pst.executeQuery();
if (rs.next())
{
if(request.getParameter("remember_me") != null)
{
String remember = request.getParameter("remember_me");
Cookie cemail = new Cookie("cookuser", email.trim());
Cookie cPassword = new Cookie("cookpass", password.trim());
Cookie cRemember = new Cookie("cookrem", remember.trim());
cemail.setMaxAge(60 * 60 * 24 * 15);//15 days
cPassword.setMaxAge(60 * 60 * 24 * 15);
cRemember.setMaxAge(60 * 60 * 24 * 15);
response.addCookie(cemail);
response.addCookie(cPassword);
response.addCookie(cRemember);
}
HttpSession httpSession = request.getSession();
httpSession.setAttribute("sessuser", email.trim());
RequestDispatcher requestDispatcher = request.getRequestDispatcher("CompanyDashboard.jsp");
requestDispatcher.forward(request, response);
}
else
{
PrintWriter out=response.getWriter();
out.println("<script type=\"text/javascript\">");
out.println("alert('Invalid Credentials');");
out.println("location='CompanyLogin.jsp';");
out.println("</script>");
}
}
catch (IOException | SQLException | ServletException e)
{
PrintWriter out=response.getWriter();
out.println("Error : " + e);
}
}
this is the way my database looks like
You don't have posted the registration-part of your application, but I suspect the issue is caused by the following line in your login-part:
String hashPass = BCrypt.hashpw(password, BCrypt.gensalt(12));
which creates the password-hash for a new salt. Of course, that doesn't match the password-hash created in your registration-part (and stored in the Password-field of your DB) since the salts differ even if the passwords match. Thus, instead of creating a new salt you have to use the salt already stored in your DB:
String hashPass = BCrypt.hashpw(password, storedSalt);
In principle, the salt can be reconstructed from the stored BCrypt-hash (if you are interested in this, the format of the BCrypt-hash is in detail explained at How can bcrypt have built-in salts? and here).
However, there is an easier way (which is also the intended way): You can use the BCrypt#checkpw-method:
boolean isAuthenticated = BCrypt.checkpw(candidatePassword, passwordHash);
Here, candidatePassword is the password to check. passwordHash is the BCrypt-hash (stored in the Password-field of your DB). If the passwords match the method returns true.
If you use this approach you have to adapt your database-access accordingly, e.g. something like (not yet tested!):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("pass");
try {
connection = Connector.ConnectDb();
PreparedStatement pst = connection.prepareStatement("SELECT * FROM Company WHERE Email= '"+email+"'");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
if (BCrypt.checkpw(password, rs.getString("Password"))) {
...
I have the following code which validates a Sign up form. I have two methods which validate if "Password" and "Confirm password" are the same and sends an error message if not and also checkEmail() which checks the DB if the email already exists. When I don't include the checkEmail() method the other one works fine (even the error message). But when I include the checkEmail() it gives an error message of NullPointerException. I believe it has to do with the incorporation of the checkEmail() method in my code but I am not sure where to put it. I would be grateful if anyone could help me.
//SERVLET doPost METHOD
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession s = request.getSession();
UserInfo ud = new UserInfo();
ud.createTable();
UserBean u = new UserBean();
ServletContext ctx = s.getServletContext();
u.setEmail(request.getParameter("email"));
u.setName(request.getParameter("name"));
u.setLname(request.getParameter("sname"));
u.setPassword(request.getParameter("password"));
s.setAttribute("User", u);
String e = u.getEmail();
String p1 = u.getPassword();
String p2 = request.getParameter("password2");
if(User.confirmPassword(p1, p2) && !User.checkEmail(e)) {
//Save data to DB
u = (User)s.getAttribute("User");
s.invalidate();
ud.insert(u);
forwardTo(ctx, request, response, "/Somepage.jsp");
} else {
if(User.checkEmail(e)) {
request.setAttribute("name",request.getParameter("name"));
request.setAttribute("sname",request.getParameter("sname"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("password"));
request.setAttribute("pass2", request.getParameter("password2"));
request.setAttribute("errorMessage", "Email already exists!");
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
if(!User.confirmPassword(p1, p2)) {
request.setAttribute("name",request.getParameter("name"));
request.setAttribute("sname",request.getParameter("sname"));
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("password"));
request.setAttribute("pass2", request.getParameter("password2"));
request.setAttribute("errorMessage", "Passwords do not match!");
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
}
}
//SIGN UP FORM
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User Registration</title>
</head>
<body>
<form action = "UserServ" method ="POST">
<h5 >Enter the details below to Sign Up</h5><br>
Name: <input type="text" name="name" required placeholder="Firstname" value="${name}"><br>
Surname: <input type="text" name="sname" required placeholder="Surname" value="${sname}"><br>
Email: <input type="text" value="${email}" name="email" placeholder="Email"><br>
Password:
<input type="password" value="${pass}" name="password" placeholder="Password" required><br>
Confirm password:
<input type="password" name="password2" value="${pass2}" placeholder="Confirm password" required><br>
<div style="color: #FF0000;">${errorMessage}</div><br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
</body>
</html>
//METHODS
public static boolean confirmPassword(String p1, String p2){
boolean status = false;
if(p1.equals(p2)) {
status =true;
}
return status;
}
public static boolean checkEmail(String email) {
boolean check = false;
PreparedStatement pst = null;
ResultSet rs = null;
try(Connection conn= ConnectionConfiguration.getConnection()){
pst = conn.prepareStatement("SELECT * FROM users WHERE email=?;");
pst.setString(1, email);
check = rs.next();
} catch (SQLException e) {
e.printStackTrace();
}
return check;
}
}
The ResultSet is never calculated as the prepared statement is never executed. This results in the NPE while executing rs.next().
Add sth like this after setting the email:
rs = preparedStatement.executeQuery();
This will execute the prepared statement with the given parameters and return the ResultSet you're looking for.
BTW:
Please consider using rs.isBeforeFirst() instead of rs.next() for checking if there is any result. In your case it will work, because you're not reading any row, but if, you'll need to reset the cursor as rs.next() moves the cursor to the next row if present.
i created a user management (Create, Read, Update, Delete) with Java and sql.
Here is my dao:
private static final String UPDATE = "UPDATE user set login_user=?, pwd_user=?, id_role=? where id_user=? ";
#Override
public void update_user(User user) throws DAOException {
Connection connexion = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connexion = (Connection) dao_factory.getConnection();
preparedStatement = connexion.prepareStatement(UPDATE);
preparedStatement.setString(1, user.getLogin());
preparedStatement.setString(2, user.getPwd());
preparedStatement.setInt(3, user.getRole());
preparedStatement.setLong(4, user.getId_user());
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new DAOException(e);
}
}
My jsp for update user:
<%
if(action.equalsIgnoreCase("edit")){
%>
<form method="get" action="client">
<div class="form-group">
<input type="text" class="form-control" id="login" name="login" placeholder="login">
Update
</div>
</form>
<% } %>
And my servlet:
String action = request.getParameter("action");
if (request.getParameter("action") != null && action.equalsIgnoreCase("view")) {
request.setAttribute("client", user_dao.find_all());
}
if (action.equalsIgnoreCase("delete")) {
int id = Integer.parseInt(request.getParameter("id"));
user_dao.delete_user(id);
request.setAttribute("client", user_dao.find_all());
}
if (action.equalsIgnoreCase("edit")) {
int id = Integer.parseInt(request.getParameter("id"));
User user = user_dao.getById(id);
session.setAttribute("user_edit", user);
}
if (action.equalsIgnoreCase("update")) {
Long id = Long.parseLong(request.getParameter("id"));
String login = request.getParameter("login");
User user = new User();
user.setLogin("test_login");
user.setPwd("test_pwd");
user.setRole(1);
user.setId_user(id);
user_dao.update_user(user);
}
else {
request.setAttribute("client", user_dao.find_all());
}
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
My first problem is, when i click in the button "update", it work. But if i press enter, i have a null pointer exception
Second problem is, If I want to recover login user with String login = request.getParameter("login");and user.setLogin(login); the login value is null in db.
Thanks a lot
EDIT:
here is stack trace:
Avertissement: StandardWrapperValve[client]: Servlet.service() for servlet `client threw exception`
java.lang.NullPointerException
at egame.servlets.admin.client.processRequest(client.java:53)
at egame.servlets.admin.client.doGet(client.java:94)
line 53 : if (action.equalsIgnoreCase("delete")).
line 94 is empty
ResultSet resultSet = null;
It is still null after update user is called.
In any case you are trying to access
the servlet will always call request.setAttribute("client", user_dao.find_all());
Use else if unless you want it to happen only on nonupdate cases.
Your HTML/JSP is wrong. You create a HTML-form but what you say is a "button" is actually just an independent link. This is the reason of both issues you mention:
When you click the link form is not submitted
When you press enter, the form is submitted but without data you put in URL
You need to change it to something like
<%
if(action.equalsIgnoreCase("edit")){
%>
<form method="post" action="client">
<div class="form-group">
<input type="text" class="form-control" id="login" name="login" placeholder="login">
<input type="hidden" id="action" value="update" >
<input type="hidden" id="id" value="${ user_edit.id_user }" >
<button type="submit" class="btn btn-primary">Update</a>
</div>
</form>
<% } %>
Side node: NEVER use HTTP GET to submit any changes to the server. If you change data on the server, it should be POST (or DELETE, or PUT but not GET).
I'm working with multiple files and servlets and I pass a variable as a flag in the following way :
managerPage.jsp :
<fieldset>
<legend>To open a new account</legend>
<form action="employeeTransaction1">
<input type="hidden" name="hdField" value="managerFlagOn" />
<input type="submit" value="Press here to continue" />
</form>
</fieldset>
Now I go to employeeTransaction1 servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
synchronized(session)
{
String hiddenValue = request.getParameter("hdField");
// then the redirection was made from a Manager's page
if (hiddenValue.equals("managerFlagOn") == true)
{
session.setAttribute("managerQuery1", hiddenValue);
}
// forwards to the page employeeOpenNewAccount.jsp
request.getRequestDispatcher("/WEB-INF/results/employeeOpenNewAccount.jsp").forward(request, response);
}
}
Here I grab the hidden value and place it under the name managerQuery1 .
Then I'm being forwarded to employeeOpenNewAccount.jsp:
employeeOpenNewAccount.jsp:
<!-- EMPLOYEE OP 1 - open a new account -->
<!DOCTYPE html>
<html>
<head><title>Employee's transaction page - open a new account</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Employee's transaction page!</h1>
<h1>
Open a new Bank account
</h1>
<!-- from here redirecting to the servelet that's called "employeeOperation1" -->
<fieldset>
<legend>Please fill the followings</legend>
<form action="employeeOperation1">
First-name : <input type="text" name="firstName"><br>
Last-name : <input type="text" name="lastName"><br>
Address : <input type="text" name="address"><br>
ID-number : <input type="text" name="idNumber"><br>
User-name : <input type="text" name="userName"><br>
Password : <input type="text" name="password"><br>
<input type="submit" value="Register">
</form>
</fieldset>
</body></html>
And now I go to employeeOperation1 servlet :
employeeOperation1:
#WebServlet("/employeeOperation1")
public class EmployeeServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
HttpSession session = request.getSession();
synchronized(session)
{
String manager = request.getParameter("managerQuery1"); // the value is null
...
...
}
}
And now the value of manager after grabbing managerQuery1 is null .
Why is it null ? I thought that session-variables are supposed to stay until the end of the program .
Thanks
You set the managerQuery1 in a session attribute, and try to fetch it from a request parameter.
fetch it from the session, and you're done.
String manager = session.getAttribute("managerQuery1");
String manager = session.getAttribute("managerQuery1");
I think you need to cast into String
String manager =(String) session.getAttribute("managerQuery1");
You can follow to get more idea.
javax.servlet.http.HttpSession session = request.getSession();
Once you have done that, you can set a session object like this:
session.setAttribute("name","value");
To retrieve the value, do this:
String foo = (String) session.getAttribute("name");