inserting data into database using JSP [duplicate] - java

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
I am trying to insert data into my database using following JSP code. I have created database named music and table named tbl_user. After I have entered all the related fields in register.jsp, the control goes to Insertdata.java but data is not going into database.
This is my JSP page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Bootstrap core CSS -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="assets/css/signin.css" rel="stylesheet">
<link href="assets/css/login.css" rel="stylesheet">
<script src="assets/js/bootstrap.js"></script>
<title>Sign UP</title>
</head>
<body>
<div class="container">
<div class="clearfix"></div>
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default login">
<div class="panel-heading">Register Here</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="post" action="Insertdata">
<div class="form-group">
<label for="firstname" class="col-sm-3 control-label"> First Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="firstname" name="fname" placeholder="First Name">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-3 control-label"> Last Name</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="lastname" name="lname" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="adress" class="col-sm-3 control-label">Address</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="address" name="address" placeholder="Address">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control" id="inputEmail3" name="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-3 control-label">Password</label>
<div class="col-sm-8">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-10">
<button type="submit" class="btn btn-default"">Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
This is my servlet for database connection DatabaseConnection.java
package mypackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DatabaseConnection {
Connection conn;
Statement stmt;
ResultSet res;
public DatabaseConnection(){
}
public Connection setConnection(){
try{
System.out.println("sdsadasd");
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/music","root","");
System.out.println("Connected to the database");
}catch(Exception e){
}
return conn;
}
public ResultSet getResult(String sql,Connection conn){
this.conn=conn;
try{
stmt=conn.createStatement();
res=stmt.executeQuery(sql);
}catch(Exception e){
}
return res;
}
}
This is my servlet to insert data Insertdata.java
package mypackage;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Insertdata extends HttpServlet {
String fname,lname,address,email,password;
String query;
Connection conn;
Statement stmt;
ResultSet res;
DatabaseConnection dbconn;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
dbconn=new DatabaseConnection();
//Af_Scheme_Number=request.getParameter("Af_Scheme_Number");
fname=request.getParameter("fname");
lname=request.getParameter("lname");
address=request.getParameter("address");
email=request.getParameter("email");
password=request.getParameter("password");
conn=dbconn.setConnection();
stmt=conn.createStatement();
query= "insert into tbl_user(first_name,last_name,address,email,password)"+
" values('"+fname+"','"+lname+"','"+address+"',"+email+",'"+ password+"')";
int i=stmt.executeUpdate(query);
} catch(Exception e){
System.out.println("Error");
}finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}

Just a vocabulary point : class DatabaseConnection is not a servlet. But you should read (or read again) a good tutorial on JDBC :
you do not correctly test the different operations to properly close what you have opened in case of error
you do not close what you have opened if things go right
you copy parameters from the request in an insert query - google around for SQL injection to understand whay you should never do that
you do not log the result from executeUpdate
you hide the exception that can occur but writing "Error" instead of the full stacktrace that could help to understand what happens.
You should begin by writing a Junit test to control that you can successfully write to database outside of the servlet context. And only when that part works correctly, you integrate the persistence code with into the web application.

remove localhost and try 127.0.0.1 ... it worked for me
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/music","root","");

Related

JSP & Servlet & Maven: form attribute "action" redirects to another jsp page, instead of sendRedirect method

