Spring MVC how to load a js from a jsp - javascript

I work with Spring MVC. I have a dynamic web project Eclipse
Structure folder is
I have the following jsp actualizarCorreo.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html>
<html>
<head>
<title>EusurveyAdmin menu princiapl</title>
<script type="text/javascript" src="/resources/js/properties.js"></script>
<script type="text/javascript">
function pruebaB()
{
alert('en prueba');
}
</script>
</head>
<body>
<c:set var="pageNumber" value="${pageNumber}" />
<table class="actualizarCorreos">
<tbody>
<a href="#" onclick="prueba()"; return false;">
<input type="radio" onclick="prueba()" class="check" id="id1"
name="id1" value="true" />
<spring:message code="label.ModificarCorreos" />
</tbody>
</table>
</body>
In this jsp I load another js
<script type="text/javascript" src="/resources/js/properties.js">
This js is the path WebContent/resources/js.
properties.js is
alert('cargado properties');
function checkConfirmationPage()
{
alert('en check');
if ($("#conflink").is(":checked"))
{} else {};
}
function prueba()
{
alert('en prueba');
}
I call function prueba from actualizarCorreo.jsp when a radio button is clicked
<input type="radio" onclick="prueba()" class="check" id="id1"
name="id1" value="true" />
<spring:message code="label.ModificarCorreos" />
I don't see the alert message function prueba.
What is it wrong?

Try this
<script type="text/javascript" src="../resources/js/properties.js"></script>
or use the below as reference and find the exact path:
/ = Root directory
. = This location
.. = Up a directory
./ = Current directory
../ = Parent of current directory
../../ = Two directories backwards
Or directly get the context path to fetch the .js
<script type="text/javascript" src="<%=request.getContextPath()%>/resources/js/properties.js" >
</script>

While using Spring framework in mvc you have to provide resources path as below in your dispatcher-servlet.xml.
< mvc:resources mapping="/resources/**" location="/resources/" />
And then that folder will be allowed for resources. You can call them as
< script type="text/javascript" src="../../resources/js/properties.js" >
</ script>

Related

jstl not executeing within jsp file loaded using jquery load()

