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

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>

Related

This page isn’t workingIf the problem continues, contact the site owner. HTTP ERROR 405

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'.

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>

method doPost, assignment of if in eclipse and servlets

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")){

Java EE - HTTP Error 404 - resource is not available - after hitting "Submit" button on page [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
My web program will allow a user to enter first name and last name and after the user press the submit button, it will print the first name and last name.
I receive an HTTP error 404 after the user presses the "Submit" button.
Error
This is my File structure
My codes
PrintFormContent.java
package form;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
#WebServlet("/PrintFormContent")
public class PrintFormContent extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PrintFormContent() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fname = request.getParameter("name");
String lname = request.getParameter("lname");
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>First Name</p>" + fname);
out.print("<p>Last Name</p>" + lname);
}catch(IOException e){
e.printStackTrace();
} }
}
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Form Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<form id="PrintFormContent" name="PrintFormContent" role="form"
action="/testForm/form/PrintFormContent" method="POST">
<div class="form-group row">
<label for="fname" class="col-md-2">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="fname"
placeholder="Enter First Name" name="fname" />
</div>
</div>
<div class="form-group row">
<label for="lname" class="col-md-2">First Name</label>
<div class="col-md-4">
<input type="text" class="form-control" id="lname"
placeholder="Enter Last Name" name="lname" />
</div>
</div>
<div style="text-align: center;">
<button id="btn" type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>testForm</display-name>
<servlet>
<servlet-name>PrintFormContent</servlet-name>
<servlet-class>PrintFormContent</servlet-class>
</servlet>
<welcome-file-list>
<welcome-file>/testForm/program/form/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Please Help.
you declared your servlet to PrintFormContent but you send your request to /testForm/form/PrintFormContent. You need to change it in the form-declaration:
<form id="PrintFormContent" name="PrintFormContent" role="form"
action="/PrintFormContent" method="POST">
btw. don't forget to change parameter name in the servlet to fname:
String fname = request.getParameter("fname");
try to add this to web.xml, somehow your anotation seems not to work
<servlet-mapping>
<servlet-name>PrintFormContent</servlet-name>
<url-pattern>/PrintFormContent</url-pattern>
</servlet-mapping>
check this, maybe you have the same problem: webservlet-annotation-doesnt-work-with-tomcat-8

inserting data into database using JSP [duplicate]

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","");

Categories