I have created a login form in my index.jsp file:
<%# page contentType="text/html; ISO-8859-1" language="java" %>
<html>
<head>
<title>Material Master Data Manager</title>
<meta charset="ISO-8859-1">
<link rel="stylesheet" href="css/login_style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div id="basicData">
<div id="createMaterialHeader">
<h2><i><b>Material Master Data Manager</b></i></h2>
<div id="newPasswordBar">
<p>New Password</p>
</div>
</div>
<form class="tabcontent" action="MaterialCreator" method="post">
<label for="client">Client</label><br>
<select type="text" name="client" id="client">
<option>Commerzbank AG S.A. Branch in Lodz</option>
<option>Daikin Airconditioning Poland Sp. z o.o.</option>
<option>Infosys Consulting</option>
</select><br>
<label for="userID">User ID</label><br>
<input type="text" id="userID" name="userID"><br>
<label for="userPassword">Password</label><br>
<input type="password" id="userPassword" name="userPassword"><br>
<label for="isAdmin">Admin</label><br>
<input type="text" id="isAdmin" name="isAdmin"><br>
<input type="submit" class="fa fa-check">
</form>
</div>
</div>
<footer>
<p><a>© Created by Lorem Ipsum. 2017</a></p>
</footer>
</body>
<script src='javaScript/loginJs.js'></script>
</html>
That is MaterialCreator servlet:
package com.mmdmanager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
#WebServlet("/MaterialCreator")
public class MaterialCreator extends HttpServlet {
Connection dbConnection;
PreparedStatement getCredentialsFromDb;
ResultSet userCredentialsReceived;
String userCredentials = "SELECT USER_ID, FIRST_NAME, LAST_NAME, SEX, COMPANY_NAME, IS_ADMIN, ACC_PASSWORD FROM USERS " +
"WHERE COMPANY_NAME =? AND USER_ID =? AND ACC_PASSWORD =? AND IS_ADMIN =?";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
doGet(request,response);
String company_name = request.getParameter("client");
String user_id = request.getParameter("userID");
String acc_password = request.getParameter("userPassword");
String is_admin = request.getParameter("isAdmin");
if (company_name.equals("Infosys Consulting") && user_id.equals("ADMIN1") && acc_password.equals("Q#3wertyuiop") && is_admin.equals("Y")) {
response.sendRedirect("MaterialCreator.jsp");
}
else {
response.sendRedirect("");
}
}
}
As You can see in the code above, the main idea is to redirect on condition that a user provides correct credentials (IF statement stores it). Unfortunately, no matter what credentials I provide, every time when I click the input button (class "fa fa-check") I am redirected to MaterialCreator servlet, not to MaterialCreator.jsp file, however the code contains method -> response.sendRedirect("MaterialCreator.jsp");, but it is invisible for the project.
MaterialCreator.jsp file has a very simple html code:
<%# page contentType="text/html; ISO-8859-1" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hello User!</h1>
</body>
</html>

request.getParameter() returning null values in servlet...dont know whats wrong

This is the html form from where i"m sending the data through input form....
<form role="form" action = "AddServlet" method="GET">
<div class="form-group">
<label for="name" class= "bg-primary">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter name of the book">
</div>
<div class="form-group">
<label for="author" class= "bg-primary">Author</label>
<input type="text" class="form-control" name="author" placeholder="Enter the authors name">
</div>
<div class="form-group">
<label for="count" class= "bg-primary">Count</label>
<input type="number" class="form-control" name="count" placeholder="Enter the number of books">
</div>
<div class="form-group">
<label for="description" class= "bg-primary">Description</label>
<textarea class="form-control" rows="5" name="description" placeholder="Enter book description"></textarea>
</div>
<input type="submit" value = "submit">
</form>
and this is the servlet where I'm recieving the data through request.getParameter....
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
#WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String name, author, description, count;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file
//creating seession factory object
SessionFactory factory=cfg.buildSessionFactory();
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Books b = new Books();
name = request.getParameter("name");
author = request.getParameter("author");
description = request.getParameter("description");
count = request.getParameter("count");
System.out.println(count + "dfghjkls");
b.setName(name);
b.setAuthor(author);
b.setDescription(description);
b.setCount(count);
session.persist(b);//persisting the object
t.commit();//transaction is commited
session.close();
System.out.println("successfully saved");
}
}
but this is returning null values...dont know whats going wrong with this...
Got the answer...label for= "name" was the problem....removed it..
perhaps "for = " was creating ambiguity and so browser couldnt collect data

How to combine an javabean with jquery validation plugin?

I am building a web app where users can sign up. I have a jquery validation method for the signup form.
What I need is to also validate the username for availability according to my database.
I am not allowed to use php to do this, so i need to use java, a javabean for that cause.
How can i combine jquery and java like this ? Should i use the "remote" command from jquery or combine validation with another function ?
If name already exists n database i don't want my form to submit.
Signup.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
<link rel="stylesheet" type="text/css" href="newcss.css" />
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css" rel="stylesheet"></link>
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/additional-methods.min.js" type="text/javascript"></script>
<script src="validate.js" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div id="container" align="center">
<h2>User Registration</h2>
<form action="welcome.xhtml" method="post" id="contact_form">
<div>
<label for="name">Name</label>
<input id="name" type="text" name="name"/>
<span id="nameInfo"></span>
</div>
<div >
<label for="email" >Email</label>
<input id="email" type="text" name="email"/>
<span id="emailInfo"></span>
</div>
<div>
<label for="password">password</label>
<input id="password" type="password" name="pass1"/>
<span id="pass1Info"></span>
</div>
<div>
<label for="confirm">confirm password</label>
<input id="confirm" type="password" name="pass2"/>
<span id="pass2Info"></span>
</div>
<div>
<label for="message">Message</label>
<textarea id="message" name="message"/>
<span id="messageInfo"></span>
</div>
<div>
<input id="send" name="send" type="submit" value="Send"/>
</div>
<br/>
<!-- <p>Already registered? Sign in.</p> -->
</form>
</div>
</body>
</html>
validate.js
$(document).ready(function () {
//Validation rules for form
$("#contact_form").validate({
// Specify the validation rules
rules: {
name: {
required: true
// remote: ???
},
password: {
required: true,
minlength: 5
},
confirm: {
required: true,
equalto: "#password"
},
email: {
required: true,
email: true
}
},
// Specify the validation error messages
messages: {
name: "Please enter your name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm:{
equalto: "Passwords are not matching"
},
email: "Please enter a valid email address"
},
submitHandler: function (form) {
form.submit();
}
});
});
CheckAvailability.java (I inserted as js, cause it would not retain its format)
package Beans;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final long serialVersionUID = -734503860925086969L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:3306/teddb"; // teddb is my database name
Connection connection;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "Sk1994!!");
String uname = request.getParameter("name");
PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("");
}
else{
out.println("Username already in use");
}
out.println();
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
}

