I am trying to get info from option boxes from my JSP page. An example of those are:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en" />
<title>Profile</title>
<link rel="shortcut icon" href="../favicon.png" />
<link rel="stylesheet" href="../reset.css" />
<link rel="stylesheet" href="app/claro.css" />
<link rel="stylesheet" href="app/theme/main.css" />
<script type="text/javascript">
// Configure application.
appConfig = {
// Get base url from current url.
baseUrl: location.href.substring(0,location.href.lastIndexOf("/")+1)
};
// Configure Dojo.
dojoConfig = {
parseOnLoad: true
};
</script>
<script type="text/javascript" src="http://cdn.devgrid.net/ajax/dojo/1.9.0/dojo/dojo.js"></script>
<script type="text/javascript">
// Load application.
require(
{
packages: [
{ name: 'app', location: appConfig.baseUrl + '/app/' }
]
},
[
"app"
]
);
</script>
</head>
<body class="claro">
<%
//allow access only if session exists
String user = null;
if(session.getAttribute("user") == null){
response.sendRedirect("login.jsp");
}else user = (String) session.getAttribute("user");
String userName = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<div class="appBorderContainer" data-dojo-type="dijit/layout/BorderContainer">
<div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top', splitter:false">
<center><IMG SRC="LogoPlaintech.png" width="30%"></center>
</div>
<div class="appLeadingAccordionContainer" data-dojo-type="dijit/layout/AccordionContainer" data-dojo-props="minSize:20, region:'leading', splitter:true">
<div data-dojo-type="dijit/layout/AccordionPane" title="Server status">
Server: RUNNING</br>
IP-address: 0.0.0.0</br>
Uptime: 12 hours 21 minutes 10 seconds </br>
</div>
<div data-dojo-type="dijit/layout/AccordionPane" title="Add a server">
<div data-dojo-type="dijit/form/Form" enctype="multipart/form-data" action="productServlet" method="post">
<div data-dojo-type="dojox/layout/TableContainer" data-dojo-props="cols:1">
<div data-dojo-type="dijit/form/TextBox" title="Name server:" name="name" value=""></div>
<select data-dojo-type="dijit/form/Select" title="Operating System:" name="os">
<option value="Windows">Windows Server 2012</option>
<option value="Ubuntu">Ubuntu 14.10</option>
<option value="Debian">Debian 7.7.0</option>
</select>
<select data-dojo-type="dijit/form/Select" title="Amount of cores:" name="cores">
<option value="1">1 core</option>
<option value="2">2 cores</option>
<option value="3">3 cores</option>
</select>
<select data-dojo-type="dijit/form/Select" title="RAM:" name="ram">
<option value="512">512 MB</option>
<option value="1024">1024 MB</option>
<option value="2048">2048 MB</option>
</select>
<select data-dojo-type="dijit/form/Select" title="HDD:" name="hdd">
<option value="20">20 GB</option>
<option value="35">35 GB</option>
<option value="50">50 GB</option>
<option value="75">75 GB</option>
</select>
</div>
<button id="btnSubmit" data-dojo-type="dijit/form/Button" type="submit" role="button">Submit</button>
</div>
</div>
<div data-dojo-type="dijit/layout/AccordionPane" title="Third pane">
Third pane content.
</div>
</div>
<div id="appCenterTabContainer" data-dojo-type="dijit/layout/TabContainer" data-dojo-props="splitter:true, region:'center'">
<div data-dojo-type="dijit/layout/ContentPane" title="Welcome">
<h3>Hi <%=userName %>, Login successful.</h3></br>
Welcome at your profile page <%=userName %>. </br>
We are happy to see you back.</br>
</br>
From this point it is possible to manage your VM('s), account info and backups.
</div>
<div data-dojo-type="dijit/layout/ContentPane" title="Connect to your server">
You can login to your server by SSH, with your credentials. </br>
IP-address: 0.0.0.0</br>
Port: 22</br>
Username: </br>
Password: </br>
</br>
<center>
<button data-dojo-type="dijit/form/Button" type="button" role="button">Connect
<script type="dojo/on" data-dojo-event="click" data-dojo-args="evt">
app.alert('You are now connecting to your server! Awesome ;-)');
</script>
</button>
</center>
</div>
</div>
<div class="appTrailingAccordionContainer" data-dojo-type="dijit/layout/AccordionContainer" data-dojo-props="minSize:20, region:'trailing', splitter:true">
<div data-dojo-type="dijit/layout/AccordionPane" title="Account info">
Fullname: </br>
${fullName}</br></br>
Email address: </br>
${email}</br></br>
Date of birth: </br>
${dateOfBirth}</br></br>
Phonenumber: </br>
${phoneNumber}</br></br>
<hr>
</br>
Company name: </br>
${companyName}</br></br>
Company email address: </br>
${companyEmail}</br></br>
Payment method: </br>
${paymentMethod}</br></br>
</br>
<button data-dojo-type="dijit/form/Button" type="button" role="button">
Change account info
</button>
</div>
<div data-dojo-type="dijit/layout/AccordionPane" title="Logout">
Are you sure you want to logout the user <%=userName %>?</br></br>
<div data-dojo-type="dijit/form/Form" id="LogoutServlet"
action="LogoutServlet" method="post">
<form action="LogoutServlet" method="post">
<table>
<tr>
<td><button data-dojo-type="dijit/form/Button" type="submit"
name="submitButton" value="Yes">Yes</button></td>
</tr>
</table>
<div data-dojo-type="dijit/form/Form" id="profile.jsp"
action="profile.jsp" method="post">
<form action="profile.jsp" method="post">
<table>
<tr>
<td><button data-dojo-type="dijit/form/Button" type="submit"
name="submitButton" value="No">No</button></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Now the problem is that I get an null pointer exception at line 32. So I guess the parameter Ram is empty or something? Am I trying todo this the wrong way? Please help me out here! thanks.
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class productServlet extends HttpServlet {
public String name;
public String os;
public String hdd;
public String processor;
public String ram;
public String userName;
public ResultSet rs, rs1;
public PreparedStatement pstmt;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// haal info van de website.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String Name = request.getParameter("name");
// zet de info van de website in public variables.
Name = name;
String[] OS = request.getParameterValues("os");
if(OS.equals("Windows")) {
os = "Windows";
} else if(OS.equals("Ubuntu")) {
os = "Ubuntu";
} else if(OS.equals("Debian")) {
os = "Debian";
}
String[] Processor = request.getParameterValues("cores");
if(Processor.equals("1")) {
processor = "1";
} else if(Processor.equals("2")) {
processor = "2";
} else if(Processor.equals("3")) {
processor = "3";
}
String[] Ram = request.getParameterValues("ram");
if(Ram.equals("512")) {
ram = "512";
} else if(Ram.equals("1024")) {
ram = "1024";
} else if(Ram.equals("2048")) {
ram = "2048";
}
String[] HDD = request.getParameterValues("hdd");
if(HDD.equals("20")) {
hdd = "20";
} else if(HDD.equals("35")) {
hdd = "35";
} else if(HDD.equals("50")) {
hdd = "50";
} else if (HDD.equals("75")) {
hdd = "75";
}
// test van OS
System.out.print(os);
}
Make sure your (comboboxes / option boxes) have between form tag start and close including your action button.
eg.
<form action="youraction" method="post/get">
//comboboxes / option boxes and your parameters
.........
.........
<button>.......submit/invoke button </button>
</form>
Related
This is my structure of the project:-
[1]: https://i.stack.imgur.com/ootY1.png
My problem is that whenever I am running my project on the server, there is an HTTP Status 404 Error.
This is the error I am getting by the server:-
The requested resource [/Doctor_Appointment_Application/Regis] is not available
I am using annotations to register my servlets and there is only a welcome file in my web.xml.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<display-name>User Login</display-name>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/JSP/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
My Register Servlet:-
package com.servlet;
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 com.bean.RegisBean;
import com.dao.RegisDao;
#WebServlet("/Regis")
public class Regis extends HttpServlet {
private static final long serialVersionUID = 1L;
public Regis() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fullname=request.getParameter("fullname");
String email=request.getParameter("email");
String username=request.getParameter("username");
String password=request.getParameter("password");
long mobile= Long.parseLong(request.getParameter("mobile"));
String address=request.getParameter("address");
String identity=request.getParameter("radio");
String specialisation=request.getParameter("special");
String degree=request.getParameter("degree");
String exp=request.getParameter("exp");
String fees=request.getParameter("fees");
RegisBean regisBean=new RegisBean();
regisBean.setFullname(fullname);
regisBean.setEmail(email);
regisBean.setUsername(username);
regisBean.setPassword(password);
regisBean.setMobile(mobile);
regisBean.setAddress(address);
regisBean.setIdentity(identity);
if(identity.equals("Doctor")) {
regisBean.setSpecialiasation(specialisation);
regisBean.setDegree(degree);
regisBean.setExperience(exp);
regisBean.setFees(fees);
}
RegisDao dao=new RegisDao();
String userRegistered=dao.registerUser(regisBean);
if(userRegistered.equals("SUCCESS"))
request.getRequestDispatcher("/JSP/conf.jsp").forward(request, response);
else {
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/JSP/register.jsp").forward(request, response);
}
}
}
EDIT 1:
Register.jsp:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration Page</title>
<style type="text/css">
<%-- <%#include file="/CSS/register.css"%> --%>
<%#include file="/CSS/regis.css"%>
</style>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<script>
function validate() {
var password = document.form.password.value;
var confpassword = document.form.confpassword.value;
/* if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
} else */ if (password != confpassword) {
alert("Confirm Password should match with the Password");
return false;
}
}
</script>
</head>
<body>
<form name="form" action="<%=request.getContextPath() %>/Regis" method="post" onsubmit="return validate()">
Full Name: <input type="text" name="fullname" required>
<br>
<br>
Email: <input type="text" name="email" required>
<br>
<br>
Username: <input type="text" name="username" required>
<br>
<br>
Password: <input type="password" name="password" required>
<br>
<br>
Confirm Password: <input type="password" name="confpassword" required>
<br>
<br>
Mobile Number: <input type="number" name="mobile" required>
<br>
<br>
Address: <input type="text" name="address" required>
<br>
<br>
Identity: Doctor <input type="radio" name="radio" value="Doctor" required>
<div class="reveal">
Specialisation: <select name="special" class="require-if-active">
<option selected disabled>Choose...</option>
<option value="Allergist">Allergist</option>
<option value="Anesthesiologist">Anesthesiologist</option>
<option value="Cardiologist">Cardiologist</option>
<option value="Dermatologist">Dermatologist</option>
<option value="Endocrinologist">Endocrinologist</option>
<option value="Gastroenterologist">Gastroenterologist</option>
<option value="Hematologist">Hematologist</option>
<option value="Immunologist">Immunologist</option>
<option value="Internist">Internist</option>
<option value="Neurologist">Neurologist</option>
<option value="Pulmonologist">Pulmonologist</option>
<option value="Oncologist">Oncologist</option>
</select>
<br>
<br>
Degree: <select name="degree" class="require-if-active">
<option selected disabled>Choose...</option>
<option value="MBBS">MBBS</option>
<option value="BDS">BDS</option>
<option value="BAMS">BAMS</option>
<option value="BUMS">BUMS</option>
<option value="BHMS">BHMS</option>
<option value="BYNS">BYNS</option>
<option value="B.V.Sc & AH">B.V.Sc & AH</option>
</select>
<br>
<br>
Experience: <input type="number" name="exp" class="require-if-active">
<br>
<br>
Fees: <input type="number" name="fees" class="require-if-active">
</div>
Patient <input type="radio" name="radio" value="Patient" required>
<span style="color: red"><%=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%></span>
<br>
<br> <input type="submit" value="Register">
</form>
</body>
</html>
EDIT 2:
I just tried to do an experiment, what I did is I created another jsp file and a servlet to check if the problem is in my jsp and servlet files or not. So the same thing happened, the jsp file ran successfully but the server wasn't abl to find the servlet after submitting the form method.
Any kind of help is appreciated.
Hello to whosoever is seeing this,
I solved this query by removing the mysqljdbc.auth.dll from my build path. This solved my problem and it is working fine now. If you are having a problem with the mysqljdbc.auth.dll file, you just have to copy it in the JDK 8 bin folder and it will work fine.
Update (based on the update posted in the question):
Replace
<form name="form" action="<%=request.getContextPath() %>/Regis" method="post" onsubmit="return validate()">
with
<form name="form" action="Regis" method="post" onsubmit="return validate()">
as the paths in a JSP are already relative to the context path.
Original answer:
The reason why you are getting this error is that by default, the server gets the request as GET whereas you have not provided any implementation of doGet in your servlet. If you are calling this servlet from a JSP/HTML, make sure you mention method="POST". If you are trying to call the servlet directly, you can either rename doPost to doGet or provide an implementation of doGet e.g.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
I have to create a form for update some user profile data. I develop this html form but when I submit and I try to get request parameters they all result null.
The form is filled with actual data and then you can modify them refilling with the new one.
Thanks
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="all" href="../CSS/style.css" th:href="#{.../CSS/style.css}"/>
<script type="text/javascript" src="../js/signup.js" th:src="#{/js/signup.js}" defer> </script>
<script type="text/javascript" src="../js/updateProfile.js" th:src="#{/js/updateProfile.js}" defer> </script>
<script type="text/javascript" th:src="#{/js/loadimage.js}" defer ></script> <!--defer fa eseguire js dopo il parsing di html-->
</head>
<body>
<div class="container">
<h1>Profilo Utente</h1>
<div class="form">
<form action="updateprofile" method="post" enctype="multipart/form-data" onsubmit="return formValidation()">
<p>
<label for="username">Username: </label><br>
<input type="text" id="username" name="username" th:attr="value=${session.user.username}" required/><br>
</p>
<p>
<label for="email">Mail: </label><br>
<input type="email" id="email" name="email" th:attr="value=${session.user.email}" required/><br>
</p>
<p>
<label for="password">Password: </label><br>
<input type="password" id="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Deve contenere almeno 8 caratteri di cui un numero, una lettera maiuscola e una lettera minuscola." /><br>
</p>
<p>
<label id="text-password-confirm" for="password-confirm">Reinserisci password: </label><br>
<input type="password" id="password-confirm" />
</p>
<p id="password-message" class="error-message"></p>
<p>
Tipo di utente:<br>
<input type="radio" name="usertype" id="manager" value="manager" th:checked="${session.user.isManager!=null && session.user.isManager}" required/>
<label for="manager">Manager</label><br>
<input type="radio" name="usertype" id="worker" value="worker" th:checked="${session.user.isManager!= null && !session.user.isManager}" checked required/>
<label for="worker">Worker</label><br>
</p>
<div id="worker-data">
<p>
<label for="exp">Exp level:</label><br>
<select name="exp" id="exp">
<option value="" disabled selected>Exp level</option>
<option value="LOW" th:selected="${session.user.exp == 'LOW'}">LOW</option>
<option value="MEDIUM" th:selected="${session.user.exp == 'MEDIUM'}">MEDIUM</option>
<option value="HIGH" th:selected="${session.user.exp == 'HIGH'}">HIGH</option>
</select><br>
</p>
<p>
<label for="photo">Profile photo</label><br>
<div id="container"style="position: relative; width:300px;">
<canvas id="canvas_background" width="300px" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
<input type="file" name="photo" id="photo" accept="image/*"/><br>
</div>
<!-- TODO: Rivedere i messaggi di errore inseriti -->
<span class="error-message" th:if="${session.signupfailed}">Salvataggio non riuscito</span>
<p>
<input id="buttonModifica" type="button" value="Modifica" />
<input id="buttonAnnulla" type="reset" value="Annulla" />
<input id="buttonAggiorna" type="submit" value="Aggiorna" />
</p>
</form>
</div>
</div>
</body>
</html>
This is java code of the Update Profile controller
public class UpdateProfile extends AbstractServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("sessionUser");
if (user != null && user.isValid()){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
boolean isManager = request.getParameter("usertype").equals("manager");
String photo;
Level exp;
if (isManager) {
photo = null;
exp = null;
} else {
photo = ImageEncoder.encodeImage(request.getPart("photo"));
exp = Level.valueOf(request.getParameter("exp"));
}
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setIsManager(isManager);
user.setPhoto(photo);
user.setExp(exp);
}
try {
UserDAO userDAO = new UserDAO(connection);
userDAO.updateProfile(user);
success=true;
} catch (SQLException e) {
}
}
This are javascript code included in signup.jsp:
function formValidation(e) {
var confirm_password = document.getElementById("password-confirm");
if (comparePassword(confirm_password, "Le due password non coincidono") ) {
/*e.preventDefault();
window.history.back();*/
return true;
}
return false;
}
function comparePassword(inputtext, alertMsg){
var password = document.getElementById("password");
if(inputtext.value != password.value) {
document.getElementById('password-message').innerText = alertMsg;
inputtext.focus();
return false;
} else {
return true;
}
}
This is javascript code included in updateProfile.jsp:
var username = document.getElementById("username");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordConfirm = document.getElementById("password-confirm");
var radioWorker = document.getElementById("worker");
var radioManager = document.getElementById("manager");
var exp = document.getElementById("exp");
var photo = document.getElementById("photo");
var buttonModifica = document.getElementById("buttonModifica");
var buttonAnnulla = document.getElementById("buttonAnnulla");
var buttonAggiorna = document.getElementById("buttonAggiorna");
function init() {
username.readOnly=true;
email.readOnly=true;
password.readOnly=true;
passwordConfirm.hidden=true;
radioManager.disabled=true;
radioWorker.disabled=true;
exp.disabled=true;
photo.disabled=true;
buttonAnnulla.hidden=true;
buttonAggiorna.hidden=true;
buttonModifica.addEventListener("click", abilitaModifica)
password.addEventListener("change", verificaPassword)
}
function abilitaModifica() {
email.readOnly=false;
password.readOnly=false;
exp.disabled=false;
photo.disabled=false;
buttonAnnulla.hidden=false;
buttonAggiorna.hidden=false;
buttonModifica.hidden=true;
}
function verificaPassword() {
passwordConfirm.hidden=false;
}
init();
try to update your servlet code with this one..
#WebServlet(
name = "UpdateProfile",
urlPatterns = {"/updateprofile"})
public class UpdateProfile extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("sessionUser");
if (user != null && user.isValid()){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
boolean isManager = request.getParameter("usertype").equals("manager");
String photo;
Level exp;
if (isManager) {
photo = null;
exp = null;
} else {
photo = ImageEncoder.encodeImage(request.getPart("photo"));
exp = Level.valueOf(request.getParameter("exp"));
}
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setIsManager(isManager);
user.setPhoto(photo);
user.setExp(exp);
}
try {
UserDAO userDAO = new UserDAO(connection);
userDAO.updateProfile(user);
success=true;
} catch (SQLException e) {
}
}
}
I encountered a problem in the connection between an HTML page and a servlet in Java. I already had this problem a few days ago but it was my mistakes in project management.
Now, it seems to me that I have done everything properly but I cannot deal with it.
In particular I'm creating an HTML page that contains a form with the action that call a servlet. My HTML page is on the "Web content" directory automatically created by Eclipse when I create a new Dynamic web project.
my WebServlet annotation is "#WebServlet(/UploadBook)" and the action on the form tag is "action=UploadBook".
When I click on the submit button the page this is the message that I receive:
Not Found
The requested URL /coltraneShop/Administrator/adminColtraneShop/WebContent/UploadBook was not found on this server.
I'm using Firefox on MacOS and apache webServer is started. I added, moreover, the Dynamic web project on server tomcat 9 from Eclipse and started it without problem.
This is my servlet Java code:
package insertion;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/UploadBook")
public class UploadBook extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out= response.getWriter();
Long productCode= (long) 0;
//Fetch data from HTML form method POST
String title= request.getParameter("Title");
String quantity= request.getParameter("Quantity");
String yearOfPublication= request.getParameter("yearOfPublication");
String genre= request.getParameter("Genre");
String numPages= request.getParameter("numPages");
String ISBN= request.getParameter("ISBN");
String publisher= request.getParameter("publisher");
String writerName1= request.getParameter("writerName1");
String writerSurname1= request.getParameter("writerSurname1");
String writerDateOfBirth1= request.getParameter("writerDateOfBirth1");
String writerGender1= request.getParameter("writerGender1");
Connection connection= null;
//Connect to DB
try {
connection= connectDB();
}
catch (ClassNotFoundException | SQLException ConnectionException) {
System.out.println("Error in connection!");
out.print("Connection to DB is not avaiable. " + ConnectionException.getMessage());
}
//Send query to DB
try {
//Preparing statement and query to DB
PreparedStatement statementProduct = connection.prepareStatement("INSERT INTO coltraneShop.Product (Category, `Title`, Quantity, `Year of publication`)"
+ "VALUES ('Book', ?, ?, ?);", Statement.RETURN_GENERATED_KEYS);
//Passing parameters
statementProduct.setString(1, title);
statementProduct.setInt(2, Integer.parseInt(quantity));
statementProduct.setInt(3, Integer.parseInt(yearOfPublication));
int affectedRows= statementProduct.executeUpdate();
if(affectedRows == 0)
throw new SQLException("Creating product failed, no rows affected.");
//Return ID of product insert in DB
ResultSet resultSet = statementProduct.getGeneratedKeys();
if(resultSet.next())
productCode= resultSet.getLong(1);
statementProduct.close();
out.print("<p>Added a product</p><br>");
PreparedStatement statementBook = connection.prepareStatement("INSERT INTO coltraneShop.Book VALUES (?, ?, ?, ?, ?);");
statementBook.setString(1, genre);
statementBook.setInt(2, Integer.parseInt(numPages));
statementBook.setLong(3, Long.parseLong(ISBN));
statementBook.setString(4, publisher);
statementBook.setLong(5, productCode);
int affectedRowsBook= statementBook.executeUpdate();
if(affectedRowsBook == 0)
throw new SQLException("Creating book failed, no rows affected.");
statementBook.close();
out.print("<p>Added a book</p><br>");
PreparedStatement statementWriter1 = connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
statementWriter1.setString(1, writerName1);
statementWriter1.setString(2, writerSurname1);
statementWriter1.setString(3, writerDateOfBirth1);
statementWriter1.setString(4, writerGender1);
int affectedRowswriter1= statementWriter1.executeUpdate();
if(affectedRowswriter1 == 0)
throw new SQLException("Creating writer failed, no rows affected.");
statementWriter1.close();
out.print("<p>Added a writer</p><br>");
int elementInRequest= request.getContentLength();
if(elementInRequest > 10) {
int numAdditionalWriter= (elementInRequest - 10) / 4;
for(int i=0; i<(numAdditionalWriter); i++) {
PreparedStatement statementAdditionalWriter= connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
statementAdditionalWriter.setString(1, ("writerName" + (i+2)));
statementAdditionalWriter.setString(2, ("writerSurname" + (i+2)));
statementAdditionalWriter.setString(3, "writerDateOfBirth" + (i+2));
statementAdditionalWriter.setString(4, "writerGender" + (i+2));
int affectedRowsAdditionalWriter= statementAdditionalWriter.executeUpdate();
if(affectedRowsAdditionalWriter == 0)
throw new SQLException("Creating addtional writer failed, no rows affected.");
statementAdditionalWriter.close();
out.print("<p>Added a writer</p><br>");
}
}
}
catch (SQLException exceptionInQuery) {
System.out.println("Error in the query");
out.print("Error in statement or process of sending queries to the database. " + exceptionInQuery.getMessage());
}
try {
connection.close();
}
catch (SQLException closeConnectionException) {
System.out.println("Problem in closing connection");
out.print("Problem in closing connection. " + closeConnectionException.getMessage());
}
out.close();
}
private Connection connectDB() throws ClassNotFoundException, SQLException {
Connection connection= null;
Class.forName("com.mysql.cj.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/coltraneShop?useTimezone=true&serverTimezone=UTC", "root", "");
return connection;
}
}
And This is my HTML form code:
<head>
<title>Insert book in the database</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<!--Bootstrap CSS-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="administrator.js"></script>
</head>
<body>
<form action="UploadBook" method="POST">
<div class="container">
<div class="form-group">
<label> <strong>Title:</strong> </label>
<input type="text" name="Title" class="form-control" placeholder="Title of book" maxlength="50" required>
</div>
<div class="form-group">
<label> <strong>Quantity:</strong> </label>
<input type="text" class="form-control" name="Quantity" placeholder="Max quantity in stock can be 999" maxlength="3" pattern="[0-9]{1,3}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Year of publication:</strong> </label>
<input type="text" class="form-control" name="yearOfPublication" placeholder="Year of publication" maxlength="4" pattern="[0-9]{1,4}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Genre:</strong> </label>
<select class="form-control" name= "Genre" required>
<option value="History" >History</option>
<option value="Fantasy">Fantasy</option>
<option value="Child">Child</option>
<option value="Art">Art</option>
<option value="Music">Music</option>
<option value="Thriller">Thriller</option>
<option value="Travel">Travel</option>
<option value="Biography">Biography</option>
<option value="Poetry">Poetry</option>
<option value="Romance">Romance</option>
<option value="Science">Science</option>
</select>
</div>
<div class="form-group">
<label> <strong>Number of pages:</strong> </label>
<input type="text" class="form-control" name="numPages" placeholder="Max length: 99.999 pages" maxlength="5" pattern="[0-9]{1,5}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>ISBN:</strong> </label>
<input type="text" class="form-control" name="ISBN" placeholder="13-digit code" maxlength="13" pattern="[0-9]{1,13}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Publisher:</strong> </label>
<input type="text" class="form-control" name="publisher" placeholder="The name of the publishing house" maxlength="30" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's name:</strong> </label>
<input type="text" class="form-control" name="writerName1" placeholder="The name of the Writer" maxlength="20" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's surname:</strong> </label>
<input type="text" class="form-control" name="writerSurname1" placeholder="The surname of the Writer" maxlength="20" pattern="[A-z]{1,20}" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's date of birth:</strong> </label>
<input type="date" class="form-control" name="writerDateOfBirth1"></input>
</div>
<div class="form-group">
<label> <strong>Writer's gender:</strong> </label>
<input type="text" class="form-control" name="writerGender1" placeholder="Gender of writer: can be 'M' or 'F' or 'N(on defined)'" maxlength="1" pattern="^(M|F|N)" ></input>
</div>
<div class="form-group" id="containerWriters">
<button type="button" class="btn btn-outline-success" id="addWriterButton" onclick="addWriter()"> Add Writer </button>
<button type="button" class="btn btn-outline-danger" id="removeWriterButton" onclick="removeWriter()"> Remove Writer </button>
</div>
<!--Submit all data -->
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Insert" id="submit"></input>
</div> <!--Container div-->
</form>
<!-- Bootstrap jQuery, Ajax and JavaScript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
Thank a lot for helping me.
It looks like you loaded file directly from file system and the tried to call this servlet. This is not correct. Load this HTML via your Tomcat, i.e. via URL like
http://localhost:8080/.../xxx.html.
If because of some reason you still want to use static HTML without Tomcat, then change servlet URL in your HTML to a full URL like following:
<form action="http://localhost:8080/.../UploadBook" method="POST">
If none of this is your case, then provide more info, how exactly are you loading HTML in you browser.
I'm having a problem with my one page contact form.
When i click the submit button, i run a javascript check to see if the fields are filled.
The check works fine but i don't have any clue why the PHP isn't responing.
i can't use another php page to do the processing because i want to use the same contact page for other contact purposes.
So this is the sequence i want to get:
1. Form gets filled in
2. On click of the submit butten, javascript checks the fields.
3. If okay, javascript submits the form
4. if mail has been sent, the page is reloaded to contact.php?MailStatus=Success
5. if not (it will run a javascript giving en errormessage telling the user to retry without the fields being cleared.
contact.php (code)
<!DOCTYPE html>
<html>
<head>
<title>Mijn Dier En Ik</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="www.csl-tech.be" />
<meta name="description" content="Op zoek naar dierenhotels, artsen, winkels,... Dan is Mijn Huisdier en Ik de website die je zoekt. Neem een kijkje!" />
<link rel="stylesheet" type="text/css" href="CSLCSS.css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="functions.js"></script>
</head>
<body>
<div class="container csl-main">
<div class="row">
<div class="col-md-6">
<form id="MailForm" method="post">
<div id="Message"></div>
<div id="FormFields">
<div class="form-group">
<label for="fname">Voornaam</label>
<input class="form-control" type="text" id="fname" placeholder="Uw voornaam...">
</div>
<br />
<div class="form-group">
<label for="lname">Achternaam</label>
<input class="form-control" type="text" id="lname" placeholder="Uw achternaam...">
</div>
<br />
<div class="form-group">
<label for="email">E-mail</label>
<input class="form-control" type="text" id="email" placeholder="Uw e-mail...">
</div>
<br />
<div class="form-group">
<label for="country">Land</label>
<select class="form-control" id="country" name="country">
<option value="Belgie">Belgiƫ</option>
<option value="Nederland">Nederland</option>
</select>
</div>
<br />
<div class="form-group">
<label for="subject">Onderwerp</label>
<select class="form-control" id="subject" name="subject">
<option value="Vragen">Vragen over Mijn Dier en Ik</option>
<option value="Suggesties">Suggesties voor de website</option>
<option value="Reservatie of Contact">Vragen over het reservatie- en/of contactsysteem</option>
<option value="Foto inzending">Foto inzenden</option>
<option value="Aanpassing gegevens">Aanpassing gegevens</option>
<option value="Andere">Andere</option>
</select>
</div>
<br />
<div class="form-group">
<label for="message">Uw bericht</label>
<textarea class="form-control" id="message" placeholder="Typ hier uw bericht..." style="height:200px"></textarea>
</div>
<br />
<input id="submit" class="btn btn-default" value="Versturen" onclick="CheckMailEntry()">
</div>
</form>
</div>
</div>
</div>
</body>
<?php
if ($_GET['MailStatus'] == 'Success') {
echo '<script type="text/javascript">MailSuccess()</script>';
}
if(isset($_POST['submit'])) {
header('Location: contact.php?MailStatus=Success');
echo 'ok';
}
?>
</html>
Javascript code:
function CheckMailEntry() {
document.getElementById("Message").innerHTML = "";
if (document.getElementById("fname").value == "") {
document.getElementById("Message").innerHTML = "<div class='alert alert-danger'><strong>Fout:</strong> Voer uw voornaam in.</div>";
} else if (document.getElementById("lname").value == "") {
document.getElementById("Message").innerHTML = "<div class='alert alert-danger'><strong>Fout:</strong> Voer uw achternaam in.</div>";
} else if (document.getElementById("email").value == "") {
document.getElementById("Message").innerHTML = "<div class='alert alert-danger'><strong>Fout:</strong> Voer uw email in.</div>";
} else if (document.getElementById("message").value == "") {
document.getElementById("Message").innerHTML = "<div class='alert alert-danger'><strong>Fout:</strong> Gelieve een bericht te typen.</div>";
} else {
document.getElementById("Message").innerHTML = "";
document.getElementById("submit").submit();
};
};
function MailSuccess() {
document.getElementById("Message").innerHTML = "<div class='alert alert-success'><strong>Succes:</strong> Wij hebben uw mail ontvangen en zullen deze zo snel mogelijk beantwoorden.</div>";
document.getElementById("FormFields").innerHTML = "";
};
I have trouble with CSS in JSP pages.
CSS files are not loaded in any page.
I have this JSP page which is a registration form for a student.
I have a page works correctly but that page has no information from my database.
The rest of pages include some lines and some data from the database.
I really don't know where the problem is so I need your help :(
Student form :
<%#page import="java.util.List"%>
<%#page import="tables.Optionn"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<base href="${pageContext.request.contextPath}">
<link href="Style/bootstrap.css" rel="stylesheet" type="text/css">
<link href="Style/font-awesome.css" rel="stylesheet" />
<link href="Style/style.css" rel="stylesheet">
<link href="Style/style-responsive.css" rel="stylesheet">
<% List<Optionn> option = (List<Optionn>) request.getAttribute("option_list");%>
<title>Etudiant</title>
</head>
<body>
<div class="container" id="registration_form">
<form method="post" class="form-login" action="//localhost:8086/GestionPfe/reg_etudiant">
<h2 class="form-login-heading" >ajouter un Etudiant!</h2>
<div class="login-wrap">
Option: <br> <select name="opt" class="form-control">
<%for (Optionn tempop : option) {%>
<option value=<%=tempop.getIdOption()%> > <%=tempop.getNomOption()%></option>
<%}%>
</select><br>
Nom: <br> <input name="nom_etudiant" type="text" class="form-control">
<br>
Prenomt: <br> <input name="prenom_etudiant" type="text" class="form-control">
<br>
Niveau: <br> <input name="niveau_etudiant" type="text" class="form-control">
<br>
Date De Naissance: <br><input name="date_naissance_etudiant" type="date" class="form-control">
<br>
Numero D'inscription: <br> <input name="num_inscription_etudiant" type="text" class="form-control">
<br>
Adresse: <br> <input name="adresse_etudiant" type="text" class="form-control">
<br>
Email: <br><input name="email_etudiant" type="email" class="form-control">
<br>
Mot De Pass: <br><input name="mot_de_pass_etudiant" type="password" class="form-control">
<br>
Telephone: <br><input name="telephone_etudiant" type="text" class="form-control">
<br>
<button type="submit" class="btn btn-theme btn-block"><i class="fa fa-lock"></i> SIGN IN</button>
</div>
</form>
</div>
</body>
</html>
Student Servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String op= request.getParameter("opt");
String nom_etudiant= request.getParameter("nom_etudiant");
String prenom_etudiant= request.getParameter("prenom_etudiant");
String niveau_etudiant= request.getParameter("niveau_etudiant");
String num_inscription_etudiant= request.getParameter("num_inscription_etudiant");
String date_naissance_etudiant= request.getParameter("date_naissance_etudiant");
String adresse_etudiant = request.getParameter("adresse_etudiant");
String email_etudiant = request.getParameter("email_etudiant");
String mot_de_pass_etudiant = request.getParameter("mot_de_pass_etudiant");
String telephone_etudiant = request.getParameter("telephone_etudiant");
try {
int idop=Integer.parseInt(op);
int tel=Integer.parseInt(telephone_etudiant);
SimpleDateFormat simpledate=new SimpleDateFormat("yyy-MM-dd");
Date birthdayDate = simpledate.parse(date_naissance_etudiant);
Optionn opt = new Optionn();
opt = (Optionn) session.get(Optionn.class,idop);
Etudiant etudiant=new Etudiant(opt,nom_etudiant,prenom_etudiant,niveau_etudiant, mot_de_pass_etudiant,num_inscription_etudiant,birthdayDate,adresse_etudiant,email_etudiant,tel);
session.save(etudiant);
session.getTransaction().commit();
session.close();
response.sendRedirect("Jsp/home.jsp");
} catch (ParseException ex) {
Logger.getLogger(reg_agent.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Add ".." to all your path,
<link href="../Style/style.css" rel="stylesheet">
Try this :
try {
int idop=Integer.parseInt(op);
int tel=Integer.parseInt(telephone_etudiant);
SimpleDateFormat simpledate=new SimpleDateFormat("yyy-MM-dd");
Date birthdayDate = simpledate.parse(date_naissance_etudiant);
Optionn opt = new Optionn();
opt = (Optionn) session.get(Optionn.class,idop);
Etudiant etudiant=new Etudiant(opt,nom_etudiant,prenom_etudiant,niveau_etudiant, mot_de_pass_etudiant,num_inscription_etudiant,birthdayDate,adresse_etudiant,email_etudiant,tel);
session.save(etudiant);
session.getTransaction().commit();
session.close();
RequestDispatcher dispatcher = request.getRequestDispatcher("Jsp/home.jsp");
dispatcher.forward(request, response);
} catch (ParseException ex) {
Logger.getLogger(reg_agent.class.getName()).log(Level.SEVERE, null, ex);
}