Confusion with Remember username codes(javascript)? - java

I started learning javascript and i have a question with a webpage that i created. The webpage is a login page that shows some tableau reports when logged in. I need to create a remember me checkbox just like any other website like gmail or salesforce. I have copy pasted the codes below.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%
ServletContext context = getServletContext();
String app = context.getInitParameter("appName");
String errorMessage = "";
if ( session.getAttribute("error-message")!=null){
errorMessage = (String) session.getAttribute("error-message");
}
%>
<!DOCTYPE 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, maximum-scale=1">
<title><%=app%> - Please login</title>
<link href="styles/bootstrap-theme.min.css" rel="stylesheet">
<link href="styles/bootstrap.min.css" rel="stylesheet">
<link href="styles/sidebars.css" rel="stylesheet">
<link rel="shortcut icon" href="img/favicon.ico">
<style type='text/css' media='screen'>
body {
font-family: Tahoma;
font-size: 12px !important;
padding-top: 40px;
padding-bottom: 40px;
background-color: #fff;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.navbar{
border-color: #ccc;
}
.alert-warning{
margin-top: 15px;
}
.validation-summary-errors{
font-family: Tahoma !important;
font-size: 12px !important;
color: #b94a48;
margin-top: 35px;
margin-bottom: -15px;
}
.col-md-8{
padding-left: 5px;
}
/* .navbar-inverse{
border-color: #ccc;
background: #ddf0f8; Old browsers
background: -moz-linear-gradient(top, #ddf0f8 0%, #ffffff 63%); FF3.6+
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ddf0f8), color-stop(63%,#ffffff)); Chrome,Safari4+
background: -webkit-linear-gradient(top, #ddf0f8 0%,#ffffff 63%); Chrome10+,Safari5.1+
background: -o-linear-gradient(top, #ddf0f8 0%,#ffffff 63%); Opera 11.10+
background: -ms-linear-gradient(top, #ddf0f8 0%,#ffffff 63%); IE10+
background: linear-gradient(to bottom, #ddf0f8 0%,#ffffff 63%); W3C
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ddf0f8', endColorstr='#ffffff',GradientType=0 ); IE6-9
}*/
</style>
</head>
<body>
<div class="navbar navbar-fixed-top" role="navigation">
<div class="navbar-header">
<img class="logo" src="img/Nexius_logo.png"/>
</div>
</div>
<div class='inner col-md-8'>
<%=errorMessage%>
<form action='LoginServlet' method='POST' id='loginForm' class='form-horizontal' role='form' autocomplete='off'>
<h4 class="form-signin-heading"> </h4>
<div class="form-group">
<label for='username' class='col-md-2 control-label'>User name</label>
<div class="col-md-4">
<input type='text' class="form-control" name='user' id='username' />
</div>
</div>
<div class="form-group">
<label for='password' class='col-md-2 control-label'>Password</label>
<div class="col-md-4">
<input type='password' class="form-control" name='pwd' id='password' />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button class="btn btn-default" type="submit">Login</button>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10"><div style="position: absolute; top: -45px; left: 100px; width: 240px;">
<input onClick="checkCookie()" type="checkbox" value="Remember me">Remember username<br>
</div>
</div>
</form>
</div>
<script type='text/javascript'>
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)===0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie()
{
var user=getCookie("user");
if (user!=="")
{
document.getElementById("username").value = user;
}
else
{
if (user!=="" && user!=null)
{
setCookie("user",user,30);
}
}
}
</script>
</body>
</html>
Mostly the upper part is just CSS. In the below part i have writtten the codes to get the username on the text box and pass it to the setcookie function below. So i need it like an usual page like when remember username check box was checked, the username should show up when the page is opened, but for me what it does is, when i open the webpage only when i click on the "remember username" checkbox the username pops up in the username textbox. Now sure what to do about this? Can someone please help me?

