values are not inserting into database from servlet - java

I am trying to develop a simple registration form , i have designed it in HTML and for business logic i used servlet but the values are not inserting into the database. Below is the html and servlet file.. Advance thanks those who resolve.
Register.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="Patient">
PID:<input type="text" name="pid" /><br/>
Title:<input type="text" name="title" /><br/>
First Name:<input type="text" name="firstname" /><br/>
Last Name:<input type="text" name="lastname" /><br/>
Birthday:<input type="date" name="dob" /><br/>
Address:<input type="text" name="address" /><br/>
E-Mail:<input type="text" name="email" /><br/>
Contact Number:<input type="text" name="contact"/><br/>
Gender:
<input type="radio" name="gender" value="male" checked> Male
<input type="radio" name="gender" value="female"> Female
<input type="radio" name="gender" value="other"> Other<br><br>
Occupation:<input type="text" name="occupation"/><br/>
Age:<input type="text" name="age"/><br/>
<label>Spouse/Parent/Legal Guardian Details</label><br>
Name:<input type="text" name="name"/><br/>
E-Mail:<input type="email" name="email2"/><br/>
Address:<input type="text" name="address2"/><br/>
Contact:<input type="text" name="phone"/><br/>
Relation:<input type="text" name="relation"/><br/>
Occupation:<input type="text" name="occupation2"/><br/>
Age Group:<input type="text" name="agegroup"/><br/>
<input type="submit" value="Register" />
</form>
</body>
</html>
Servlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Patient extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Started");
String pid = request.getParameter("pid");
String title = request.getParameter("title");
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String dob = request.getParameter("dob");
String address = request.getParameter("address");
String email = request.getParameter("email");
String contact = request.getParameter("contact");
String gender = request.getParameter("gender");
String occupation = request.getParameter("occupation");
String age = request.getParameter("age");
String name = request.getParameter("name");
String email2 = request.getParameter("email2");
String address2 = request.getParameter("address2");
String phone = request.getParameter("phone");
String relation = request.getParameter("relation");
String occupation2 = request.getParameter("occupation2");
String agegroup = request.getParameter("agegroup");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/copd","root","root");
PreparedStatement ps=con.prepareStatement("insert into tbl_patient values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, pid);
ps.setString(2, title);
ps.setString(3, firstname);
ps.setString(4, lastname);
ps.setString(5, dob);
ps.setString(6, address);
ps.setString(7, email);
ps.setString(8, contact);
ps.setString(9, gender);
ps.setString(10, occupation);
ps.setString(11, age);
ps.setString(12, name);
ps.setString(13, email2);
ps.setString(14, address2);
ps.setString(15, phone);
ps.setString(16, relation);
ps.setString(17, occupation2);
ps.setString(18, agegroup);
int i=ps.executeUpdate();
if(i>0)
{
out.println("Record has been inserted");
}
else
{
out.println("Failed to insert the data");
}
}
catch(Exception se)
{
se.printStackTrace();
}
finally{}
out.println("ended");
}
}

Given that your servlet is activated ("finally" is printed), I can only see 3 options:
Most importantly: close the connection. That would be important even if you didn't have this missing data problem. By closing, you both 'commit' and prevent a leak. For a quick test it's enough that after "ps.executeUpdate" you'll add "con.close()" (In the longer consider putting it in the 'finally' clause).
A less likely option is that there was an exception but you don't see it, so please check all log files of your container
And also a thousand apologies for this silly suggestion, but could you double-check that you're looking into the correct database/table/etc... at least personally I made such silly mistakes in complex environments ;)

Related

Unable to retrieve the user identity (userName and password)from mysql to login

I am trying to implement this code to process the user login but does not work.
It skips the if statement in the code which means that something is wrong in the user validation or selection. It just goes to the error page after pressing the submit button.
Here is the code I am using below
CustomerController:
HttpSession session = request.getSession();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String firstname = request.getParameter("firstname");
User.getTransaction().begin();
Query query = User.createQuery("select p from Customer where p.userName=:uName");
query.setParameter("uName", userName);
#SuppressWarnings("unchecked")
List<Customer> Result = query.getResultList();
User.close();
if(Result.size()>0)
if(Result.get(0).getPassword().equals(password))
{
Customer pass=Result.get(0);
session.setAttribute("Id", pass.getId());
String message="Welcome " + firstname;
return new ModelAndView("userpage","pass",pass);
}
return new ModelAndView("error","message","Wrong credentials");
}
login jsp file:
<form action="signin" method="post">
<table align="center">
<tr>
<td>
<label>User Name</label>
</td>
<td>
<input type="text" name="UserName" />
</td>
</tr>
<tr>
<td>
<label >Password</label>
</td>
<td>
<input type="text" name="password" />
</td>
</tr>
<tr>
<td></td>
<td>
<button id="login" type="submit" name="login" style="width:100%;border-
radius:10px;text-shadow:2px 2px 3px
rgba(150,150,150,0.75);font-family:time">Login</button>
</td>
</tr>
<tr>
<td>Don't have an account? Sign Up?
</td>
</tr>
</table>
</form>
first of all, respect the cases in request.getParameter("UserName"); same as in name of input tag <input type="text" name="UserName" />
String firstname = request.getParameter("firstname"); this line will try to extract the parameter firstname from you POST request, in other words it extracts it from your login form which only contains two fields for login and password. so you just have to delete this line of code.
no need to use this User.getTransaction().begin(); in getting data from database
your query is wrong
try this code:
HttpSession session = request.getSession();
/*get username and password from the login form*/
String userName = request.getParameter("UserName");
String password = request.getParameter("password");
/*query to search customer having the username and password inserted in the login form*/
Query query = User.createQuery("select p from Customer p where p.userName = :uName and p.password = :uPassword");
query.setParameter("uName", userName);
query.setParameter("uPassword", password);
/*getting the result*/
Customer pass = (Customer) query.getSingleResult();
User.close();
/*if not null, means we have found the user (correct username and password), else login failed)*/
if(pass!=null){
session.setAttribute("Id", pass.getId());
String message="Welcome " + pass.getFirstname();
}
else{
String message="Authentication Error";
}
return new ModelAndView("userpage","pass",pass);

Inserting user records into MYSQL table

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.

Retrieving data from embedded database wont work

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

How to pass variable from java to jsp?

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

Updating database in JSP

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>

Categories