Drop Down list Null Pointer JSP to Servlet

I'm having a difficulty in getting the value on my drop down list from jsp. I'm getting a Null value of String which is "" only. But if I use only textbox for the department It will work. I'm having a hard time of finding where is the error in my code.
This is my JSP file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.18.custom.min.js"></script>
</head>
<body>
<form method="POST" action='PersonnelController' name="frmAddData" class="form">
<fieldset>
<legend id="myLegend">User</legend>
<label for="firstname">First Name :</label>
<input type="text" name="firstname"
value="<c:out value="${data.firstname}" />" /><br />
<label>Last Name :</label>
<input type="text" name="lastname"
value="<c:out value="${data.lastname}" />" /><br />
<!--<label>Department Name :</label>
<input type="text" name="department_id"
value="<c:out value="${data.department_id}" />" /><br />-->
<label>Department Name :</label>
<select name="personnel">
<c:forEach items="${personnels}" var="personnel">
<option value="${personnel.department_id}"><c:out value="${personnel.department_name}" /></option>
</c:forEach>
</select>
</fieldset>
<input type="submit" value="Submit" class="submit"/>
</form>
</body>
</html>
This is for Servlet:
private DepartmentDao dd;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<DepartmentBean> personnels = dd.getAllDepartmentName();
request.setAttribute("personnels", personnels);
request.getRequestDispatcher("/WEB-INF/personnel.jsp").forward(request, response);
}
}
and this is my DAO:
public List<DepartmentBean> getAllDepartmentName() {
List<DepartmentBean> departments = new ArrayList<DepartmentBean>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select department_name,id from department ORDER BY department_name");
while (rs.next()) {
DepartmentBean department = new DepartmentBean();
department.setPeople_manager_name(rs.getString("department_name"));
departments.add(department);
}
} catch (SQLException e) {
e.printStackTrace();
}
return departments;
The problem is that you're not fulfilling the necessary fields in your DepartmentBean object reference in the dao class. You're only filling people_manager_name field, and in your JSP you're requesting the data for department_id and department_name, which will call DepartmentBean#getDepartment_id() and DepartmentBean#getDepartment_name() methods.
Change this in getAllDepartmentName method:
while (rs.next()) {
DepartmentBean department = new DepartmentBean();
department.setDepartment_name(rs.getString("department_name"));
department.setDepartment_id(rs.getInt("department_id"));
departments.add(department);
}
Here's a useful link about how expression language works.

Application using SOAP webservices, signup functionality not working on client side

