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).
Related
I'm trying to DELETE some data from SQL when a button is clicked. However, I keep getting the error java.lang.NumberFormatException: null when the button is clicked. This confusses me because I can display the ID in my jsp.file, so i know the value is selected and displayed.
Here is my jsp file:
if (request.getParameter("delete") != null){
long betID = Long.parseLong(request.getParameter("id"));
System.out.print(betID);
}
<form action="newBet.jsp" method="get">
<fieldset>
<input class="btn btn-default" type="submit" name="w" value="Vundet"/>
<input class="btn btn-default" type="submit" name="L" value="Tabt" />
<input type="submit" name="id" value="<%=bet.getId()%>"/>
</fieldset>
</form>
This successfully shows the value bet.getId() in my jsp file. I will ofc change type to "hidden" when I'm done.
The problem is when I click the button "delete" it does not ready my value.
Here is my Java:
public static void removeBet(long betID) throws SQLException {
Connection connection = null;
try {
DB_Connection connect = new DB_Connection();
connection=connect.get_Connection();
String sql = "DELETE FROM bets WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1, betID);
ps.executeUpdate();
}catch (SQLException e) {
e.printStackTrace();
} finally {
connection.close();
}
The value of my betID is set to long everywhere in my code. I hope some of you might be able to help me. I've checked similar questions, but unfortunatly I've not been able to solve the issues. Thank you.
I add the answer just to put in line all the comments.
Only the value of the submit actually clicked will be passed as request param.
This is why when you click on the name="delete" submit, you see the value on the html page built from jsp but not in the request.
I would even advice you taglib (es. JSTL) insted of writing java code in JSP.
For instance, imagining you have a request or page param named "bet" cotaining the bet bean,
<form action="newBet.jsp" method="get">
<fieldset>
<input class="btn btn-default" type="submit" name="w" value="Vundet"/>
<input class="btn btn-default" type="submit" name="L" value="Tabt" />
<input type="submit" name="id" value="${bet.id}"/>
</fieldset>
</form>
Get a log to JSTL too :
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
https://docs.oracle.com/javaee/5/jstl/1.1/docs/tlddocs/
Regards
I have different fields in database and I need to show all the records in jsp but when I am making ajax request to servlet, it is binding all the results to all fields. I want firstname should be bind with firstname, lastname should be bind with lastname. Currently it is binding with frstname with firstanamelastname.
I've tried all level best to solve my problem but I think, the problem is with ajax request which I am making.
<html>
<head></head>
<body>
<div class="form-row">
<div class="col-md-9">
<div class="form-row pad-left">
<div class="col-md-6 mb-1">
<label for="validationCustomUsername"><b>Birth Name:</b>
<span id='birthName'></span>
</div>
<div class="col-md-6 mb-3">
<label for="validationCustomUsername"><b>Initiated Name:</b>
<span id='initiatedName'></span>
</div>
</div>
<!-- SECOND ROW STARTS HERE -->
<div class="form-row pad-left">
<div class="col-md-6 mb-1">
<label for="validationCustomUsername"><b>Place Of Birth: </b>
<span id='placeOfBirth'></span>
</div>
</div>
<div class="form-row pad-left">
<div class="col-md-6 mb-1">
<label for="validationCustomUsername"><b>Caste:</b>
<span id='caste'></span>
</div>
</body>
</html>
Servlet Code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
int userID = UserDetails.getInstance().getLastRegisteredID();
Connection con = DBConnection.connectDB();
String query = "Select * from PERSONS inner join
PersonsDetails on persons.PersonID=PersonsDetails.PersonId "
+ "where PERSONS.PersonID="+userID;
try {
ResultSet rs = DBConnection.getDBResultSet(con, query);
UserDetails user = new UserDetails();
while(rs.next()) {
String birthName =rs.getString("BirthName");
String initiatedName =rs.getString("InitiatedName");
String placeOfBirth =rs.getString("PlaceOfBirth");
String caste =rs.getString("Caste");
response.getWriter().write(birthName);
response.getWriter().write(initiatedName);
response.getWriter().write(placeOfBirth);
response.getWriter().write(caste);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBConnection.closeDBConnection(con);
}
}
Ajax Call
function userHomeDetails(){
var username = $('#username');
var url = "http://localhost:8080/IskconDevotteeMarriage/page/UserHome"
$(document).ready(function(){
var url=url
$.post("../UserHomeController", function(responseText) {
/*document.getElementById('birthName').innerHTML ="birthName"*/
$('#birthName').html(responseText);
$('#initiatedName').html(responseText);
$('#placeOfBirth').html(responseText);
$('#caste').html(responseText);
alert(responseText);
});
});
}
You can use JSONObject ,firstly add json jar file and then in your servlet class create object of JSONObject like below :
JSONObject ob= new JSONObject();
And then put your parameter like below :
try {
ob.put("birthName",birthName);
ob.put("initiatedName",initiatedName);
ob.put("placeOfBirth",placeOfBirth);
ob.put("caste",caste);
} catch (JSONException e) {
e.printStackTrace();
}
Now ,passed above parameter to your ajax call like below :
response.getWriter().write(obj);
In your ajax call set dataType: "json" and in your function(responseText) you can get this parameter like below :
document.getElementById('birthName').value = responseText.birthName;//setting values to span with id birthName
document.getElementById('initiatedName').value = responseText.initiatedName;
document.getElementById('placeOfBirth').value = responseText.placeOfBirth;
document.getElementById('caste').value = responseText.caste;
Hope this helps !
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 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);
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)}">