I am trying to validate the login and password of the user, in that if not enter the login fields and password will appear a message in the screen "Please fill in the fields of login or password" or if the user type the wrong username or password will appear an "Incorrect Login or Password" screen message but it does not show the messages.
Why does not it show the message on the jsp page?
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String vazio="Por favor preencha os campos de login ou senha";
String incorretos="Login ou senha incorretos";
String login = request.getParameter("login");
String senha = request.getParameter("senha");
Cliente cli= new Cliente();
LoginDAO login2= new LoginDAO();
Cliente login_validacao=login2.validacaoLogin(login,senha);
if(login_validacao.getLogin()==null && login_validacao.getSenha()==null){
request.setAttribute("vazio", vazio);
}
else if(login_validacao.getLogin().equals(request.getParameter("login"))
& login_validacao.getSenha().equals((request.getParameter("senha")))){
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
else{
request.setAttribute("incorreto", incorretos);
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/jquery-1.12.0.min.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput.js" type="text/javascript"></script>
<script src="js/jquery.maskedinput.min.js" type="text/javascript">
</script>
<script src="bootstrap/bootstrap.min.js" type="text/javascript">
</script>
<script src="bootstrap/bootstrap.js" type="text/javascript"></script>
<link rel="stylesheet" href="bootstrap/bootstrap.css">
<link rel="stylesheet" href="css/css.css" type="text/css">
<link rel="stylesheet" href="css/font-awesome.min.css" type="text/css"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-
awesome.min.css" rel="stylesheet">
<title>JSP Page</title>
</head>
<body>
<div class="login-form">
<div class="row">
<div class="col-6 col-md-4"></div>
<div class="col-6 col-md-4">
<h2 id="AcesseConta"><span>Acesse sua Conta</span></h2>
<label for="vazio_resposta">${vazio}</label>
<label for="validacao">${incorreto}</label>
</div>
</div>
<div class="row">
<div class="col-6 col-md-4"></div>
<div class="col-6 col-md-4">
Login:<input type="text" id="login" name="login" ><br/><br/>
Senha:<input type="text" id="senha" name="senha" ><br/>
Não é cadastrado?Cadastre-se<br/><br/>
</div>
</div>
<div class="row">
<div class="col-6 col-md-4"></div>
<div class="col-6 col-md-4">
<div id="teste"></div>
<button type="button" onclick="login()" >Entrar</button> <button
type="button" onclick="" >Esqueceu a Senha?</button>
</div>
</div>
</div>
</body>
</html>
Instead of validating HTML Form Using Controller/Servlet You Can use 'REQUIRED' tag in html as follow.
Login:<input type="text" id="login" name="login" Required><br/><br/>
Senha:<input type="text" id="senha" name="senha" Required><br/>
And Displaying message on JSP from servlet use below code
for Servlet
if(login_validacao.getLogin()==null && login_validacao.getSenha()==null)
{
response.sendRedirect("login.jsp?vazio=" + URLEncoder.encode(vazio, "UTF-8"));
}
else if(login_validacao.getLogin().equals(request.getParameter("login"))
& login_validacao.getSenha().equals((request.getParameter("senha"))))
{
RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
else
{
response.sendRedirect("login.jsp?incorretos=" + URLEncoder.encode(incorretos, "UTF-8"));
}
FOR JSP
<c:if test="${!empty vazio}">
<p style="color:red;" align="center">${param.vazio}</p>
</c:if>
Related
Here is my code and it throws exception of : Excepted condition faild to locate element
whats the problem with my code? why driver can't catch html elements.
below after the code, html of the page source on the browser which i can't get from the driver.
//////////////////////////////////////////////////////////////
String proxySetting = internalConstant.getAddress() + ":" + internalConstant.getPort();
System.setProperty("webdriver.chrome.driver","C://driver/chromedriver.exe");
Proxy proxy = new Proxy();
proxy.setHttpProxy(proxySetting);
proxy.setSslProxy(proxySetting);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("proxy", proxy);
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = driver = new ChromeDriver(capabilities);
driver.get(internalConstant.getUrl());
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
try {
logger.info("current url: " + driver.getCurrentUrl());
new WebDriverWait(driver, 20, 5000).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id=\"ctl00_PlaceHolderMain_signInControl\"]")));
new WebDriverWait(driver, 20, 5000).until(ExpectedConditions.elementToBeClickable(By.id("ctl00_PlaceHolderMain_signInControl_UserName"))).sendKeys(this.internalConstant.getUsername());
driver.findElement(By.id("ctl00_PlaceHolderMain_signInControl_password")).sendKeys(this.internalConstant.getPassword());
driver.findElement(By.id("ctl00_PlaceHolderMain_signInControl_login")).click();
catch(TimeoutException e){
logger.info("time out exp: " + e.toString());
}
finally {
driver.quit();
}
and here is the html page source:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:o="urn:schemas-microsoft-com:office:office" lang="en-us" dir="ltr">
<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="Expires" content="0" /><meta http-equiv="X-UA-Compatible" content="IE=8"/><meta name="ROBOTS" content="NOHTMLINDEX" /><title>
Sign In
</title><link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/corev15.css?rev=ox%2BqLd6WTqhn6d%2FMqf2BMw%3D%3D"/>
<link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/error.css?rev=nc1850SZNy60qTAeQIRxsA%3D%3D"/>
<script type="text/javascript" src="/_layouts/15/init.js?rev=%2FWTxr8UesytJ8GB%2F5hOwZA%3D%3D"></script>
<script type="text/javascript" src="/ScriptResource.axd?d=b8aG9BSsOzH4Psxrq74Zvc_pIn6eY3of7kBqwPeEeJ8P2XA_lSkmKIifnqd9-IL8CEPfvU6k16J_-_YZ5r2ZblfXiIw1EXtGjGRd08Brd5mgiYh6xWXZ7F3pKzK0NyqjRinRUVml7y_P1P24kyakvpLM7lXNE1ZgeReCzD0S-35tYv52FWCflKfCauowft6K0&t=ffffffff805766b3"></script>
<script type="text/javascript" src="/_layouts/15/blank.js?rev=ZaOXZEobVwykPO9g8hq%2F8A%3D%3D"></script>
<script type="text/javascript" src="/ScriptResource.axd?d=8PxrTGbFqBTOmbVOY6PYJ-dNFoq_7BTGppdUkof9uYJ_c_8T-FyZDw8LmG1aWZJM6J49rRIXs-9xGZqJW1umdLd4XQJMFTDswrFyS5pCwqYnvdoprb_5wevdVDkXh4JwfjAHvOpc6RjsFpVFZ5c7AVLop_vMOeT4-uFQQs-n4zUJT_i6nzkqV4BCVM9IJ14Y0&t=ffffffff805766b3"></script>
<script type="text/javascript">RegisterSod("initstrings.js", "\u002f_layouts\u002f15\u002f1033\u002finitstrings.js?rev=4Yrxyggg5knao3D48Ii\u00252FWA\u00253D\u00253D");</script>
<script type="text/javascript">RegisterSod("strings.js", "\u002f_layouts\u002f15\u002f1033\u002fstrings.js?rev=u\u00252B0KcZWR52dtr8LTlqcZcw\u00253D\u00253D");RegisterSodDep("strings.js", "initstrings.js");</script>
<script type="text/javascript">RegisterSod("sp.init.js", "\u002f_layouts\u002f15\u002fsp.init.js?rev=3nSw25FIGbfepznMSgi74A\u00253D\u00253D");</script>
<script type="text/javascript">RegisterSod("sp.res.resx", "\u002f_layouts\u002f15\u002fScriptResx.ashx?culture=en\u00252Dus\u0026name=SP\u00252ERes\u0026rev=yNk\u00252FhRzgBn40LJVP\u00252BqfgdQ\u00253D\u00253D");</script>
<script type="text/javascript">RegisterSod("sp.ui.dialog.js", "\u002f_layouts\u002f15\u002fsp.ui.dialog.js?rev=0xf6wCIW4E1pN83I9nSIJQ\u00253D\u00253D");RegisterSodDep("sp.ui.dialog.js", "sp.init.js");RegisterSodDep("sp.ui.dialog.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("core.js", "\u002f_layouts\u002f15\u002fcore.js?rev=uA2xjCXmuYM5ARP8g3eTSA\u00253D\u00253D");RegisterSodDep("core.js", "strings.js");</script>
<link rel="shortcut icon" href="/_layouts/15/images/favicon.ico?rev=23" type="image/vnd.microsoft.icon" /></head>
<body id="ms-error-body" onload="if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();">
<form method="post" action="default.aspx?ReturnUrl=%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F&Source=%2f" id="aspnetForm" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}">
<div class="aspNetHidden">
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPBSpWU0tleTozNzIwYjA0My0wZTRiLTRmOTEtOTIwYS1jN2YwNzRjMGQzZWNkn/24vz5ZtU1zojuNDN6GIpggcfrrpaNh3Ux0Gy5TR6w=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=v_PLJBJCpIcKkSvMlNKF0P2DNOij3yylWhnXYr-eXN-HgXXLTGjYbYt4QJ10YYwXDpQAFDr9Ika8viTaiTlLGWHvOxKh0ovxrXhxpv-uBoU1&t=635589543571259667" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var g_presenceEnabled = true;
var g_wsaEnabled = false;
var g_wsaQoSEnabled = false;
var g_wsaQoSDataPoints = [];
var g_wsaLCID = 1033;
var g_wsaListTemplateId = null;
var _fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\u002f", webAbsoluteUrl: "https:\u002f\u002fremittance.bankalbilad.com", siteAbsoluteUrl: "https:\u002f\u002fremittance.bankalbilad.com", serverRequestPath: "\u002f_forms\u002fdefault.aspx", layoutsUrl: "_layouts\u002f15", webTitle: "", webTemplate: "", tenantAppVersion: "none", webLogoUrl: "\u002fSiteAssets\u002fEnjazLogo.png", webLanguage: 1033, currentLanguage: 1033, currentUICultureName: "en-US", currentCultureName: "en-US", clientServerTimeDelta: new Date("2020-11-06T19:02:00.6935939Z") - new Date(), siteClientTag: "14$$15.0.4569.1000", crossDomainPhotosEnabled:false, webUIVersion:15, webPermMasks:{High:0,Low:0}, pagePersonalizationScope:1, alertsEnabled:false, siteServerRelativeUrl: "\u002f", allowSilverlightPrompt:'True',"themedCssFolderUrl" : "/_catalogs/theme/Themed/C7475956","themedImageFileNames" : {"spcommon.png" : "spcommon-B35BB0A9.themedpng?ctag=4","ellipsis.11x11x32.png" : "ellipsis.11x11x32-2F01F47D.themedpng?ctag=4","O365BrandSuite.95x30x32.png" : "O365BrandSuite.95x30x32-C212E2FD.themedpng?ctag=4","socialcommon.png" : "socialcommon-6F3394A9.themedpng?ctag=4","spnav.png" : "spnav-230C537D.themedpng?ctag=4"}};var MSOWebPartPageFormName = 'aspnetForm';//]]>
</script>
<script src="/_layouts/15/blank.js?rev=ZaOXZEobVwykPO9g8hq%2F8A%3D%3D" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(DeferWebFormInitCallback) == 'function') DeferWebFormInitCallback();//]]>
</script>
<script src="/WebResource.axd?d=JKZNQQPGwhxlZ02QrerbO_XIcgR4915gcRBEEQOD70Ab7Yez0BwpZBhk-oHFF4AlJD79wCvy3oNRCS9mrby8Yghy6toAP1me9FsA6E5vVig1&t=635589543571259667" type="text/javascript"></script>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="2EB18009" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAAQXglRNYXr74m4KXXhr5Tg7D3gNq6qp/JTilQw5ZNkpfe4vJyKPNbAHwGois4u5nam1l6dqP2Wbh/cJ6mTdRfbZbWeydvlh6wRzCcTcUOMRXZNxPizwWTG/l3GXqkCZTi4=" />
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ctl00$ScriptManager', 'aspnetForm', [], [], [], 90, 'ctl00');
//]]>
</script>
<div id="ms-error-header" class="ms-pr">
<h1 class="ms-core-pageTitle">
</h1>
<div>
</div>
</div>
<div id="ms-error">
<div id="ms-error-top">
</div>
<div id="ms-error-content">
<div id="ms-error-error-content">
<div id="DeltaPlaceHolderMain">
<style>
body{font-family:tahoma !important;font-size:13px !important;}
.login_holder{width:600px;height:450px;background:#eaeaea;margin:40px auto 0 auto;border:1px solid #eaeaea;
-webkit-box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.50);
-moz-box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.50);
box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.50);}
.logo_holder{width:100%;background:#fff;border-bottom:2px solid #fcb034;padding:10px 0}
.login_holder p{padding:10px;color:#455560}
.user_div, .pass_div{padding:10px !important;}
.user_div label, .pass_div label{width:120px !important;color:#999 !important;display:inline-block !important;font-weight:bold !important;text-align:right !important;padding:10px !important;}
.text_in{width:320px !important;height:35px !important;border:1px solid #CCC !important;padding:0 10px !important;color:#666 !important;font-size:17px !important;}
.enter_btn{cursor:pointer !important;float:left !important;margin:15px 0 0 158px !important;width:150px !important;height:40px !important;background:#455560 !important;border:1px solid #455560 !important;color:#fff !important;}
.enter_btn:hover{background:#ef4035;border:1px solid #333;}
.login_error{color:#c60f13;font-weight:bold}
.clear{clear:both;float:none}
</style>
<div class="login_holder">
<div class="logo_holder">
<img src="/_layouts/Remittance.WebApp/images/EnjazLogo.png"" alt="" />
</div>
<p id="SslWarning" style="color:red;display:none">
Warning: this page is not encrypted for secure communication. User names, passwords, and any other information will be sent in clear text. For more information, contact your administrator.
</p>
<script language="javascript" >
if (document.location.protocol != 'https:')
{
var SslWarning = document.getElementById('SslWarning');
SslWarning.style.display = '';
}
</script>
<table id="ctl00_PlaceHolderMain_signInControl" cellspacing="0" cellpadding="0" style="width:100%;border-collapse:collapse;">
<tr>
<td>
<div class="user_div">
<label>User name:</label>
<input name="ctl00$PlaceHolderMain$signInControl$UserName" type="text" id="ctl00_PlaceHolderMain_signInControl_UserName" class="text_in" autocomplete="off" />
</div>
<div class="pass_div">
<label>Password:</label>
<input name="ctl00$PlaceHolderMain$signInControl$password" type="password" id="ctl00_PlaceHolderMain_signInControl_password" class="text_in" autocomplete="off" />
</div>
<input type="submit" name="ctl00$PlaceHolderMain$signInControl$login" value="Sign In" id="ctl00_PlaceHolderMain_signInControl_login" class="enter_btn" />
<div class="clear"></div>
<div style="padding:10px;"><span id="ctl00_PlaceHolderMain_signInControl_FailureText" class="login_error"></span></div>
<div class="clear"></div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
var _fV4UI = true;WebForm_AutoFocus('ctl00_PlaceHolderMain_signInControl');//]]>
</script>
</form>
</body>
</html>
Actually there is no need to wait for the visibility of the table fist and then wait for the visibillity of the box to send the username so first of all
remove this line:
new WebDriverWait(driver, 20, 5000).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id=\"ctl00_PlaceHolderMain_signInControl\"]")));
Use this xpath for the usernamebox :
//input[#id='ctl00_PlaceHolderMain_signInControl_UserName']
Try this xpath for the passwordbox :
//input[#id='ctl00_PlaceHolderMain_signInControl_password']
From my experience By.xpath is better than By.id
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);
}
Below is my code where i would be using to pass data to another domain. I am having this problem where with request.getParameter("accType"); the value could not be retrieved. However , other value is working fine, the names are correct and form has a post method on it, can anybody help me with this? Thanks in advance.
<%--
Document : viewEmployee
Created on : Jan 23, 2018, 12:06:44 AM
Author : AaronLee
--%>
<%#page import="java.sql.ResultSet"%>
<%# page import = "da.employeeDA" %>
<jsp:useBean id="employeeDA" class="da.employeeDA" scope="application" ></jsp:useBean>
<jsp:setProperty name="employeeDA" property="*" />
<%--import domain page--%>
<%# page import = "domain.employee" %>
<jsp:useBean id="employee" class="domain.employee" scope="application" ></jsp:useBean>
<jsp:setProperty name="employee" property="*" />
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%!
ResultSet rs = null;
%>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<%--import css--%>
<link href="font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<link href="css/website.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%--Bootstrap CSS--%>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"/>
<title>Account Details</title>
</head>
<body>
<div class="wrapper">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="homepage.jsp">Document</a>
</div>
<ul class="nav navbar-nav">
<li>+ Document</li>
<li class="active">+ Claim</li>
<li>Search Document</li>
<li>Search Claim</li>
<li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Account<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>Log Out</li>
</ul>
</li>
</ul>
</div>
</nav>
<div class="content">
<%
//login session
String username = null;
if (session.getAttribute("username") == null) {
response.sendRedirect("Login.jsp");
username = null;
return;
} else {
username = session.getAttribute("username").toString();
}
%>
<% try {
rs = employeeDA.searchEmployee(username);
} catch (Exception ex) {
ex.getMessage();
}
if (rs.next()) {
%>
<form method="POST" action="viewEmployee.jsp" >
Account Type :<br/>
<input type="text" value="<%=rs.getString("ACCTYPE")%>" name="accType" disabled /><br/><br/>
Employee ID :<br/>
<input type="text" value="<%=rs.getString("EMPLOYEEID")%>" name="employeeID" disabled/><br/><br/>
Name : <br/>
<input type="text" value="<%=rs.getString("EMPLOYEENAME")%>" name="employeeName"/><br/><br/>
Contact Number :<br/>
<input type="text" value="<%=rs.getString("EMPLOYEECONTACTNO")%>" name="employeeContactNo"/><br/><br/>
<div class="panel-group" id="panelGrp">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#collapse1">Password</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse">
<div class="panel-body">Current Password :<br/>
<input type="text" class="form-control"/><br/>
New Password : <br/>
<input type="password" class="form-control" name="password"/><br/>
Confirm Password : <br/>
<input type="password" class="form-control" /><br/>
<input type="submit" value="Change Password" name="selection" class="btn btn-primary btn-lg btn-square" id="changepw"/>
</div>
</div>
</div>
</div>
<input type="submit" value="Update" id="changepw" name="selection" class="btn btn-primary btn-lg btn-square"/>
</form>
<%}%>
</div>
<div class="footer"></div>
</div>
</body>
</html>
<%if (request.getMethod().equals("POST")) {
if("Update".equals(request.getParameter("selection"))){
try{
employeeDA.updateEmployee(employee);
}catch(Exception ex){
ex.getMessage();
}
}else if("Change Password".equals(request.getParameter("selection"))){
try{
employeeDA.changePassword(username,request.getParameter("password"));
}catch(Exception ex){
ex.getMessage();
}
}
}
out.println(request.getParameter("accType"));
out.println(employee.getAccType());
%>
disabled elements in a form will not be submitted. You may have to use readonly.
I'm having a problem that when my JSP loads, it returns a blank page. The page is supposed to call the Controller with the parameter "btnListar" and call de DAO to list entries from the database. I debugged the code (I'm using NetBeans to build this app), and the values are being passed correctly, the variables are filled with entries from the DB that the DAO gets, but the page the browser is supposed to show just doesn't appear, it's blank.
My Controller:
public class ExperienciaControle extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String action = request.getParameter("action");
switch (action) {
case "btnCadastrar": {
Experiencia exp = new Experiencia();
exp.setEmpresa(request.getParameter("txtEmpresa"));
exp.setCargo(request.getParameter("txtCargo"));
exp.setData(request.getParameter("txtData"));
exp.setAtribuicoes(request.getParameter("txtAtrib"));
ExperienciaDAO dao = new ExperienciaDAO();
dao.insertExp(exp);
break;
}
case "btnAtualizar": {
Experiencia exp = new Experiencia();
exp.setEmpresa(request.getParameter("txtEmpresa"));
exp.setCargo(request.getParameter("txtCargo"));
exp.setData(request.getParameter("txtData"));
exp.setAtribuicoes(request.getParameter("txtAtrib"));
ExperienciaDAO dao = new ExperienciaDAO();
dao.updateExp(exp);
break;
}
case "btnRemover": {
Experiencia exp = new Experiencia();
exp.setId(Integer.parseInt(request.getParameter("chckId")));
ExperienciaDAO dao = new ExperienciaDAO();
dao.deleteExp(exp);
break;
}
case "btnListar": {
ExperienciaDAO dao = new ExperienciaDAO();
ArrayList<Experiencia> expArray = dao.selectExp();
request.setAttribute("expArray", expArray);
break;
}
default:
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#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";
}
}
My JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# page import="java.util.*" %>
<%# page import="Modelo.*" %>
<!DOCTYPE html>
<html>
<head>
<script src="../js/dropdown.js"></script>
<script src="../js/jquery-1.12.3.min.js"></script>
<script src="../js/lista.js"></script>
<link type="text/css" rel="stylesheet" href="../css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="../css/admin.css" />
<link type="text/css" rel="stylesheet" href="../css/dropdown.css" />
<link type="text/css" rel="stylesheet" href="../css/body.css" />
<link type="text/css" rel="stylesheet" href="../css/main.css" />
<link type="text/css" rel="stylesheet" href="../css/fonts.css" />
<title>Currículo | Administração</title>
</head>
<body>
<div class="body">
<div>
<nav id="primary_nav_wrap">
<ul>
<li class="current-menu-item">Home</li>
<li><a>Experiência</a>
<ul>
<li>Adicionar</li>
<li>Listar</li>
</ul>
</li>
<li><a>Educação</a>
<ul>
<li>Adicionar</li>
<li>Atualizar</li>
<li>Remover</li>
</ul>
</li>
<li><a>Habilidade</a>
<ul>
<li>Adicionar</li>
<li>Atualizar</li>
<li>Remover</li>
</ul>
</li>
</ul>
</nav>
</div>
<div id="divAddExp" style="display:none" class="cadastros">
<form name="frmExp" action="../ExperienciaControle" method="POST">
<h1 style="font-family: Roboto">Cadastro de Experiência</h1><br />
<label for="lblEmpresa">Empresa </label><input type="text" name="txtEmpresa" class="form-control" /><br />
<label for="lblCargo">Cargo </label><input type="text" name="txtCargo" class="form-control" /><br />
<label for="lblData">Data </label><input type="text" name="txtData" class="form-control" /><br />
<label for="lblAtrib">Atribuições </label><textarea rows="4" cols="50" name="txtAtrib" class="form-control"></textarea><br />
<input class="btn" type="submit" name="btnCadastrar" value="Cadastrar" />
</form>
</div>
<div id="divUpdExp" class="cadastros">
<form name="frmExp" action="/ExperienciaControle" method="GET">
<h1 style="font-family: Roboto">Listagem de Experiência</h1><br />
<table>
<thead>
<tr>
<th> </th>
<th>ID</th>
<th>Empresa</th>
<th>Cargo</th>
</tr>
</thead>
<%
request.getRequestDispatcher("/ExperienciaControle?action=btnListar").forward(request, response);
ArrayList<Experiencia> expArray = (ArrayList<Experiencia>) request.getAttribute("expArray");
for (Experiencia exp : expArray) {
%>
<tr>
<td><input type="checkbox" name="chckID" value="<%= exp.getId()%>" /></td>
<td><%= exp.getId()%></td>
<td><%= exp.getEmpresa()%></td>
<td><%= exp.getCargo()%></td>
</tr>
<%
}
%>
</table>
<span><input class="btn" type="submit" name="btnListar" value="Listar" /></span>
<span><input class="btn" type="submit" name="btnAtualizar" value="Atualizar" /></span>
<span><input class="btn" type="submit" name="btnRemover" value="Remover" /></span>
</form>
</div>
</div>
</body>
</html>
If I remove the Java code from the JSP and turn it into a pure HTML page, it works perfectly, the page comes up without any problems. Tomcat (and Glassfish) log shows no error messages, which makes things even harder. :(
What am I doing wrong here? Why am I getting a blank page?
COMPLETE CODE: http://gitlab.creationkit.com.br/thales/Curriculum
In my web application, I have a home page where the options available to the user are placed in a fixed sidebar in the top of the screen, and each one of this options are opened inside of a tag <div> in this same page.
My problem is: when this content is a form, and I submit it to the server, after the processing, the output page isn't opened in this <div>, but in the entire navigation space. What I want is a way of capture this return and display it in the same <div> it was originated.
the code for my home page is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<title>HorarioLivre</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="navbar-fixed-top.css" rel="stylesheet">
<!-- Just for debugging purposes. Don't actually copy this line! -->
<!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]-->
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body onload="close_page()">
<!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HorarioLivre</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>Evento</li>
<li>Lista Horarios</li>
<li>Cadastra Horarios</li>
<li>Usuarios</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
${usuario.nome} <b class="caret"></b>
<ul class="dropdown-menu">
<li>Perfil</li>
<li>Configurações</li>
<li>Sair</li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<div class="container">
<div class="page-header">
<h1></h1>
</div>
<div class="panel panel-default" id="results">
<div class="panel-heading">
<div align="right"><button type="button" class="btn btn-lg btn-danger" onclick="close_page()">Fechar</button></div>
</div>
<div class="panel-body" id="content">
Panel content
</div>
</div>
</div> <!-- /container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function load_page(url){
$('#results').css("display", "block");
$('#content').load(url);
$('#container').draggable();
}
function close_page(){
$('#results').css("display", "none");
$('#content').empty();
}
</script>
</body>
</html>
I am using Spring, and the pages linked here are handled by Controller. By example,the page "cadastra_evento.html" is:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Lista de Eventos</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="alert alert-info">
<strong>Eventos</strong> Segue a lista de eventos cadastrados.
</div>
<div class="container">
<div class="row">
<div class="col-md-3">Nome</div>
<div class="col-md-3">Descrição</div>
<div class="col-md-3">Periodo</div>
<div class="col-md-3">Duração</div>
</div>
<c:forEach var="item" items="${lista}">
<div class="row">
<div class="col-md-3"><c:out value="${item.nome}"/></div>
<div class="col-md-3"><c:out value="${item.descricao}"/></div>
<div class="col-md-3"><c:out value="${item.data_inicial}"/> - <c:out value="${item.data_final}"/></div>
<div class="col-md-3"><c:out value="${item.duracao}"/></div>
</div>
</c:forEach>
</div>
<div class="alert alert-info">
<strong>Novo</strong> Cadastre um novo evento.
</div>
<form method="post" action="cad_evento.html">
<input type="text" name="nome" placeholder="Nome" size=20 maxlength=40> <br/>
<input type="text" name="descricao" placeholder="Descrição" size=30 maxlength=100> <br/>
<h3>Periodo da Data</h3>
inicio: <input name="data_inicial" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
final: <input name="data_final" placeholder="DD-MM-AAAA" required pattern="\d{2}-\d{2}-\d{4}" /> <br/>
<h3>Periodo do Horário</h3>
inicio: <input name="hora_inicial" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
final: <input name="hora_final" placeholder="HH:MM:SS" required pattern="\d{2}:\d{2}:\d{2}" /> <br/>
<input type="text" name="duracao" placeholder="duração" size=20 maxlength=2> <br/>
<button type="submit" class="btn btn-lg btn-primary">Cadastrar</button>
</form>
</body>
</html>
To finish, the page "cad_evento.html" used as action for the form above, is handled by method of same name from Controller:
#RequestMapping(value="/cad_evento", method=RequestMethod.POST)
public ModelAndView cadastra_evento(#RequestParam("nome") String nome, #RequestParam("descricao") String descricao, #RequestParam("data_inicial") String data_inicial, #RequestParam("hora_inicial") String hora_inicial, #RequestParam("data_final") String data_final, #RequestParam("hora_final") String hora_final, #RequestParam("duracao") int duracao) {
if(sessao != null)
{
if(sessao.getUsuario().temAutorizacao("cad_evento"))
{
Date d_inicio = new Date(Date.parse(data_inicial));
Date d_final = new Date(Date.parse(data_final));
Time h_inicio = new Time(Time.parse(hora_inicial));
Time h_final = new Time(Time.parse(hora_final));
EventoDAO evento = new EventoDAO(nome, descricao, d_inicio, d_final, h_inicio, h_final, duracao, sessao.getUsuario());
int saida = evento.cadastra();
if(saida == 0)
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Erro ao cadastrar o evento");
return mav;
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/listagem_evento");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.addObject("message", "Usuário sem permissão de acesso");
return mav;
}
}
else
{
ModelAndView mav = new ModelAndView();
mav.setViewName("/usuario_login_page");
return mav;
}
}
Someone have any thoughts about how to do that?
Well, spring mvc just open new page with a content you set in ModelAndView. If you want to load somthing just in some part of page ( in this case ) there pure javascript / jquery ajax is needed. So steps needed here:
Add javascript which will do ajax request to controller
Controller need to return JSON ( #ResponseBody can help you )
You have to do some DOM manipulation using javascript/jquery to put JSON answer to your div.