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) {
}
}
}
Related
I have a drop down list in a JSP which I am reading the values from and pass it into my servlet to perform actions based on the value received.
Below is my JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="getdata.do" method="post">
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</div>
</div>
<hr class="colorgraph">
<div class="row">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</div>
</form>
</body>
</html>
I gave the drop down list an ID: reportSelection
In my servlet class, I tried to read it as below:
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
String message;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("In POST Method");
getTableColumn gt = new getTableColumn();
String issue = request.getParameter("reportSelection");
System.out.println("Drop Down Message: " + issue);
try {
System.out.println("In Try");
if (issue.equals("Latency")) {
message = gt.cruise("latency");
} else if (issue.equals("DataQuality")) {
message = gt.cruise("DataQuality");
System.out.println("Data quality");
} else if (issue.equals("Outage")) {
message = gt.cruise("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I also printed the values of it just to see I am receiving any values from it.
But once I click on submit button, I see null pointer exception as
String issue = request.getParameter("reportSelection");
is receiving NULL from JSP
Could anyone let me know what is the mistake I am doing here & how do I correct it ?
I having a problem in sending json data from front end bootstrap to express servlet. Here is what i have tried. I use ajax to send data from my form to servlet class with json. please give my hand to solve this problem .here is my form to register student:
<html>
<head>
<link rel="stylesheet" type="text/css" href="resources/css/bootstrap.min.css">
<script type="text/javascript" src="resources/js/jquery.min.js"></script>
<script type="text/javascript" src="resources/js/bootstrap.min.js"> </script>
<script type="text/javascript">
function registerStudent() {
var firstName = $("#firstName").val();
var lastname = $("#lastname").val();
var phone = $("#phone").val();
var email = $("#email").val();
var studentCode = $("#studentCode").val();
$.ajax({
type : "POST",
url : "/RegisterStudent",
data :{data: "firstName=" + firstName + "lastname=" + lastname + " phone=" + phone + "email=" + email+"studentCode"+studentCode},
success : function(data) {
var ht = data.msg;
$("#resp").html(ht);
},
error : function(data) {
alert("Some error occured.");
}
});
}
</script>
</head>
<body>
<div class="container">
<div class="card " style="width:750px;margin:0px auto">
<div class="card-header">Student Register</div>
<div class="card-body">
<form data-toggle="validator" role="form" method="post" >
<div class="form-group">
<label class="control-label" for="firstName">Name</label>
<input class="form-control" data-error="Please enter name field." id="firstName" placeholder="Name" type="text" required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="lastname" class="control-label">lastname</label>
<input type="text" class="form-control" id="lastname" placeholder="lastname" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="phone" class="control-label">phone</label>
<div class="form-group">
<input type="text" data-minlength="5" class="form-control" id="phone" data-error="fill your phone" placeholder="phone" required>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<label class="control-label" for="email">email</label>
<textarea class="form-control" data-error="Please enter email field." id="email" placeholder="email" required=""></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="studentCode" class="control-label">studentCode</label>
<div class="form-group">
<input type="text" class="form-control" id="studentCode" data-error="fill your studentCode" placeholder="studentCode" required>
<div class="help-block with-errors"></div>
</div>
</div>
</form>
</div>
<button onclick="registerStudent();" type="button" class="btn btn-success btn-block">Register</button>
<div class="text-center" id="resp" style="margin-top: 14px;"></div>
</div>
</div>
and this is my servletclass for send data to database .
#WebServlet(urlPatterns = "/RegisterStudent")
public class RegisterStudentController extends HttpServlet {
StudentServiceInter service = new StudentServiceImpl();
ObjectMapper mapper = new ObjectMapper();
String json = "";
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Student student = new Student();
req.getSession().setAttribute("student", student);
resp.sendRedirect("/addStudent.jsp");
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String jsonData = req.getParameter("data");
resp.setContentType("application/json");
PrintWriter out = resp.getWriter();
out.println(jsonData);
out.close();
}
}
Try this...
$.ajax({
type: 'GET',
url: '<?php echo base_url(); ?>"/RegisterStudent"', // your syntax
data: {
'firstName ': firstName ,
'lastName' :lastname,
'phone': phone,
'email' : email,
'studentCode' : studentCode,
},
success : function(data) {
var ht = data.msg;
$("#resp").html(ht);
},
error : function(data) {
alert("Some error occured.");
}
});
One problem is that, client-side, you are not creating json, and server side you try to parse a json. Json format doesn't have equal (=) sign.
A valid object is:
data = {
data: {
firstName: 'Name',
lastName: 'Surname',
phone: '123-4456',
email: 'a#b.c',
studentCode: 12345
}
};
and before sending it you should do JSON.stringify(data).
I'm using Spring and I would like to submit my agentForm with POST method but submitNewAgent isn't called on form submit. However, it works when I replace POST by GET. I've been working on it for a few days now, and I have no idea what to change. Does anyone can help me please ?
Here my files
new.html
<!DOCTYPE html>
<html lang="fr"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.w3.org/1999/xhtml"
layout:decorator="index" >
<head th:replace="index :: head">
<link href="../../static/css/bootstrap.min.css" rel="stylesheet" media="screen" />
</head>
<body>
<th:block layout:fragment="body">
<h1 class="page-header"> Nouvel Agent </h1>
<form class="form" th:modelAttribute="agentForm" th:object="${agentForm}" action="/agents/ajouter-submit/" method="POST">
<div class="form-group">
<label>Prénom</label>
<div th:if="${#fields.hasErrors('prenom')}" th:errors="*{prenom}" class="text-danger">
Erreur prénom
</div>
<input type="text" th:field="*{prenom}" class="form-control" />
</div>
<div class="form-group">
<label th:for="*{nom}">Nom</label>
<div th:if="${#fields.hasErrors('nom')}" th:errors="*{nom}" class="text-danger">Erreur nom</div>
<input type="text" th:field="*{nom}" class="form-control" />
</div>
<div class="form-group">
<button class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span>
<span th:remove="tag" th:text="#{label.add}"></span>
</button>
</div>
</form>
</th:block>
</body>
</html>
AgentForm.class
public class AgentForm {
#NotNull
#Size(min=2, max=255)
private String prenom;
#NotNull
#Size(min=2, max=255)
private String nom;
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
#Override
public String toString() {
return "Agent{" +
"prenom='" + prenom + '\'' +
", nom='" + nom + '\'' +
'}';
}
}
AgentController.class link agent views and agent model.
#Controller
#RequestMapping("/agents")
public class AgentController {
private final AgentService agentService;
#Autowired
public AgentController(AgentService agentService) {
this.agentService = agentService;
}
/**
* Gets all agents
*
* #param model view
* #return template name
*/
#RequestMapping(value = {"/", "lister"}, method = RequestMethod.GET)
public String allAgents(Model model) {
List<Agent> agentList = agentService.findAll();
if (agentList != null)
model.addAttribute("agentList", agentList);
return "agents/list";
}
/**
* Displays form to add an agent
*
* #return template and attributes
*/
#RequestMapping(value = {"/", "ajouter"}, method = RequestMethod.GET)
public ModelAndView addAgentForm() {
AgentForm a = new AgentForm();
a.setNom("test");
a.setPrenom("prenom");
return new ModelAndView("agents/new", "agentForm", a);
}
/**
* Manages the form to add an agent and submit in the repository
*
* #param agentForm form
* #param result results
* #param model form the view
* #param attributes view attributes
* #return url
*/
#RequestMapping(value = {"/", "ajouter-submit"}, method = RequestMethod.POST)
public String submitNewAgent(#ModelAttribute("agentForm") #Validated AgentForm agentForm,
BindingResult result, Model model, final RedirectAttributes attributes) {
if (result.hasErrors())
return "agents/new";
agentService.saveAndFlush(AgentAdapter.adaptAgentFormToAgent(agentForm));
attributes.addFlashAttribute("css", "success");
attributes.addFlashAttribute("msg", "L'agent est correctement ajouté !");
return "redirect:/agents/lister";
}
}
I'm sorry for mixing English and French.
<!DOCTYPE html>
<html lang="fr"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.w3.org/1999/xhtml"
layout:decorator="index" >
<head th:replace="index :: head">
<link href="../../static/css/bootstrap.min.css" rel="stylesheet" media="screen" />
</head>
<body>
<th:block layout:fragment="body">
<h1 class="page-header"> Nouvel Agent </h1>
<form class="form" th:modelAttribute="agentForm" th:object="${agentForm}" th:action="#{ajouter-submit}" method="POST">
<div class="form-group">
<label>Prénom</label>
<div th:if="${#fields.hasErrors('prenom')}" th:errors="*{prenom}" class="text-danger">
Erreur prénom
</div>
<input type="text" th:field="*{prenom}" class="form-control" />
</div>
<div class="form-group">
<label th:for="*{nom}">Nom</label>
<div th:if="${#fields.hasErrors('nom')}" th:errors="*{nom}" class="text-danger">Erreur nom</div>
<input type="text" th:field="*{nom}" class="form-control" />
</div>
<div class="form-group">
<button class="btn btn-primary"><span class="glyphicon glyphicon-ok"></span>
<span th:remove="tag" th:text="#{label.add}"></span>
</button>
</div>
</form>
</th:block>
</body>
</html>
I need to implement the Mercado Pago custom checkout to receive payments in my site. To do it I need to run the javascript code to get the card_token_id, like described in this link: https://developers.mercadopago.com/documentation/custom-checkout?lang=en_US.
But my website, for business restrictions, need to get this card_token_id running into a Java code, into my class. I need to run this javascript code into my Java class, get the result, e use him in a http POST. I already tried use ScriptEngine, but not works.
See below the complete code that works in html.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pagar</title>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://secure.mlstatic.com/org-img/checkout/custom/1.0/checkout.js"></script>
</head>
<body>
<h1>Fluxo de pagamento personalizado (avançado)</h1>
<form action="" method="post" id="form-pagar-mp">
<input id="amount" type="hidden" value="100"/>
<p>Número do cartão: <input data-checkout="cardNumber" type="text" value="4509953566233704"/></p>
<p>Código de Segurança: <input data-checkout="securityCode" type="text" value="123"/></p>
<p>Mês de vencimento: <input data-checkout="cardExpirationMonth" type="text" value="12"/></p>
<p>Ano de vencimento: <input data-checkout="cardExpirationYear" type="text" value="2020"/></p>
<p>Titular do cartão: <input data-checkout="cardholderName" type="text" value="Joao"/></p>
<p>Número do documento: <input data-checkout="docNumber" type="text" value="19313777584"/></p>
<input data-checkout="docType" type="text" value="CPF"/>
<p id="issuersField">Bancos: <select id="issuersOptions"></select>
<p>Parcelas: <select id="installmentsOption"></select>
<p><input type="submit" value="Concluir pagamento"></p>
</form>
<script type="text/javascript">
/* Troque com a sua public_key */
Checkout.setPublishableKey("TEST-cba0f2d5-c989-4c97-8e61-847121530093");
$("input[data-checkout='cardNumber']").bind("keyup",function(){
var bin = $(this).val().replace(/ /g, '').replace(/-/g, '').replace(/\./g, '');
if (bin.length == 6){
Checkout.getPaymentMethod(bin,setPaymentMethodInfo);
}
});
// Estabeleça a informação do meio de pagamento obtido
function setPaymentMethodInfo(status, result){
$.each(result, function(p, r){
$.each(r.labels, function(pos, label){
if (label == "recommended_method") {
Checkout.getInstallments(r.id ,parseFloat($("#amount").val()), setInstallmentInfo);
Checkout.getCardIssuers(r.id,showIssuers);
return;
}
});
});
};
// Mostre as parcelas disponíveis no div 'installmentsOption'
function setInstallmentInfo(status, installments){
var html_options = "";
for(i=0; installments && i<installments.length; i++){
html_options += "<option value='"+installments[i].installments+"'>"+installments[i].installments +" de "+installments[i].share_amount+" ("+installments[i].total_amount+")</option>";
};
$("#installmentsOption").html(html_options);
};
function showIssuers(status, issuers){
var i,options="<select data-checkout='cardIssuerId'><option value='-1'>Escolha...</option>";
for(i=0; issuers && i<issuers.length;i++){
options+="<option value='"+issuers[i].id+"'>"+issuers[i].name +" </option>";
}
options+="</select>";
if(issuers.length>0){
$("#issuersOptions").html(options);
}else{
$("#issuersOptions").html("");
$("#issuersField").hide();
}
};
$("#issuersOptions").change(function(){
var bin = $("input[data-checkout='cardNumber']").val().replace(/ /g, '').replace(/-/g, '').replace(/\./g, '').slice(0, 6);
Checkout.getInstallmentsByIssuerId(bin,this.value,parseFloat($("#amount").val()),setInstallmentInfo);
});
$("#form-pagar-mp").submit(function( event ) {
var $form = $(this);
Checkout.createToken($form, mpResponseHandler);
event.preventDefault();
return false;
});
var mpResponseHandler = function(status, response) {
var $form = $('#form-pagar-mp');
if (response.error) {
alert("Ocorreu um erro: "+JSON.stringify(response));
} else {
var card_token_id = response.id;
$form.append($('<input type="text" id="card_token_id" name="card_token_id"/>').val(card_token_id));
alert("card_token_id: "+card_token_id);
$form.get(0).submit();
}
}
</script>
</body>
</html>
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>