i have partial jsp file with jstl code :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form method="POST" action="EntrerClient" id="submitparticulier"
class=submitparticulier">
<fieldset>
<input type="hidden" id="Id" name="idform" value="inscp">
<select name="genre" class="genre">
<option>Monsieur</option>
<option>Melle/Madame</option>
</select>
</br>
<label for="etat">Nom <span class="requis">*</span></label></br>
<input type="text" id="nom" name="nom" value="<c:out
value="${particulier.getNom()}"/>" size="20" maxlength="60" />
<span class="erreur">${form.erreurs['nom']}</span>
<br />
<p class="${empty form.erreurs ? 'succes' :
'erreur'}">${form.resultat}</p>
<br />
<p id="adcli"><a href='#ADCLI'>Valider</a></p>
</fieldset>
</form>
and principal jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1
/jquery.min.js"></script>
<script src="ressources/_javasctipt.js"></script>
<script type="text/javascript">
constructform("<c:out value="${param['par']}"/>");
</script>
...
the partial file is loaded using jquery :
...
function constructform(param) {
var principal = $("#Gc_FenettrePrincipale");
principal.empty();
principal.append("<div class=\"Gc_FenettreSec\" id=\"_ADD\"><p>Ajout
Clients</p></div>");
principal.append("<div style=\"width:700px;padding:20px;S\">");
principal.append("<div id=\"ajout_client\" class=\"ajout_client\">");
principal.append("</div></div>");
var add=$("#add");
add.removeClass('current');
$("#adcli").addClass('current');
$('#ajout_client.div').remove();
var form_particulier=$("<div/>");
form_particulier.load("ressources/PaletParticulier.jsp");
//form_particulier.html();
var formul = $("#ajout_client");
formul.append("<select name=\"type\" class=\"type
\"><option>Particulier</option><option>Organisme</option></select>");
formul.append(form_particulier);
} ...
the
<input type="text" id="nom" name="nom" value="<c:out
value="${particulier.getNom()}"/>"
servlet call
...
request.setAttribute(ATT_FORM,form);
request.setAttribute(ATT_PARTICULIER,particulier);
response.setContentType("text/html");
this.getServletContext().getRequestDispatcher(VUE).forward(request,
response);
in the partial jsp does not work but it work in the principal jsp if used,i can't figure why
in the java channel in the irc thy suggeced to go to jsf,i can't to that now,am off of deley
Idea 1: If your JavaScript function constructform is in /ressources/_javasctipt.js, then the load request might look for /ressources/ressources/partial.jsp due to the relative URL.
Idea 2: Have you tried omitting the <!DOCTYPE html> in your partial JSP?
i figured out that load() function is http resquet,GET or POST ,and am using servlet to load jsp,so the soution is to create the hol jsp.
i don't see better solution
"an other servlet or an other jsp"

Not getting value in <c:set var from scriptlet variable

I am defining a variable in scriptlet to get value from request headers, then we are using that variable c:set to set to variable to use in c:out .But i am not getting any value c:set variable, as a result c:out is giving result as ''.
please find the code snippet below and guide me if i am missing anything.
Code in jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=ISO-8859-1">
<title>DM</title>
<SCRIPT Language="JavaScript">
function submitform()
{
this.LoginForm.submit();
}
</SCRIPT>
</head>
<body onload="submitform()">
<%
String userName= request.getHeader("IV-USER");
System.out.println("name "+userName);
if (userName == null || userName.length()==0){
response.setHeader("IV-USER",userName);
response.sendRedirect("ULM.jsp");
}
%>
<c:set var="uName" value="<%=userName%>"/>
<p>Welcome1 ${uName}</p>
<form name="LoginForm" action="/ICDDMContent/STGDM.html" method="post">
<input type="hidden" name="UserId" value='<c:out value="${uName}"/>'/>
<!--
<input type="hidden" name="UserId" value="<%=userName%>" >
-->
<input type="hidden" name="Token" value="dummy">
<p>Welcome1 <c:out value="${uName}"/></p>
</form>
</body>
</html>
String userName= request.getHeader("IV-USER");
System.out.println("name "+userName);
if (userName == null || userName.length()==0){
response.setHeader("IV-USER",userName);
response.sendRedirect("ULM.jsp");
}
Is redundant piece of code, if userName is empty, you will just assign empty value to IV-USER header, if "ULM.jsp" is the same page as you've attached, and that redirect is just to set variable - here is your problem

Uncaught Error: [$injector:nomod] and Uncaught Error: [$injector:modulerr]

I am trying to setup a simple SP app with angularjs, bootstrand and ui bootstrap, the code is copy paste from the Alert Directive example on the UI bootstrap (intention was to test if at least a simple thing work) but its not.
MY SP Page code:
<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
<%# Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
<%# Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%# Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<meta name="WebPartPageExpansion" content="full" />
<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="../Scripts/bootstrap.js"></script>
<script src="../Scripts/angular-ui/ui-bootstrap-tpls.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>
<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
AngularJS - Sharepoint List CRUD Sample
</asp:Content>
<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div class="container" ng-app="ui.bootstrap.demo">
<div ng-controller="AlertDemoCtrl">
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="closeAlert($index)">{{alert.msg}}</alert>
<button class='btn btn-default' ng-click="addAlert()">Add Alert</button>
</div>
</div>
</asp:Content>
My app.js
'use strict';
angular.module('ui.bootstrap.demo').controller('AlertDemoCtrl', function ($scope) {
$scope.alerts = [
{ type: 'danger', msg: 'Oh snap! Change a few things up and try submitting again.' },
{ type: 'success', msg: 'Well done! You successfully read this important alert message.' }
];
$scope.addAlert = function () {
$scope.alerts.push({ msg: 'Another alert!' });
};
$scope.closeAlert = function (index) {
$scope.alerts.splice(index, 1);
};
});
I get the 2 errors in the title
I suppose something messed up in the order of the js files?
change the module definition to
angular.module('ui.bootstrap.demo', [ui.bootstrap]).....
you need to add ui.bootstrap as a dependency

need to check/uncheck checkbox on page load depending on variable passed from controller in jsp

I am passing a variable to my jsp. If the variable is 1, I need to check a check box on page load. If it is 2, the checkbox will be unchecked on load. By default, the check box is unchecked.
I am using Spring MVC. Please suggest how can i do it using javascript/jquery.
Thanks.
Assuming the conditional variable is in form say yourForm, you can
set the check box in javascript and jsp as:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<script type="text/javascript" language="JavaScript">
function loadOnValues(){
var conditionalVariable = '<c:out value="${yourForm.conditionalVariable}"/>';
if(conditionalVariable == null || conditionalVariable == '2'){
document.getElementById("boxId").checked = false;
} else {
document.getElementById("boxId").checked = true;
}
}
</script>
</head>
<title>Jsp Title</title>
<body onload="javascript:loadOnValues();">
<form:form id="yourForm" modelAttribute="yourForm" method="post">
<tr>
<td>
<form:checkbox id="boxId" path="checkBoxName"> CheckBox Text
</td>
</tr>
</form:form>
</body>
</html>

Error invoking Javascript function from .ascx file

I migrated a VS 2003 app to VS 2010.
The application has side_menu.ascx which is referenced in default.aspx.
in side_menu.ascx, a javascript function menu is invoked which is present in side_menu.js.
However, when the function menu is invoked, it gives an error during runtime - 'Cannot find function menu' This works fine in VS 2003
This is where I am getting this error - this code is in side_menu.ascx
new menu (SIDE_MENU_ITEMS, SIDE_MENU_POS, SIDE_MENU_STYLES)
This is the code in default.aspx
<!-- Side Menu -->
<td valign="top" class="page_side_menu">
<mycontrols:sidemenu id="SideMenu1" runat="server"/>
</td>
This is the code in side_menu.ascx
<%# Control Language="vb" AutoEventWireup="false" Codebehind="side_menu.ascx.vb" Inherits="TOrders.UI.Controls.SideMenu" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<table cellPadding="0" width="100%">
<tr>
<td vAlign="top" align="left" width="100%">
<table cellSpacing="10" cellPadding="0" width="100%">
<tr>
<td align="left">
<asp:Literal ID="litError" Runat="server" Text="<font color=#E0E0E0 size=1>* </font>" Visible="False"></asp:Literal><asp:label id="lblJump" runat="server" ForeColor="#E0E0E0" Font-Size="XX-Small">Jump to Telex/Order:</asp:label>
<br>
<asp:textbox id="txtJumpTo" runat="server" Width="125px" CssClass="textbox"></asp:textbox> <input type="button" value="Go" runat="server" id="btnGo" class="TabOut-Button">
</td>
</tr>
</table>
</td>
</tr>
</table>
<script language="JavaScript" src="~/library/scripts/side_menu.js" type="text/javascript"></script>
<script language="JavaScript" src="~/library/scripts/side_menu_items.js" type="text/javascript"></script>
<script language="JavaScript" src="~/library/scripts/side_menu_tpl.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
new menu (SIDE_MENU_ITEMS, SIDE_MENU_POS, SIDE_MENU_STYLES);
// -->
</script>
This is the javascript function side_menu.js
var menus = [];
function menu (item_struct, pos, styles) {
// browser check
this.item_struct = item_struct;
this.pos = pos;
this.styles = styles;
this.id = menus.length;
this.items = [];
this.children = [];
this.add_item = menu_add_item;
this.hide = menu_hide;
this.onclick = menu_onclick;
this.onmouseout = menu_onmouseout;
this.onmouseover = menu_onmouseover;
this.onmousedown = menu_onmousedown;
var i;
for (i = 0; i < this.item_struct.length; i++)
new menu_item(i, this, this);
for (i = 0; i < this.children.length; i++)
this.children[i].visibility(true);
menus[this.id] = this;
}
try removing tilde (~) from javascript src path and make sure path is actually correct
To me it was the same and so solution is:
Change the relative path and leave them in taking away the root ~ /
before
<%# Control Language="VB" AutoEventWireup="false" CodeFile="wucDTmisc1.ascx.vb" Inherits="wucDTmisc1" %>
<%# Register Src="wucBeneficiarios.ascx" TagName="wucBeneficiarios" TagPrefix="uc1" %>
<%# Register Assembly="Coolite.Ext.Web" Namespace="Coolite.Ext.Web" TagPrefix="ext" %>
<%# Register Src="Controles/wucMoneda.ascx" TagName="wucMoneda" TagPrefix="uc1" %>
<link href="~/css/content.css" rel="stylesheet" type="text/css" />
<link href="~/css/Blue.css" rel="stylesheet" type="text/css" />
<script src="~/js/siscli.js" type="text/javascript"></script>
<script src="~/js/json2.js" type="text/javascript"></script>
<script src="~/js/date.js" type="text/javascript"></script>
after
<%# Control Language="VB" AutoEventWireup="false" CodeFile="wucDTmisc1.ascx.vb" Inherits="wucDTmisc1" %>
<%# Register Src="wucBeneficiarios.ascx" TagName="wucBeneficiarios" TagPrefix="uc1" %>
<%# Register Assembly="Coolite.Ext.Web" Namespace="Coolite.Ext.Web" TagPrefix="ext" %>
<%# Register Src="Controles/wucMoneda.ascx" TagName="wucMoneda" TagPrefix="uc1" %>
<link href="/css/content.css" rel="stylesheet" type="text/css" />
<link href="/css/Blue.css" rel="stylesheet" type="text/css" />
<script src="/js/siscli.js" type="text/javascript"></script>
<script src="/js/json2.js" type="text/javascript"></script>
<script src="/js/date.js" type="text/javascript"></script>
Also while looking for the solution, I realized that in controls is better to leave the JS code.
It worked for me, I hope you too.
What you need is maybe something as explained here. You'll have to replace the "~" with something that will follow the usercontrol where he PRESENTLY is instead of where he is landed phisicaly in the application.
<script language="javascript" type="text/javascript" src="<%=Page.ResolveUrl("~/JS/VerticalMenu.js")%>"></script>
<script language="javascript" type="text/javascript" src="<%=Page.ResolveUrl("~/library/scripts/side_menu_items.js")%>"></script>
<script language="javascript" type="text/javascript" src="<%=Page.ResolveUrl("~/library/scripts/side_menu_tpl.js")%>"></script>
RESOLVED
I finally found the solution to the problem. It was with the script tag
I rewrote it as
<script src="../library/scripts/side_menu.js" type="text/javascript" />
instead of
<script src="../library/scripts/side_menu.js" type="text/javascript"></script>

Categories

Resources