I am trying to create a register page for users to register new accounts.
I am using signup.jsp page with the register form
Which is then connected to RegisterServlet.java (gets form parameters and inserts parameters into database after connecting to DBConnection.java)
DBConnection contains the try{} of connecting to the mysql database.
I have tried multiple ways of registering a user, but the users information never inserts into database.
signup.jsp:
<form action="RegisterServlet" method="post" onsubmit="return validate()">
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="First Name" name="fname" class="form-control" />
</div>
<div class="col-lg-6 col-md-6">
<input type="text" placeholder="Last Name" name="lname" class="form-control" />
</div>
</div>
<div>
<input type="text" placeholder="User Name" name="username" class="form-control" />
</div>
<div class="row">
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Password" name="password" class="form-control" id="pass" name="pass" />
</div>
<div class="col-lg-6 col-md-6">
<input type="password" placeholder="Retype Password" name="confirm_password" class="form-control" id="pass2" name="pass2" />
</div>
<div class="col-lg-6 col-md-6">
<%=(request.getAttribute("errMessage") == null) ? ""
: request.getAttribute("errMessage")%>
</div>
</div>
<div class="pull-left"><button type="submit" class="btn btn-primary">Sign Up</button></div>
</form>
RegisterServlet.java:
#WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String username = request.getParameter("username");
String password = request.getParameter("password");
DBConnection db = new DBConnection();
Connection con = db.getCon();
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
System.out.println("data inserted sucessfully");
response.sendRedirect("login.jsp");
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
DBConnection.java
public class DBConnection {
public Connection con;
public Connection getCon(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cultureexchange", "root", "");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
Sql user table:
fname lname username password
varchar varchar varchar varchar
My login.jsp works so the connection to database must work,
appreciate the help in advance.
try Changing these line
Statement stmt = con.createStatement();
stmt.executeUpdate("insert into user (fname, lname, username, password)values('"+fname+"','"+lname+"','"+username+"','"+password+"')");
to
PreparedStatement stmt = con.prepareStatement("insert into user (fname, lname, username, password)values(?,?,?,?)");
ps.setString(1, fname);
ps.setString(2, lname);
ps.setString(3, username);
ps.setString(4, password);
ps.executeUpdate();
And make sure that you have mysql-j-connector in your lib folder under WEB-INF.
Related
I am trying to save data from my registration page to my database but it is not working some how. Does anyone have advise on how I can fix it?
This is my jsp page form.
I am using an embedded derby database.
Any advise would be greatly appreciated.
<form class="form-signin" method="POST" action="newuserservlet">
<input type="text" class="input-block-level" name="firstName" placeholder="First Name">
<input type="text" class="input-block-level" name="lastName" placeholder="Last Name">
<button class="btn btn-large btn-primary" >Sign up</button>
This my servlet:
public class newuserservlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstName");
String lastname = request.getParameter("lastName");
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection dbConnection = null;
String strUrl = "jdbc:derby:billsdb;create=true";
dbConnection = DriverManager.getConnection(strUrl);
PreparedStatement stmt = dbConnection.prepareStatement("insert into USERDATA values(?,?)");
stmt.setString(1, firstname);
stmt.setString(2, lastname);
int i = stmt.executeUpdate();
if (i > 0) {
out.println("You are successfully registered.....");
}
} catch (Exception ey) {
System.out.println(ey);
}
out.close();
}
I am working on a simple home library web application using Java EE, Servlets, JSP, and MySQL. My Create, Read, and Delete are working fine but Update is not working. I am not using any form of design patterns, just servlets and POJO. All examples i try to learn from seem to have used MVC and DAO design patterns. Is there any way to achieve the CRUD application without using MVC and DAO patterns? What is the recommended and best practice for such a simple application?
here is code:
UpdateBook.jsp
<%# page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%# page import ="java.util.ArrayList"%>
<%#page import="book.Book"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk">
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<title>Updated Library Collection</title>
</head>
<body>
<div id="container">
<div id="header"><h1 align="center" style="color:blue">Edit Library Collection</h1></div>
<div id="wrapper">
<div id="content" align="center">
<%
request.setCharacterEncoding("gbk");
String ISBN=request.getParameter("Isbn");
String BookTitle=request.getParameter("Title");
String BookAuthor=request.getParameter("Author");
String Category=request.getParameter("Category");
String Description=request.getParameter("Description");
%>
<table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" >
<tr>
<td width="100%" bgcolor="#EAEAEA" colspan="2">
<form name="bookUpdate" action="/homelibrary/UpdateBookServlet" method="POST">
<p>
<label for="Isbn">ISBN: </label>
<input type="text"readonly name="Isbn" id="Isbn" value=<%=ISBN%> >
<br><br>
<label for="Title">Title: </label>
<input type="text" name="Title" id="Title" value=<%=BookTitle%>>
<br><br>
<label for="Author">Author: </label>
<input type="text" name="Author" id="Author" value=<%=BookAuthor%>>
<br><br>
<label for="Category">Category: </label>
<input type="text" name="Category" id="Category" value=<%=Category%>>
<br><br>
<label for="Description">Description: </label>
<input type="text" name="Description" id="Description" value=<%=Description%>>
<br><br>
<p>
<input type="submit" name="Submit" value="Submit" onclick="goto">
<input type="button" name="Cancel" value="Cancel" onclick="javascript:history.go(-1);">
</p>
</form>
</td>
</tr>
</table>
</div>
</div>
<div id="footer" align="center">
<p>© Home Library</p>
</div>
</body>
</html>
UpdateBookServlet.java
package book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UpdateBookServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String forward="";
String action = request.getParameter("action");
if (action == ("edit")){
String Isbn = request.getParameter("Isbn");
Book book = null;
try {
book = this.getBookByIsbn(Isbn);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("book", book);
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/UpdateBook.jsp");
dispatcher.forward(request,response);
}
//#SuppressWarnings("unused")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Book book = new Book();
response.setContentType("text/html");
request.setCharacterEncoding("gbk");
//Get data from form data
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
//#SuppressWarnings("unused")
//PreparedStatement preStmt = null;
//Connection cn =null;
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/ebookstore";
Connection cn = DriverManager.getConnection(url, "admin", "admin");
PreparedStatement prepStmt= null;
if(ISBN != null)
// create the java MySQL update PreparedStatement
prepStmt = cn.prepareStatement("UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=?");
//String update = "UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=1111";
//prepStmt = cn.prepareStatement(update);
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));
//execute the java preparedStatment
prepStmt.executeUpdate();
cn.close();
prepStmt.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
//forwarding from Servlet to a JSP
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/QueryBook.jsp");
dispatcher.forward(request,response);
}
public Book getBookByIsbn(String isbn) throws ClassNotFoundException {
Book book = new Book();
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/homelib";
Connection cn = DriverManager.getConnection(url, "root", "admin");
PreparedStatement preparedStatement = cn.
prepareStatement("SELECT * FROM book where Isbn=?");
preparedStatement.setString(1, isbn);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
book.setISBN(rs.getString("Isbn"));
book.setTitle(rs.getString("Title"));
book.setAuthor(rs.getString("Author"));
book.setCategory(rs.getString("Category"));
book.setDescription(rs.getString("Description"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return book;
}
}
Button in QueryBook.jsp
<td>Update</td>
This example is for updating a book's information when a user is logged in on the session
Insert this at the top of your JSP to identify the user on the session
if (session!=null && request.getSession().getAttribute("loggedin") != null) {
if (request.getSession().getAttribute("role").equals("Student")) {
response.sendRedirect("index.jsp");
return;
}
} else {
response.sendRedirect("index.jsp");
return;
} %>
<% if (request.getSession().getAttribute("loggedin") == null) {
response.sendRedirect("index.jsp");
return;
}
BookDTO dto = (BookDTO) request.getSession().getAttribute("book");
Then insert this code below in the JSP to post new data to the servlet
<form method="POST" action="EditBookServlet">
<div class="form-submit">
My Information
<div class="submit">
<div class="form-row">
<div class="x">
<label>Name</label>
<input type="text" class="form" value="<%= dto.getName()%>" name="name">
</div>
<div class="x">
<label>Author</label>
<input type="author" class="form" value="<%= dto.getAuthor()%>" name="author">
</div>
<div class="form x">
<button class="btn" type="submit">Save Changes</button>
</div>
</div>
</div>
</form>
In the EditBookServlet, insert this code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
BookDB db = new BookDB();
BookDTO dto = db.getBookByID(((BookDTO)
request.getSession().getAttribute("book")).getId());
dto.setName(request.getParameter("name"));
dto.setAuthor(request.getParameter("author"));
db.updateBook(dto);
request.getSession().setAttribute("book", dto);
In the StudentDB java file insert this to find the book by Id and then to update the book sql file
public BookDTO getBookByID(int id) {
BookDTO obj = null;
String query = "Select * from book where id=?";
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(query);
pst.setInt(1,id);
rs = pst.executeQuery();
if (rs != null) {
if (rs.next()) {
obj = new BookDTO();
obj.setId(rs.getInt(1));
obj.setName(rs.getString(2));
obj.setAuthor(rs.getAuthor(3));
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean updateBook(BookDTO obj) {
int affectedRows = 0;
String query = "update `book` set name=? , author=lower(?) where id=?";
PreparedStatement pst = null;
try {
pst = conn.prepareStatement(query);
pst.setString(1,obj.getName());
pst.setString(2,obj.getAuthor());
pst.setInt(10, obj.getId());
System.out.println(pst);
affectedRows = pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
return affectedRows > 0;
}
You said in your comment:
The update page return with null for all the values.
That is, because you intantiate the Book object In UpdateBookServlet.java
Book book = new Book();
but you set the request parameters into separate string objects:
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
But never use them. Instead you add data from the empty Book object:
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));
I have a login page and when i run it, it must check which radio button is checked and check database for that radio button.
When I run the codes I get this error:
HTTP Status 500 - Request processing failed;
nested exception is java.lang.NullPointerException
and
this is my web page:
<form action="/HelloWorldInWeb/login" method="post">
<div class="col-lg-12" id="div3">
<div class="form-group input-group" id="div4">
<div class="input-group-addon "><span class="glyphicon glyphicon-eye-open "></span></div>
<input type="text" class="form-control" name="username" id="textbox1" placeholder="Enter your username">
</div>
<div class="form-group input-group" id="div5">
<div class="input-group-addon "><span class="glyphicon glyphicon-eye-close "></span></div>
<input type="text" class="form-control" name="password" id="textbox2" placeholder="Enter your Password">
</div>
<div class="form-group" id="div6">
<label><input type="radio" name="sign" name="checkbox" value="adminstrator" id="adminstrator" checked>Adminstrator</label>
<label><input type="radio" name="sign" name="checkbox" value="admin" id="admin">Admin</label>
</div>
<div class="align">
<button type="submit" class="btn btn-danger">Ok</button>
</div>
</div>
</form>
this is my controler servelt:
#SuppressWarnings({ "null", "static-access"})
#RequestMapping(value="/login" , method = RequestMethod.POST)
protected void doPost(HttpServletRequest reque, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username=reque.getParameter("username");
String password=reque.getParameter("password");
String radio=reque.getParameter("checkbox");
if(radio.equals("admin")){
Boolean t = stdDAO.validate(username, password);
if(t){
out.print(username);
out.print(password);
out.print(" username or password succes");
response.sendRedirect("/HelloWorldInWeb/addozvv");
}
else{
out.print(username);
out.print(password);
out.print("Sorry username or password error");
response.sendRedirect("/HelloWorldInWeb/login");
}
out.close();
}else
if(radio.equals("adminstrator")){
Boolean s = stdDAO.validateadm(username, password);
if(s){
out.print(username);
out.print(password);
out.print(" username or password succes");
response.sendRedirect("/HelloWorldInWeb/addozvv");
}
else{
out.print(username);
out.print(password);
out.print("Sorry username or password error");
response.sendRedirect("/HelloWorldInWeb/login");
}
}
}
this is my validates:
public Boolean validate(String username, String password) {
boolean t =false;
try{
Connection con = dataSource.getConnection();
PreparedStatement ps =con.prepareStatement
("select * from admins where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
t = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return t;
}
#Override
public java.lang.Boolean validateadm(String username, String password) {
boolean s =false;
try{
Connection con = dataSource.getConnection();
PreparedStatement ps =con.prepareStatement
("select * from admin where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
s = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return s;
}
radio may be null. Use "admin". equals(radio) and "administrator".equals(radio) in your if statements.
EmployeeController.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Employee employee = new Employee();
employee.setFirstname(request.getParameter("firstName"));
employee.setLastname(request.getParameter("lastName"));
employee.setEmail(request.getParameter("email"));
employee.setStatus(request.getParameter("status"));
String employeeId = request.getParameter("email");
employee.setEmail(employeeId);
dao.addEmployee(employee);
RequestDispatcher view = request.getRequestDispatcher(employee_listing);
request.setAttribute("employees", dao.getAllEmployees());
view.forward(request, response);
}
EmployeeDao.java
HttpServletRequest request;
public void addEmployee(Employee employee) throws ServletException, IOException{
try {
PreparedStatement preparedStatement = conn.prepareStatement("insert into login(firstname, lastname, email, pass, role, status) values (?, ?, ?, ?, 'employee', ?)");
preparedStatement.setString(1, employee.getFirstname());
preparedStatement.setString(2, employee.getLastname());
preparedStatement.setString(3, employee.getEmail());
//preparedStatement.setString(4, employee.getFirstname());
preparedStatement.setInt(4, employee.getFirstname().hashCode());
preparedStatement.setString(5, employee.getStatus());
//preparedStatement.setBoolean(4, employee.getStatus());
int i = preparedStatement.executeUpdate();
if(i > 0){
System.out.println("Employee added successfully.");
HttpSession session = request.getSession();
session.setAttribute("successMessage", "Employee added successfully.");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
//e.printStackTrace();
}
}
addEmployee.jsp
<form class="form-horizontal" method="post" action="EmployeeController" name="frmAddEmployee" id="frmAddEmployee">
<!-- <form class="form-horizontal" method="post" action="adduser.jsp" name="frmAddEmployee" id="frmAddEmployee"> -->
<div class="form-group">
<label for="" class="col-sm-4 control-label">First Name</label>
<div class="col-sm-8">
<input type="text" name="firstName" class="form-control" id="firstName">
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-4 control-label">Last Name</label>
<div class="col-sm-8">
<input type="text" name="lastName" class="form-control" id="lastName" >
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control" id="email" >
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">Employee Status</label>
<div class="col-sm-8">
<label class="switch">
<input type="checkbox" name="status" value="1" checked>
<div class="slider round"></div>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-4"></div>
<div class="col-sm-8">
<input type="submit" name="submit" value="Submit" class="btn btn-primary"> <!-- <button name="cancel" onclick='employee-listing.jsp' class="btn btn-primary" >Cancel</button> -->
</div>
</div>
</form>
So basically when submit the form It redirects to EmployeeController.java file and get all the values in Employee and then redirect to EmployeeDao.java file to addEmployee(employee);
And I will get this in jsp page like ::
session.getAttribute("successMessage");
I tried all this but i didn't get any message form "successMessage" attribute and got only "null" value.
I also tried to response.sendRedirect("employee-success.jsp") but still it didnt redirect to that page.
So can anyone help me to set the value in java code and get that value in jsp page for further use.
change your
public void addEmployee(Employee employee)
to
public void addEmployee(Employee employee, HttpServletRequest request)
pass HttpServletRequest object in EmployeeController.java
dao.addEmployee(employee,request);
Pass the request object from your Controller,
dao.addEmployee(employee);
and access the sessionAttribute directly in your jsp anywhere like,
${successMessage}
OR
you can send the success message back to your Controller from addEmployee method and then set that String message in request attribute like,
String successMessage = dao.addEmployee(employee);
RequestDispatcher view = request.getRequestDispatcher(employee_listing);
request.setAttribute("employees", dao.getAllEmployees());
request.setAttribute("successMessage", successMessage);
In your DAO method,
public String addEmployee(Employee employee) throws ServletException, IOException{
String successMessage = "";
try {
PreparedStatement preparedStatement = conn.prepareStatement("insert into login(firstname, lastname, email, pass, role, status) values (?, ?, ?, ?, 'employee', ?)");
preparedStatement.setString(1, employee.getFirstname());
preparedStatement.setString(2, employee.getLastname());
preparedStatement.setString(3, employee.getEmail());
//preparedStatement.setString(4, employee.getFirstname());
preparedStatement.setInt(4, employee.getFirstname().hashCode());
preparedStatement.setString(5, employee.getStatus());
//preparedStatement.setBoolean(4, employee.getStatus());
int i = preparedStatement.executeUpdate();
if(i > 0){
System.out.println("Employee added successfully.");
HttpSession session = request.getSession();
successMessage = "Employee added successfully.";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
//e.printStackTrace();
successMessage = "Error occured while adding employee."
}
return successMessage;
}
I coded this Java code for my JSP page to update current login details of a user. Code is not showing any errors or exceptions but not updates the MySql database.
Help me to to implement this functionality;
My code:
<%
//variable declaration for encrypt and decrypt
byte [] input ;
byte [] keyBytes = "12345678".getBytes();
byte [] ivBytes ="input123".getBytes();
SecretKeySpec key = new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] cipherText;
int ctLength=0;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
if(request.getParameter("submit")!=null){
String cuser=request.getParameter("currentusername");
String user = request.getParameter("username");
String pwd = request.getParameter("password");
String cpwd = request.getParameter("confirmpassword");
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
input = pwd.getBytes();
key = new SecretKeySpec(keyBytes, "DES");
ivSpec = new IvParameterSpec(ivBytes);
cipher = Cipher.getInstance("DES/CTR/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
cipherText = new byte[cipher.getOutputSize(input.length)];
ctLength+=cipher.update(input, 0, input.length, cipherText, 0);
ctLength+= cipher.doFinal(cipherText, ctLength);
String enpwd = new String(cipherText);
String sql2 = "update webadmin set username=? ,password=? where username='"+cuser+"' ";
if((cuser!=null &&cuser.length()>0)
&& (user!=null &&user.length()>0)
&& (pwd!=null && pwd.length()>0)
&& cpwd!=null && cpwd.length()>0) {
if((pwd.equals(cpwd))){
pst =conn.prepareStatement(sql2);
pst.setString(1, user);
pst.setString(2, enpwd);
pst.executeUpdate();
%>
<script language="JavaScript">
alert("Sucessfully Updated");
</script>
<%
}else{
%>
<script language="JavaScript">
alert("Passwords are not matching try again");
</script>
<%
}
}
}
}
%>
Note: I implement to encrypt the password and store that encrypted password to the database.
HTML form;
<form id="login-form" action="adminpg-mysettings.jsp" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="currentusername" id="currentusername" tabindex="1" class="form-control" placeholder="Current Username" value="" required="">
</div>
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="New Username" value="" required="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="New Password" required="">
</div>
<div class="form-group">
<input type="password" name="confirmpassword" id="password" tabindex="2" class="form-control" placeholder="Confirm New Password" required="">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="submit" id="submit" tabindex="4" class="form-control btn btn-login" value="Save">
</div>
</div>
</div>
</form>
First of, like everyone will tell you, it is a very bad idea to put Java in JSP. The correct way of operating is with a Servlet and requests stored in session. It will prevent malicious sql injections.
Second of, your security constraints should be handled in the web.xml and Servlet, which is best for back-end maintenance. Following good programming practice will prevent you from going crazy over bugging logs.
I can help you implement what you are trying to do with a Servlet, but before I do, I need to know the following:
The obvious: Do you have a Servlet?
Do you use JDBC/JNDI connectivity?
Do you have entity and session classes for user?
Which IDE/framework do you use to develop your app?
What server are you deploying to?
It is the most effective way of accomplishing what you want. Please provide with the answers and I will update my answer with some code :)
public class UpdateController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
request.setAttribute("id", new StudentDAO().getStudent(id));
request.getRequestDispatcher("update.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
Date dob = Date.valueOf(request.getParameter("dob")); // yyyy-mm-dd
String gender = request.getParameter("gender");
Student s = new Student();
s.setId(id);
s.setName(name);
s.setGender(gender);
s.setDob(dob);
StudentDAO db = new StudentDAO();
db.update(s);
response.sendRedirect("list");
request.setAttribute("students", new StudentDAO().getAll());
// request.getRequestDispatcher("list.jsp").forward(request, response);
}
public void update(Student s) {
try {
String sql = "UPDATE [dbo].[Student]\n"
+ " SET [name] = ?\n"
+ " ,[gender] = ?\n"
+ " ,[dob] = ?\n"
+ " WHERE id = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, s.getName());
ps.setString(2, s.getGender());
ps.setDate(3, s.getDob());
ps.setInt(4, s.getId());
ps.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(StudentDAO.class.getName()).log(Level.SEVERE, null, ex);
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Update</title>
<% String id = request.getParameter("id");%>
</head>
<body>
<form action="update" method="post">
<table>
<tr>
<td>ID: <input type="text" name="id"
value="<%=id%>" readonly></td>
</tr>
<tr>
<td>Name: <input type="text" name="name"/></td>
</tr>
<tr>
<td>Gender: <input type="radio" name="gender" value="male"/> Male
<input type="radio" name="gender" value="female"/> Female </td>
</tr>
<tr>
<td>Dob: <input type="date" name="dob" /></td>
</tr>
</table>
<input type="submit" value="Create" />
</form>
</body>