You're checking for cookies only when user clicks on the remember me button. You need to check for cookie on document load, for instance.
Add onload handler on body tag this way: <body onload=checkCookie()>. You need to also remove onClick="checkCookie()" from your remember me button.

Related

Spring Adding Cookies

I am trying to create a shopping cart using cookies in spring boot but the cookie is not being added/displayed. Below are the controller mappings and page htmls, can you let me know what I'm doing wrong?
Screenshots of pages :
Controller Mappings:
#GetMapping("/products/addToCart/{id}")
private String addToCart(#PathVariable("id") long productId, HttpServletResponse response) {
try {
Cookie browserSessionCookie = new Cookie(Long.toString(productId), Long.toString(1L));
response.addCookie(browserSessionCookie);
return "redirect:/products/cart";
} catch (Exception e) {
logger.error(e.getMessage());
return "fail";
}
}
#GetMapping("/products/cart")
public String showCookies(HttpServletRequest request, Model model) {
Cookie[] cookies = request.getCookies();
model.addAttribute("cookies",cookies);
return "/cart";
}
Thymeleaf Page For Products List:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>All Products</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
table, th, td {
border: 1px solid black;
}
td {
padding: 20px;
}
.topnav {
background-color: #A32638;
overflow: hidden;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #FCB514;
color: white;
}
</style>
</head>
<body>
<div class="topnav">
<a th:href="#{/}">Home</a>
<a class="active" th:href="#{/productsList}">Products</a>
<a th:href="#{/products/cart}">Cart</a>
</div>
<br>
Products
<br>
<br>
<div th:if="${ not#lists.isEmpty(products)}">
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Action</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.name}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.category.name}"></td>
<td>
<a th:href="#{/products/details/{id}(id=${product.id})}">Details</a>
<a th:href="#{/products/addToCart/{id}(id=${product.id})}">Add To Cart</a>
</td>
</tr>
</table>
<br>
</div>
</body>
</html>
Thmeleaf Page For Showing Cookies :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br>
<h1>Show cookies</h1>
<dl th:each="cookie : ${cookies}">
<dt th:text="${cookie.getName()}"></dt>
<dd th:text="${cookie.getValue()}"></dd>
</dl>
<h1>Session Data</h1>
<dl th:each="elem : ${sessionElems}">
<dt th:text="${elem.getName()}"></dt>
<dd th:text="${elem.getValue()}"></dd>
</dl>
</body>
</html>
Thank you.
The solution was to set the path of the created cookie to the path of the cart page as below :
browserSessionCookie.setPath("/products/cart");
Thanks for the responses!

Trouble authenticating with Java through HTMLUnit. Debugging issues

