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();
}
}
}
Related
I keep getting the error This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 405
I created a signup form. but when I submit, it doesn't show the action page.
**In html:
**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Signup Form</title>
<link rel="stylesheet" href="\assets\css\main.css">
</head>
<body>
<nav class="flex-container">
<div class="one"><img src="\assets\images\vanierlogo.jpg" alt="logo"></div>
<div class="two"><a href=\signup.html>Signup</a></div>
<div class="three">Login</div>
</nav>
<div id="txtHint"></div>
<form>
<h3>Create New Student Account</h3><br><br>
<label for="username">Student ID: </label>
<input type="text" id="username" name="username" required><br><br>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="firstName"><br><br>
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="lastName"><br><br>
<label>Enter Password<sup>*</sup>: </label>
<input type="password" autocomplete="passwd" name="passwd" required><br><br>
<label>Confirm Password: </label>
<input type="password" autocomplete="passwd1" name="passwd1" required><br><br>
<label>Are you Full-Time or Part-Time?</label><br><br>
<label for="Full-Time">Full-Time</label>
<input type="radio" id="Full-Time" name="status" value="Full-Time">
<label for="Part-Time">Part-Time</label>
<input type="radio" id="Part-Time" name="status" value="Part-Time"><br><br>
<input type="submit" onclick="createAccount(this)" value="Sign Up!"><br><br>
<footer>* Password must be at least 3 characters in length</footer>
</form>
<script src="\assets\js\main.js"></script>
</body>
</html>
In main.js:
function createAccount(element) {
const currForm = element.closest('form');
const params = "username="+currForm.elements[0].value +
"&firstName="+currForm.elements[1].value +
"&lastName="+currForm.elements[2].value +
"&passwd="+currForm.elements[3].value +
"&passwd1="+currForm.elements[4].value +
"&status="+currForm.elements[5].value;
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:80/SignupHandlingServlet",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhttp.readyState == 4) {
alert("DONE");
alert(xhttp.status);
if (xhttp.status==409 || xhttp.status==417 || xhttp.status==200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
else {
alert(xhttp.method);
let response = JSON.parse(xhttp.responseText);
document.querySelector("#ipText").innerHTML = response.ip;
}
}
else if (xhttp.readyState==0) {
alert("request unsent");
} else if (xhttp.readyState==1){
alert("request OPENED");
} else if(xhttp.readyState==2) {
alert("request HEADERS_RECEIVED");
} else {
alert("The HTTP request response is being downloaded");
}
}
}
**In web.xml:
**
<web-app>
<servlet>
<servlet-name>SignupHandlingServlet</servlet-name>
<servlet-class>SignupHandlingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupHandlingServlet</servlet-name>
<url-pattern>/SignupHandlingServlet</url-pattern>
</servlet-mapping>
</web-app>
**In java:
**
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
#WebServlet("/SignupHandlingServlet")
public class SignupHandlingServlet extends HttpServlet {
/* Process the HTTP Post request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Obtain parameters from the client
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
if (Interpreter.usernameExists(username)) {
out.println("<br><br>That username already exists.<br>");
response.setStatus(417);
}
else if (!passwd.equals(request.getParameter("passwd1"))) {
out.println("<br><br>Please confirm password<br>");
response.setStatus(409);
}
else {
String lastName = request.getParameter("lastName");
String firstName = request.getParameter("firstName");
String status = request.getParameter("status");
Student CreateStudent = new Student(username, passwd, firstName, lastName, status);
Interpreter.saveStudentCredentials(CreateStudent);
out.println("<br><br>Account created successfully<br>");
response.setStatus(200);
}
out.close(); // Close stream
}
}
Any help please? it's my 1st front end school project. It's been long debugging this error with no success.
I was expecting a createAccount page with result of the doPost() printed out.
click here to view my folder structure
When submitting a form, only input fields with the name attribute are submitted.
For inputs 'username', 'new-password' and 'new-password1', there is no name attribute and hence no data sent to server. So, accessing 'passwd' variable (which is null) with equals method will throw 'NullPointerException'.
That this wrong in the code? I want to make an answer HttpServlet with an if but "I appear "the left-hand an assignment must be a variable" in the last else, I cannot correctly declare the method, How can I fix it?
package controladores;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class AjaxController
*/
#WebServlet("/AjaxController")
public class AjaxController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AjaxController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain ");
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
if(action.equals("demo1")){
String nombreCompleto = request.getParameter("nombreCompleto");
out.println("Hola " + nombreCompleto);
}
else if (action.equals("demo2")){
int a = Integer.parseInt(request.getParameter("numero1"));
int b = Integer.parseInt(request.getParameter("numero2"));
out.println(a + b);
} else(action.equals("demo3")){
int d = Integer.parseInt(request.getParameter("numa"));
int c = Integer.parseInt(request.getParameter("numb"));
out.println(c * d);
}
}
}
and index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Demo Ajax</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet"/>
<link href="" rel="stylesheet"/>
<link type="text/css" rel="stylesheet" href="resources/css/miPrimerCSS.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#unHola').click(function(){
var nombreCompleto = $('#nombreCompleto').val();
$.ajax({
type:'POST',
data: {
nombreCompleto : nombreCompleto,
action: 'demo1'
},
url: 'AjaxController',
success: function(result){
$('#resultadoNombre').html(result);
}
});
});
$('#unaSuma').click(function(){
var numero1 = $('#numero1').val();
var numero2 = $('#numero2').val();
$.ajax({
type:'POST',
data: {
numero1 : numero1,
numero2 : numero2,
action: 'demo2'
},
url:'AjaxController',
success : function(result){
$('#resultadoSuma').html(result);
}
});
});
$('#unProducto').click(function(){
var numero1 = $('#numa').val();
var numero2 = $('#numb').val();
$.ajax({
type:'POST',
data: {
numa : numa,
numb : numb,
action: 'demo3'
},
url:'AjaxController',
success : function(result){
$('#resultadoProd').html(result);
}
});
});
});
</script>
</head>
<body>
<nav>
<div class="nav-wrapper">
Logo
<ul class="right hide-on-med-and-down">
<li>Home</li>
<li>Pages</li>
<li>About us</li>
<li>Lab</li>
<!-- Dropdown Trigger -->
<!-- <li><a class="dropdown-button" href="#!" data-activates="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li> -->
</ul>
</div>
</nav>
<div class="container">
<p class="z-depth-5">
<fieldset>
<h3>Un Hola</h3>
<form>
Introduce tu nombre <input type="text" id="nombreCompleto"><br>
<input type="button" value="Hola" id="unHola"><br>
<span id="resultadoNombre"></span>
</form>
</fieldset>
</div>
<br><br>
<div class="container">
<fieldset>
<h3>Una Suma</h3>
<form>
Numero 1 <input type="text" id="numero1"><br>
Numero 2 <input type="text" id="numero2"><br>
Resultado <span
id=resultadoSuma></span><br> <input type="button" value="Suma"
id="unaSuma">
</form>
</fieldset>
</div>
<div class="container">
<fieldset>
<h3>Un Producto</h3>
<form>
Numero 1 <input type="text" id="numero1"><br>
Numero 2 <input type="text" id="numero2"><br>
Resultado <span id=resultadoProd></span><br> <input type="button" value="Producto"
id="unProducto">
</form>
</fieldset>
</div>
<footer class="page-footer">
<div class="container">
<h5 class="white-text">Footer Content</h5>
</div>
<div class="footer-copyright">
<div class="container">
© 2014 Copyright Text
<a class="grey-text text-lighten-4 right" href="#!">More Links</a>
</div>
</div>
</footer>
</body>
</html>
} else(action.equals("demo3")){
I assume you meant:
} else if(action.equals("demo3")){
I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.
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.
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>