Servlet code dispatching to JSP shows error - java

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.

Related

JDBC insert query does not update mysql database

The following code does not insert a row into the corresponding table.
I have already tested the db connection and ran the query in the database, both of which have passed however when I add inputs via a .jsp form the values are still not inserting.
public class UserDao {
public String registerUser(User user){
String username = user.getUsername();
String email = user.getEmail();
String password = user.getPassword();
Connection con;
con = DBConnection.createConnection();
PreparedStatement preparedStatement;
try{
con.setAutoCommit(false);
String query = ("INSERT INTO user (username, email, password, user_id) VALUES(?, ?, ?, ?)");
preparedStatement = con.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, email);
preparedStatement.setString(3, password);
preparedStatement.setString(4,null);
int i = preparedStatement.executeUpdate();
con.commit();
preparedStatement.close();
con.close();
if(i !=0 ){
return "SUCCESS";
}
}catch(SQLException e){
throw new RuntimeException(e);
}
return "Something is wrong!";
}
}
For reference here is what my servlet class and .jsp file looks also like:
public class UserRegistrationServlet extends HttpServlet {
public UserRegistrationServlet(){}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("username");
String email = request.getParameter("email");
String password = request.getParameter("password");
User user = new User();
user.setUsername(userName);
user.setEmail(email);
user.setPassword(password);
UserDao userDao = new UserDao();
String userRegistered = userDao.registerUser(user);
if(userRegistered.equals("SUCCESS")){
request.getRequestDispatcher("test.jsp").forward(request, response);
}else{
request.setAttribute("error", userRegistered);
request.getRequestDispatcher("/UserRegistration.jsp").forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register</title>
<script>
function validate()
{
var username = document.form.username.value;
var email = document.form.email.value;
var password = document.form.password.value;
var conpassword= document.form.conpassword.value;
if (username==null || username=="")
{
alert("Full Name can't be blank");
return false;
}
else if (email==null || email=="")
{
alert("Email can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (password!=conpassword)
{
alert("Confirm Password should match with the Password");
return false;
}
}
</script>
</head>
<body>
<center><h2>Java Registration application using MVC and MySQL </h2></center>
<form name="form" action="UserRegistrationServlet" method="post" onsubmit="return validate()">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="conpassword" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></input><input
type="reset" value="Reset"></input></td>
</tr>
</table>
</form>
</body>
</html>
Not sure where the error in my code, so any advice will be very helpful. Thanks
Updates:
[![After throwing a runtime exception ][2]][2]
You're setting user_id to null and the database complains that the column must not be null. I assume that you haven't passed null to the statement you tested against the DB directly, so that you were setting an empty string instead (or the table is to set a default or automatically generated value in case it's missing).
If there is a default value or a autogenerated one, you can simply leave away user_id in your insert statement and it should work.

Verify BCrypt Hash password when Login

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"))) {
...

Null pointer exception on click submit

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).

Predefined Form Fields from database

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);

In struts 1.3 how to retrieve data from database and display it using DAO

*M new to struts. I am making simple login page that display username and password by retrieving it from database. I m using DAO.
I have LoginDAO.java, LoginAction.java and Displaydata.jsp pages. *
LoginDAO.java
public boolean login(String user,String pass) throws SQLException
{
Connection con = getConnection();
Statement st;
try {
st = con.createStatement();
st.executeQuery("select * from login where Username='" + user + "' and Password='" + pass + "'");
return true;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return false;
}
LoginAction.java
public class LoginAction extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm rf= (DynaValidatorForm) form;
String username = rf.get("username").toString();
String password = rf.get("password").toString();
HttpSession session=request.getSession();
session.setAttribute("user", username);
Login dao= new Login();
if(dao.login(username,password))
{
System.out.println("GOT");
return mapping.findForward("success");}
else
{System.out.println("NOT");
return mapping.findForward("failure");
}
}
}
and also what do i write in Dislpaydata.jsp to display username and password in it dont want any java code in it.
Thankyou
Right. Some time ago I built an application with Struts 1.x and MySql with login.
LoginAction
public ActionForward login( ... ) throws Exception {
String forward;
final String mail = PropertyUtils.getProperty(form, "mail");
final String password = PropertyUtils.getProperty(form, "password");
if (LoginService.getInstance().validate(mail, password)) {
// Do something e.g. put name of user in session
forward = SUCCESS;
} else {
forward = ERROR;
}
return mapping.findForward(forward);
}
LoginService
public boolean validate(final String mail, final String password)
throws ServiceException {
try {
final boolean valid;
// Validate null and empty
// Validate with DB
final UserDAO dao = new UserDAO();
final User user = dao.findByPk(mail);
if (user == null) {
valid = false;
} else {
if (password.equals(user.getPassword())) {
valid = true;
} else {
valid = false;
}
}
return valid;
} catch (DAOException e) {
throw new ServiceException("Error validating user and password.", e);
}
}
UserDAO
private static final String FIND_BY_PK_SQL
= "SELECT mail, name, password, admin FROM user WHERE mail = ?";
public User findByPk(final String mail) throws DAOException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnection();
ps = conn.prepareStatement(FIND_BY_PK_SQL);
ps.setString(1, mail); // PK, NOT NULL
rs = ps.executeQuery();
if (rs.next()) {
return fill(rs);
}
return null;
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
// Close DB resources
}
}
private User fill(final ResultSet rs) throws SQLException {
final User user = new User();
user.setMail(rs.getString("mail"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("password"));
user.setAdmin(rs.getBoolean("admin"));
return user;
}
In my case I have a table user with mail as a primary key. There are various forms.
More examples:
Building a Login Application
Struts Login Application Using Action Form Tutorial | DZone
Creating a Email Login Web Application with Struts
e.g. For show the name of variable user in session scope from the database:
LoginAction
if (LoginService.getInstance().validate(mail, password)) {
final HttpSession session = request.getSession();
final User user = UserService.getInstance().getUser(mail);
session.setAttribute("user", user);
forward = SUCCESS;
}
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
Welcome,
<bean:write scope="session" name="user" property="name" filter="false" />
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript"
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
</head>
<body bgcolor="#2EFEF7">
<form action="action" method="post" id="formDemo" name="MyForm">
<div id="header">
<h2 style="color: red;">Training</h2>
</div>
<hr>
<h3>Login</h3>
<div id="center" style="padding-top: 50px; padding-bottom: 220px;">
<table align="center">
<tr>
<th colspan="2"><h1 style="color: BLUE;">LOGIN</h1></th>
</tr>
<tr>
<th colspan="2"><h5 id="error" style="color: red;"></h5></th>
</tr>
<tr>
<td>UserID:</td>
<td><input type="text" size="40" name="UserId" maxlength="8"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" size="40" name="Password" maxlength="8"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Login"> <input type="button" id="reset"
value="Clear"></td>
</tr>
</table>
</div>
<hr>
<div id="footer">
<label>Copy right# 2000-2008 FUJINET, All Rights Reserved.</label>
</div>
</form>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate() {
if (document.MyForm.UserId.value === ""
|| document.MyForm.UserId.value === null) {
document.getElementById("error").innerHTML = "Please insert userId";
return false;
}
if (document.MyForm.Password.value === ""
|| document.MyForm.Password.value === null) {
document.getElementById("error").innerHTML = "Please insert password";
return false;
}
return (true);
}
$("#reset").click(function(event) {
document.MyForm.UserId.value = "";
document.MyForm.Password.value = "";
document.getElementById("error").innerHTML = "";
});
$("#formDemo").submit(function(event){
return validate();
});
</script>
</body>
</html>

Categories

Resources