I am having trouble authenticating with HTMLUnit on a webpage. I enter a username and password, and then click sign in, then check the title of the page, and it is still the sign in page. SO I am not signed in properly.
What is going wrong here? I'm trying to use Fiddler and Charles for debugging but I don't see my requests show up there. Does this Java code make sense for authentication with the given website? Any debugging tips?
Please help me! Thank you.
My code:
package com.company;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.CookieManager;
public class Main {
static WebClient webClient;
static CookieManager cookieManager;
static String username = "MyUsername";
static String password = "MyPassword";
#Before
public static void init() throws Exception {
webClient = new WebClient();
cookieManager = new CookieManager();
cookieManager = webClient.getCookieManager();
cookieManager.setCookiesEnabled(true);
webClient.getOptions().setTimeout(90000);
webClient.setJavaScriptTimeout(90000);
}
#After
public static void close() throws Exception {
webClient.close();
cookieManager.clearCookies();
}
public static void signIn() throws Exception {
//Acquire location for URI, password, username, submitbutton
HtmlPage page1 = webClient.getPage("https://h3c.mlspin.com/signin.asp#ath");
HtmlForm form = page1.getFormByName("loginform");
HtmlTextInput uName = form.getInputByName("user_name");
HtmlPasswordInput passWord = form.getInputByName("pass");
HtmlButton button = form.getFirstByXPath("//*[#id=\"loginForm\"]/table/tbody/tr[7]/td/button");
uName.setValueAttribute(username);
passWord.setValueAttribute(password);
HtmlPage page2 = button.click();
System.out.println("HTMLUNIT UserText : \n" + uName.getText());
System.out.println("HTMLUNIT PassText : \n" + passWord.getText());
System.out.println("Results p2 " + page2.getTitleText());
System.out.println("Results p2 " + page2.getPage());
}
#Test
public static void givenAClient_gatherInfo() throws Exception {
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setRedirectEnabled(true);
webClient.getCache().setMaxSize(0);
}
public static void main(String[] args) throws Exception {
init();
givenAClient_gatherInfo();
signIn();
close();
}
}
<!-- Latest compiled and minified CSS -->
<LINK href="/css/Signin.css" type=text/css rel=stylesheet>
<script language='javascript'>
window.sessionStorage.clear();
</script>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,
shrink-to-fit=no">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<meta http-equiv="expires" content="0">
<title>pinergy - Sign In</title>
<link href="/style.asp" type="text/css" rel="stylesheet">
<script type="text/javascript" src="/shared/scripts/3rdParty/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/shared/scripts/3rdParty/bootstrap-4.1.1/bootstrap.min.js"></script>
<script type="text/javascript" src="/shared/scripts/cookieConsent.js?v=2"></script>
<script language="JavaScript">
var ath;
ath = {}
;
var isMobile = function() {
return /(iphone|ipod|(android.*mobile)|blackberry|windows ce|palm|symbian|nexus 7|xoom|windows phone)/i.test(navigator.userAgent);
}
;
var isIPad = function() {
return /(ipad)/i.test(navigator.userAgent);
}
function CheckSavePassword() {
if (document.loginform.SavePassword.checked) {
document.loginform.SavePassword.checked = false;
} else {
document.loginform.SavePassword.checked = true;
}
}
function parseQueryString(queryString) {
var QueryString = {};
queryString = queryString.slice(queryString.indexOf("?") + 1);
var qsArray = queryString.split("&");
for (var i = 0; i < qsArray.length; i++) {
var arr = qsArray[i].split("=");
QueryString[arr[0]] = arr[1];
}
return QueryString;
}
if (window != top) {
top.location.href = location.href;
}
</script>
<style>
body {
padding: 0;
}
INPUT.login {
height: 22px;
border: 1px solid #808080;
padding: 2px 4px;
background-image: url('images/bg_input.gif');
}
.mobile {
padding: 6px;
align-content: center;
align-self: center;
width: 90%;
height: auto;
display: none;
text-align: center;
border: 4px solid #E7E7E7;
border-radius: 15px;
color: #444;
margin: auto;
background: -moz-linear-gradient(top, #FFFFFF, #E7E7E7);
background: -ms-linear-gradient(#FFFFFF, #E7E7E7);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#E7E7E7));
max-width: 25rem;
}
.mobileButton {
font-weight: bold;
border-top: 1px outset grey;
border-left: 1px outset grey;
-moz-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
border-radius: 10px 10px 10px 10px;
-webkit-appearance: none;
-moz-appearance: none;
min-height: 2rem;
/*width:90px;
height:54px;
font-family:Arial;
font-size:x-large;*/
}
.yes {
background-color: #FBAF41;
}
.no {
background-color: #BEBEBE;
}
.mobileCheckTable {
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif !important;
}
.mobileCheckTable td {
vertical-align: top;
}
.textContent {
font-size: .9rem;
text-align: center;
font-weight: 500;
}
.textContent1Child {
white-space: nowrap;
padding-left: .5rem;
}
.mobilecheck {
height: 1.2rem;
width: 1.2rem;
vertical-align: top;
padding: 0;
border: 1px solid rgba(0, 0, 0, 0.3);
}
.mobilequest {
margin: 0 auto;
max-width: 20rem;
box-sizing: border-box;
float: left;
padding-left: .5rem;
padding-bottom: .5rem;
}
div#remember {
font-size: 0.88rem;
}
.mls-bootstrap-font {
font-size: 1rem;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif;
}
.sm-remember {
display: none;
}
#media only screen and (min-width: 476px) {
.mobile {
padding: 15px;
}
.sm-remember {
display: initial;
}
.mobilequest {
padding-bottom: 1rem;
}
.mobilequest,
.textContent1Child {
padding-left: 1rem;
}
}
#media only screen and (min-width: 768px) {
.mobilequest.textContent {
font-size: 1.5rem !important;
}
.textContent1Child {
font-size: 1.2rem !important;
}
}
#media only screen and (min-width: 1024px) {
.mobilequest.textContent {
font-size: 1.6rem !important;
}
.textContent1Child {
font-size: 1.2rem !important;
}
}
</style>
<link rel="icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
<link rel="shortcut icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="css/addtohomescreen.css">
<script src="Scripts/addtohomescreen.js"></script>
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-120x120.png" type="image/x-
icon" sizes="120x120" />
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-152x152.png" type="image/x-
icon" sizes="152x152" />
<link rel="shortcut icon" href="images/apple-touch-icon-152x152.png" type="image/x-icon" sizes="152x152" />
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-57x57.png" type="image/x-
icon" sizes="57x57" />
</head>
<body marginheight="0" marginwidth="0" topmargin="0" leftmargin="0">
<table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="100%" height="100%">
<form name="loginform" id="loginForm" method="POST" action="signin.asp" style="margin:
0px" onsubmit="return signInFn.loginFormOnSubmit();
">
<input name="cxzvvfbvvalideguaueff" value="DT: 8/16/2020 8:18:40 PM" type="hidden"><input name="Page_Loaded" value="DT: 8/16/2020 9:25:16 PM" type="hidden">
<table border="0" cellspacing="0" cellpadding="0" class="mls-login">
<tr>
<td><img src="images/MLSPIN_Logo.jpg" width="240" height="60" /></td>
</tr>
<tr>
<td class="text-left pl-4"><span class="h4">Sign In to</span><img src="images/pinergy-logo.jpg" width="90" height="30" /></td>
</tr>
<tr>
<td class="pl-2"><input class="form-control" type="text" style="width: 220px;" name="user_name" maxlength="8" value="MyUsername" placeholder="Enter Your Agent ID"></td>
</tr>
<tr>
<td class="pl-2"><input class="form-control" type="password" style="width: 220px" name="pass" maxlength="20" placeholder="Password"></td>
</tr>
<tr>
<td class="text-left pl-2">Forgot your password?</td>
</tr>
<tr>
<td class="text-left pl-2 mls-login-rem-me"><input type="checkbox" name="SavePassword" value="Y"><span onclick="CheckSavePassword();">Remember My Password</span></td>
</tr>
<tr>
<td><button class="btn btn-sm btn-primary" type="submit">Sign In</button>
<!--<input class="btn btn-sm btn-primary" type="submit" value="Sign In" name="signin"></td>--></tr>
</table>
</form>
</td>
</tr>
<tr>
<td>
<footer class="mls-site-footer">
<div class="footer-content">
<div class="footer-icon MLSPINlogo mr-1"></div>
<div class="mb-1">©
<span>MLS Property Information Network,
Inc.</span></div>
<div class="vert-bar">|</div>
<div>900 Hartford Turnpike, fakeville, TN 01245 </div>
<div class="vert-bar">|</div>
<div>800-700-3189 </div>
<div class="vert-bar">|</div>
<div class="footer-content-group">
<div class="d-inline">Access Notice</div>
<div class="vert-bar d-inline">|</div>
<div class="d-inline">Privacy Policy</div>
<div class="vert-bar d-inline">|</div>
<div class="d-inline">Copyright Policy</div>
</div>
<div class="vert-bar">|</div>
<div class="footer-user-count">2190 users online right now!</div>
</div>
</footer>
</td>
</tr>
</table>
<div id="cookieConsentBootstrapModal" class="modal mls-bootstrap-font" role="dialog" aria-labelledby="cookieConsentTitle" aria-describedby="cookieConsentDesc" aria-hidden="true" data-backdrop="static" tabindex="-1">
<div class="modal-dialog" role="document">
<!-- Modal content-->
<div class="modal-content mls-modal-bgcolor">
<div class="modal-header">
<h1 class="modal-title h5" id="cookieConsentTitle">This website uses cookies</h1>
</div>
<div class="modal-body" id="cookieConsentDesc">This website uses cookies for a number of purposes, including to enhance your browsing experience. Learn more about our use of cookies in our Privacy Policy. </div>
<div class="modal-footer"><button type="button" class="btn btn-sm btn-primary mls-js-cookie-consent-action" data-dismiss="modal">OK</button></div>
</div>
</div>
</div>
<script language="JavaScript">
document.loginform.user_name.focus();
alert("Incorrect password!\nPlease try again.");
</script>
<script>
if (!window.location.hash.match('ath')) {
addToHome = addToHomescreen({
detectHomescreen: true,
autostart: false,
icon: true,
lifespan: 15,
maxDisplayCount: 1,
appID: 'com.mlspin.MobileWeb'
});
addToHome.show();
window.location.hash = '#ath';
}
</script>
<script type="text/javascript">
var signInFn = (function() {
var _suppressCookieConsent = false;
function _loginFormOnSubmit() {
var isValid = true;
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
isValid = false;
cookieConsentUtil.showCookieBanner();
}
_enableDisableLoginForm();
return isValid;
}
function _enableDisableLoginForm() {
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
document.getElementById("loginForm").action = "signin.asp";
} else {
document.getElementById("loginForm").action = "validate_new.asp";
}
}
function _focusOnFirstElement() {
try {
var focusable = $('button:visible, a[href]:visible, input:visible, select:visible, textarea:visible, [tabindex]:visible:not([tabindex="-1"])');
if (focusable.length > 0) {
var firstFocusable = focusable[0];
firstFocusable.focus();
}
} catch (ex) {}
}
function _docOnReady() {
//_focusOnFirstElement();
cookieConsentUtil.init({
onStoreCookieConsent: function() {
_enableDisableLoginForm();
setTimeout(_focusOnFirstElement, 0);
}
});
cookieConsentUtil.docOnReady();
_enableDisableLoginForm();
}
return {
loginFormOnSubmit: _loginFormOnSubmit,
docOnReady: _docOnReady
};
}
());
$(document).ready(function() {
signInFn.docOnReady();
}
);
</script>
</body>
</html>
Looking in the javascripts there's this section:
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
document.getElementById("loginForm").action="signin.asp";
}
else{
document.getElementById("loginForm").action="validate_new.asp";
}
Seems from looking at the http requests validate_new.asp is returning a 302 (redirect) to signin.asp. This might help locate the relevant requests.
I tried looking a bit deeper but I'd need to try running your code which I've not got time to do right now. If I find time I'll come back to this as it should be possible.

