Custom Function from .tld File not working - java

I am pulling my hair out trying to get a custom function working in JSP. I have read other questions on the topic, but I have not made those mistakes and am following a JSP book (Head First Servlets & JSP) in creating my tag.
Here's my login.tld file located in /WEB-INF/:
<tlib-version>1.2</tlib-version>
<uri>/WEB-INF/login.tld</uri>
<function>
<name>validate</name>
<function-class>org.patrickslagle.model.LoginManager</function-class>
<function-signature>
boolean validate(String username, String password)
</function-signature>
</function>
The method in LoginManager class:
public static boolean validate(String username, String password) {
System.out.println("Servlet");
DatabaseManager dbm = new DatabaseManager();
boolean valid = false;
ResultSet rs = null;
Statement stmt = null;
dbm.setUrl("jdbc:mysql://localhost:3306/pattycakes");
dbm.connect();
try {
stmt = dbm.getConn().createStatement();
String sql = "SELECT * FROM users WHERE email = '" + username + "' AND password = '" + password + "'";
rs = stmt.executeQuery(sql);
if (rs.next()) {
valid = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbm.disconnect(stmt, dbm.getConn());
}
return valid;
}
}
And the tag in index.jsp:
<%# taglib prefix="lm" uri="/WEB-INF/login.tld"%>
It is called like so:
<c:if test="${ lm.validate(username, password) }">
with these two inputs on the page in a form:
<input type="text" name="username" id="user_login" class="input"
placeholder="Email Address" value="" size="20" />
<input type="password" name="password" id="user_pass" class="input"
placeholder="Password" value="" size="20" />
If I print to the console, I find that anything inside the test isn't printed and the System.out.println in LoginManager is never printed. It simply skips the test.
Having trouble figuring out the problem in debug mode as well. I am assuming that the expression just isn't being evaluated for some reason and is returning nothing.

In your login.tld, instead of using
boolean validate(String username, String password)
try using
boolean validate(java.lang.String username, java.lang.String password)
also, instead of using
<c:if test="${ lm.validate(username, password) }">
try using
<c:if test="${lm:validate(username, password)}">
if you getting data from request, then you might need
<c:if test="${lm:validate(param.username, param.password)}">

Related

How do I take user entered data from HTML forms in a JSP file, and enter it into a mysql database using a java class?

So this is a project for my high school computer science class and my goal right now is to make a registration page, which stores its data inside a mysql server. So far, I've been able to connect to the database from java and also store data into it, but only when its been hardcoded by me.
I've searched the internet for solutions, and so far that has gotten me this code.
This is the main code in the jsp file.
<form action="NewAccount.jsp">
<div class = "inputBox"> <p id = "inputFName">First Name</p> <input type="text" name="FName"/> </div>
<div class = "inputBox"> <p id = "inputLName">Last Name</p> <input type="text" name="LName"/> </div>
<div class = "inputBox"> <p id = "inputEmail">Email</p> <input type="text" name="Email"/> </div>
<div class = "inputBox"> <p id = "inputUser">Username</p> <input type="text" name="User"/> </div>
<div class = "inputBox"> <p id = "inputPass1">Password</p> <input type="password" name="Pass1"/> </div>
<div class = "inputBox"> <p id = "inputPass2">Retype Password</p> <input type="password" name="Pass2"/> </div>
<br/>
<div id="inputButton"> <input type="submit" value="submit" name = "submit"/> </div>
</form>
<%
if (request.getParameter("submit") != null) {
CreateUser c = new CreateUser();
String FName = request.getParameter("FName");
String LName = request.getParameter("LName");
String Email = request.getParameter("Email");
String User = request.getParameter("User");
String Pass = request.getParameter("Pass1");
c.createUser(FName, LName, Email, User, Pass);
}
%>
This is the code in the Java class file.
private static PreparedStatement pst;
public void createUser(String FName, String LName, String Email, String User, String Pass) throws SQLException {
SQLCon.Connect();
pst = SQLCon.getMyConn().prepareStatement("insert into User_Info (FirstName,LastName,Email,Username,Password) values(?,?,?,?,?)");
pst.setString(1, FName);
pst.setString(2, LName);
pst.setString(3, Email);
pst.setString(4, User);
pst.setString(5, Pass);
}
the SQLCon.Connect() method is below.
public static void Connect() throws SQLException {
String url = "jdbc:mysql://localhost:3306/IA Schema";
String user = "root";
String pass = "bruhbruh";
try {
//Connect to database
myConn = DriverManager.getConnection(url, user, pass);
} catch (Exception exc) {
System.out.println("failed");
}
}
My project runs fine, but when I enter stuff data and click enter, the glassfish console thing says this.
Any help on how to successfully enter the data into the database is greatly appreciated, but please keep in mind that this has all been self-taught from the internet (except java) and I may have a stupid mistake somewhere. Thank you.
The whole SQLCon class.
package JavaClasses;
import java.sql.*;
public class SQLCon {
private static Connection myConn;
public static Connection getMyConn() {
return myConn;
}
public static void Connect() throws SQLException {
String url = "jdbc:mysql://localhost:3306/IA Schema";
String user = "root";
String pass = "bruhbruh";
try {
//Connect to database
myConn = DriverManager.getConnection(url, user, pass);
} catch (Exception exc) {
System.out.println("failed");
}
}
}
You have the wrong name for LName in the jsp file.
<div class = "inputBox"> <p id = "inputLName">Last Name</p> <input type="text" name=":Name"/> </div>
LName, not :Name.
also in SQLCon class try the following changes.
public static Connection getMyConn() {
if(myConn!=null){
return myConn;
}else{
SQLCon.Connect();
return myConn;
}
}

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.

Servlet code dispatching to JSP shows error

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.

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

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