Am creating a web application using SOAP web services in java. Sign up functionality works fine when I test through the test client at the server side however, at the client side when I fill in the details and click on signUp button the same page is getting refreshed but no action is being performed (data is not getting inserted into the database). When debugged, I saw that the code is failing at
if(qdone.equalsIgnoreCase("true")){
Could anyone please help me with this. I'm not knowing where am I going wrong.
Here is my code
signUp.jsp
<%# page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link href="Flat-UI-master/css/flat-ui.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link rel="shortcut icon" href="Flat-UI-master/images/favicon.ico">
<link rel="stylesheet" href="Flat-UI-master/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="css/icon-font.css">
</head>
<body>
<div id="page-wrapper">
<header class="header-11">
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="row">
<div class="navbar-collapse collapse in" style="height: auto;">
<ul class="nav navbar-nav">
<li class="active"><span class="glyphicon glyphicon-home"></span>Home</li>
<li>College Explorer
<li>Fund Raisers</li>
<li>FAFSA</li>
<li>Student Loans</li>
</ul>
<ul class="nav pull-right">
<li><a class="btn btn-primary" href="signIn.jsp">SIGN IN</a> </li>
</ul>
</div>
</div>
</div>
</div>
</header>
<br>
<br>
<br>
<section class="header-11-sub bg-midnight-blue">
<div class="background"> </div>
<div class="container">
<div class="row">
<div class="col-sm-4">
<h3>Task Tracker</h3>
<p>Make your life easy having a task tracker</p>
<div class="signup-form">
<form id="form" method="post" action="signUp">
<div class="form-group">
<input class="form-control" type="text" placeholder="username"
id="username">
</div>
<div class="form-group">
<input class="form-control" type="password"
placeholder="password" id="password">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="fname"
id="fname">
</div>
<div class="form-group">
<input class="form-control" type="text" placeholder="lname"
id="lname">
</div>
<div class="form-group">
<input class="form-control" type="text"
placeholder="email#example.com" id="email">
</div>
<div class="form-group">
<button type="submit" class="btn btn-large btn-primary">Sign
Up</button>
<a href='http://localhost:8080/FinalClient/View/signUp.jsp'
class="btn btn-large btn-primary">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</div>
<script class="cssdeck"
src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script class="cssdeck"
src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/js/bootstrap.min.js">
</script>
</body>
</html>
signUp Servlet (signUp.java)
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.jws.WebService;
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;
import javax.servlet.http.HttpSession;
import DefaultNamespace.ServiceProxy;
/**
* Servlet implementation class signUp
*/
#WebServlet("/signUp")
public class signUp extends HttpServlet {
private static final long serialVersionUID = 1L;
ServiceProxy proxy =new ServiceProxy();
/**
* #see HttpServlet#HttpServlet()
*/
public signUp() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out =response.getWriter();
response.setContentType("text/html");
String qdone;
try{
String username = request.getParameter("username");
String password = request.getParameter("password");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
if (!checkMandatorySignUpFields(username, password, fname, lname, email)) {
request.setAttribute("message", "Required Field Missing!");
String nextJSP = "/View/signUp.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}else {
proxy.setEndpoint("http://localhost:8080/Final/services/Service");
System.out.println("crossed the endpoint");
qdone=proxy.signUp(username,password,fname,lname,email);
System.out.println(qdone);
System.out.println("signup qdone");
HttpSession session =request.getSession();
System.out.println("Session started");
if(qdone.equalsIgnoreCase("true")){
System.out.println("qdone value obtained....signup successful");
session.setAttribute("userSession", session);
out.println("Welcome to CollegeTime Task planner" +username);
request.setAttribute("message", "Signup successful, Please login.");
String nextJSP= "/View/signIn.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}else{
out.println(qdone.equalsIgnoreCase("false"));
out.println("\n <a href='http://localhost:8080/FinalClient/View/signUp.jsp'><br>Go back to Signup and try again</a>");
request.setAttribute("message", "Unable to Signup!" + qdone);
String nextJSP = "/View/signUp.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
private boolean checkMandatorySignUpFields(String username, String password, String fname, String lname, String email){
// TODO Auto-generated method stub
return true;
}
}
Service.java (signup functionality) code at the Server side
#WebService
public class Service {
DatabaseConnection db = new DatabaseConnection();
String result="";
public String signUp(String username, String password, String fname, String lname, String email){
System.out.println("Inside SignUp");
result=db.signUp(username, password, fname, lname, email);
System.out.println("SignUp Successful");
System.out.println(result);
return result;
}
Database query implementation for signUp at server side
public String signUp(String username, String password, String fname, String lname, String email){
int rowcount=0;
String result = "";
Calendar cal= Calendar.getInstance();
String time = sdf.format(cal.getTime());
try{
String query="select * from user where username = '"+username+"'";
ResultSet res;
stm.executeQuery(query);
res=stm.getResultSet();
if(!res.next()){
String insertQuery = "insert into user(username, fname, lname, password, email, lastlogin) values ('"+username+"', '"+password+"','"+fname+"','"+lname+"','"+email+"','"+time+"')";
rowcount=stm.executeUpdate(insertQuery);
if(rowcount>0){
result ="true";
}
else{
result="false";
}
}
}catch(SQLException e){
e.printStackTrace();
}
System.out.println(result);
return result;
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>FinalClient</display-name>
<welcome-file-list>
<welcome-file>signUp.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>signUp</display-name>
<servlet-name>signUp</servlet-name>
<servlet-class>servlets.signUp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>signUp</servlet-name>
<url-pattern>/View/signUp</url-pattern>
</servlet-mapping>
</web-app>
My issue was solved. Just posting, in case if anyone in future come across the same issue.
I dint give name attribute in the signUp.jsp form
Previously in signUp.jsp:
<form id="form" method="post" action="signUp">
<div class="form-group">
<input class="form-control" type="text" placeholder="username"
id="username">
</div>
Later(Solution) in signUp.jsp (adding a name attribute):
<form id="form" method="post" action="signUp">
<div class="form-group">
<input class="form-control" type="text" placeholder="username"
id="username" name="username">
</div>

Categories