Converting jsp web app into hybrid app using phonegap

I have developed a web app, connected to an Arduino UNO sensor and relay switch.
On the webpage, when I touch a button, a relay switch turns on/off.
My plan was to convert this web app into smartphone app, using phonegap.
I searched on google and found out that
I need to seperate the 'java' resource from my jsp file, as the phonegap only perceive html, css, javascript.
Then, How can I separate these elements out of my coding? Just like the following:
<!-- Main page that shows a simple on/off control and
DHT11 sensor value -->
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%# page import="com.Test.domain.Relay" %>
<%
Relay relay = new Relay();
pageContext.setAttribute("relay", relay);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fan Control</title>
<link href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" rel="stylesheet" type="text/css"/>
<script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js" type="text/javascript"></script>
<style>
#footer{
height: 86px;
text-indent: -9999px;
background-image: url(Logo.png);
background-repeat: no-repeat;
background-size: 100% 100%;
margin: 0 0 0 0;
position: absolute;
bottom: 0;
}
#header{
height: 86px;
text-indent: -9999px;
background-image: url(headerImage.png);
background-repeat: no-repeat;
background-size: 100% 100%;
margin: 0 0 0 0;
}
#FanOn:onClick{
background: green;
}
</style>
<script>
$(document).ready(function(){
var timer = setInterval(function(){
$.get("http://192.168.0.54", function(data){
$("#temperatureValue").val(data);
});
$("#form1").attr("action","Processing.jsp");
$("#form1").submit();
}, 1000);
$("#FanOn").click(function(){
$("#fanState").val("1");
$("#form1").attr("action","Processing.jsp");
$("#form1").submit();
});
$("#FanOff").click(function(){
$("#fanState").val("0");
$("#form1").attr("action","Processing.jsp");
$("#form1").submit();
});
$("#LampOn").click(function(){
$("#lampState").val("1");
$("#form1").attr("action","Processing.jsp");
$("#form1").submit();
});
$("#LampOff").click(function(){
$("#lampState").val("0");
$("#form1").attr("action","Processing.jsp");
$("#form1").submit();
});
$("#footer").click(function(){
window.location.replace("http://www.samwooinc.net");
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header" id="header">
<h1>FAN Control Example</h1>
</div>
<div data-role="content">
<form method="GET" id="form1" action="" target="haha">
<div class="ui-field-contain">
<label for="temperatureValue">Current Temperature</label>
<input type="text" id="temperatureValue" name="temperatureValue" value="0" data-inline="true">
</div>
<label for="FanSwitch">FAN Control</label>
<div data-role="navbar" id="FanSwitch">
<ul>
<li>FanOn</li>
<li>FanOff</li>
</ul>
</div>
<label for="LampSwitch">LAMP Control</label>
<div data-role="navbar" id="LampSwitch">
<ul>
<li>LampOn</li>
<li>LampOff</li>
</ul>
</div>
<input type="hidden" id="fanState" name="fanState" value="998">
<input type="hidden" id="lampState" name="lampState" value="234">
</form>
</div>
<div data-role="footer" id="footer">
<h2>footer</h2>
</div>
</div>
<iframe name="haha">
</iframe>
</body>
</html>
So, for example, How can I separate the coding like this, out of the jsp file?:
<%# page import="com.Test.domain.Relay" %>
<%
Relay relay = new Relay();
pageContext.setAttribute("relay", relay);
%>

How to submit selected items only from jQuery-ui selectable to java spring controller

I have working controller and jsp with form which submits all elements of some list back to controller.
I would like to submit only selected items of jQuery-ui selectable to spring controller.
My .jsp looks like this:
<html>
<head>
...
<!-- jQuery rference -->
<script src="<c:url value="/resources/jquery-2.1.1.js" />"></script>
<!-- jQuery-ui reference -->
<script src="<c:url value="/resources/jquery-ui-1.11.2.custom/jquery-ui.js" />"></script>
<script>
$(function() {$("#selectable").selectable();});
</script>
</head>
<body>
...
<!-- context path -->
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<form:from action="${contextPath}/user/categories/delete" method="POST" modelAttribute="categoryList">
<input type="submit" value="Delete Selected" />
<ol id="selectable">
<c:forEach items="${categoryList.catList}" var="category" varStatus="status">
<li class="ui-widget-content" value="${category}">${category.name}</li>
<input type="hidden" name="catList[${status.index}].id" value="${category.id}" />
<input type="hidden" name="catList[${status.index}].name" value="${category.name}" />
</c:forEach>
</ol>
</form:form>
</body>
</html>
And here is controller:
#Controller
public class CategoriesController {
#Autowired
private CategoryDetailService categoryDetailService;
#RequestMapping("user/categories/delete")
public String deleteCategory(#ModelAttribute("categoryList") CategoryList categoryList) {
//do something
return "redirect:/user/categories";
}
Is there a way to submit only selected items back to controller?
After reading a lot about jQuery and JSTL best thing I came up with is adding jQuery function which clears unselected dom elements. I have used empty function, but .remove() also does the trick.
$(function() {
$("#categorySubmit").button().click(function(event) {
$(function() {
$("#selectable li:not(.ui-selected)", this).each(function() {
$(this).empty();
});
});
});
});
where "#categorySubmit" is id given to submit button with name "Delete category"
You have to be careful tough, because only elements with index greater than last selected element are removed, elements with lower index which are not selected have property values set to null (or 0), for both .empty() and .remove().
Add a hidden variable in Ui and append selected values to that hidden variable and in your controller read the value of hidden variable after submit.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Selectable - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
</style>
<script>
$(function() {
$( "#selectable" ).selectable({
selected: function() {
$( ".ui-selected", this ).each(function() {
var hdnValue = $('#hdnFieldName').val();
var selectedValue=$(this).text() ;
if(hdnValue!='') {
$('#hdnFieldName').val(hdnValue +','+selectedValue);
}
alert(hdnValue);
});
}
});
});
</script>
</head>
<body>
<form action="${contextPath}/user/categories/delete" method="POST" >
<input type="submit" value="Delete Selected" />
<ol id="selectable">
<li class="ui-widget-content">Item 1</li>
<li class="ui-widget-content">Item 2</li>
<li class="ui-widget-content">Item 3</li>
<li class="ui-widget-content">Item 4</li>
<li class="ui-widget-content">Item 5</li>
<li class="ui-widget-content">Item 6</li>
<li class="ui-widget-content">Item 7</li>
</ol>
<input type="hidden" id="hdnFieldName"/>
</form>
</body>
</html>

Primefaces & Twitter Bootstrap - Styling of a Bootstrap wizard

I am struggeling with a problem. My jsfiddle output is as I want it:
jsfiddle Output
However, my page looks differently, especially the Product styles:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="" />
<meta name="author" content="" />
<!-- Le styles -->
<link href="http://fuelcdn.com/fuelux-imh/2.2/css/fuelux.css"
rel="stylesheet" />
<link
href="http://fuelcdn.com/fuelux-imh/2.2/css/fuelux-responsive.css"
rel="stylesheet" />
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap-responsive.css" rel="stylesheet"
type="text/css" />
<style type="text/css">
body {
padding-bottom: 200px;
}
.pillbox {
border: 1px solid #bbb;
margin-bottom: 10px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
width: 251px;
}
.container>div,.container>table {
margin: 20px;
}
.tree {
width: 430px;
height: 350px;
}
.static-loader {
margin-left: 30px;
}
.step-content {
border: 1px solid #D4D4D4;
border-top: 0;
border-radius: 0 0 4px 4px;
padding: 10px;
margin-bottom: 10px;
}
</style>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons
<link rel="shortcut icon" href="../assets/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
-->
<h:outputScript name="js/require.js" />
<script>
//<![CDATA[
requirejs.config({
paths: {
'jquery': 'js/jquery',
'underscore': 'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min',
'bootstrap': 'js/bootstrap/js',
'fuelux': 'src'
}
});
require(['jquery', 'sample/data', 'sample/datasource', 'sample/datasourceTree', 'fuelux/all'], function ($, sampleData, StaticDataSource, DataSourceTree) {
// WIZARD
$('#MyWizard').on('change', function(e, data) {
console.log('change');
if(data.step===3 && data.direction==='next') {
// return e.preventDefault();
}
});
$('#MyWizard').on('changed', function(e, data) {
console.log('changed');
});
$('#MyWizard').on('finished', function(e, data) {
console.log('finished');
});
$('#btnWizardPrev').on('click', function() {
$('#MyWizard').wizard('previous');
});
$('#btnWizardNext').on('click', function() {
$('#MyWizard').wizard('next','foo');
});
$('#btnWizardStep').on('click', function() {
var item = $('#MyWizard').wizard('selectedItem');
console.log(item.step);
});
$('#MyWizard').on('stepclick', function(e, data) {
console.log('step' + data.step + ' clicked');
if(data.step===1) {
// return e.preventDefault();
}
});
});
//]]>
</script>
</h:head>
<h:body>
<!-- Content Area -->
<div class="well" style="margin-top: 50px;">
<div class="fuelux">
<div class="container">
<!-- WIZARD -->
<div>
<div id="MyWizard" class="wizard">
<ul class="steps">
<li data-target="#step1" class="active"><span
class="badge badge-info">1</span><span class="chevron"></span></li>
<li data-target="#step2"><span class="badge">2</span>Step 2<span
class="chevron"></span></li>
<li data-target="#step3"><span class="badge">3</span>Step 3<span
class="chevron"></span></li>
<li data-target="#step4"><span class="badge">4</span>Step 4<span
class="chevron"></span></li>
<li data-target="#step5"><span class="badge">5</span>Step 5<span
class="chevron"></span></li>
<li data-target="#step5"><span class="badge">5</span>Step 5<span
class="chevron"></span></li>
<li data-target="#step5"><span class="badge">5</span>Step 5<span
class="chevron"></span></li>
</ul>
<div class="actions">
<button class="btn btn-mini btn-prev">
<i class="icon-arrow-left"></i>Prev
</button>
<button class="btn btn-mini btn-next" data-last="Finish">
Next<i class="icon-arrow-right"></i>
</button>
</div>
</div>
<div class="step-content">
<div class="step-pane active" id="step1">
<legend>
<h3>Product</h3>
</legend>
<!-- Product Name-->
<div class="control-group">
<label class="control-label">Product Name</label>
<div class="controls">
<h:inputText name="Product Name" class="input-xlarge"
type="text" />
</div>
</div>
<!-- Categorie-->
<div class="control-group">
<label class="control-label">Categorie</label>
<div class="controls">
<h:inputText name="Product Name" class="input-xlarge"
placeholder="Insert Categorie" type="text" />
</div>
</div>
<!-- Textarea -->
<div class="control-group">
<label class="control-label">Description</label>
<div class="controls">
<div class="textarea">
<textarea rows="3"></textarea>
</div>
</div>
</div>
</div>
<div class="step-pane" id="step2">This is step 2</div>
<div class="step-pane" id="step3">This is step 3</div>
<div class="step-pane" id="step4">This is step 4</div>
<div class="step-pane" id="step5">This is step 5</div>
</div>
<!-- <h:button type="button" class="btn btn-mini" id="btnWizardPrev"
value="prev" />
<h:button type="button" class="btn btn-mini" id="btnWizardNext"
value="next" />
<h:button type="button" class="btn btn-mini" id="btnWizardStep"
value="current step" /> -->
</div>
</div>
</div>
</div>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<h:outputScript name="js/jquery-1.7.2.min.js" />
<h:outputScript name="js/bootstrap.min.js" />
<h:outputScript name="js/jquery.dataTables.min.js" />
<h:outputScript name="js/bootstrap.js" />
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"
type="text/javascript"></script>
<script src="http://fuelcdn.com/fuelux-imh/2.2/loader.min.js"
type="text/javascript"></script>
</h:body>
</html>
and it looks like that:
Therefore, there is no real bootstrap style in the product area. How would you fix that?
I really appreciate your answer!!!
UPDATE
I guess its because I use primefaces and jsf. However, at the moment I cannot locate the real problem...
It could be the oprder in which you are calling your style sheets. Values are getting superseded. Make this style sheet the last one you add
<link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
It works for me!
You have to download bootstrap folder and place js folder in %projectRoot% and the same for css and img folders.
after you have to delete h:outputScript name="js/jquery-1.7.2.min.js" and h:outputScript name="js/jquery.dataTables.min.js" .

Categories