Why EL function not working in this case? - function

I am working with Java 1.7, Eclipse Luna and JBoss 4.2.3.
I created a simple Dynamic Web Project named "Test001_WAR". In it:
I created a StringUtil class where I define a public static method:
package com.srh.base.util;
public final class StringUtil {
public static String notNullTrim(String string) {
System.out.println("StringUtil.java: notNullTrim(String): string=" + string);
if (string == null) {
return "";
} else {
return string.trim();
}
}
}
I created a myfunction.tld file where I mapped the above Java method to an EL function:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xml="http://www.w3.org/XML/1998/namespace"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd ">
<display-name>Custom Functions</display-name>
<tlib-version>1.0</tlib-version>
<short-name>NMTOKEN</short-name>
<uri>http://test001.srh.com/functions</uri>
<function>
<name>notNullTrim</name>
<function-class>com.srh.base.util.StringUtil</function-class>
<function-signature>java.lang.String notNullTrim(java.lang.String)</function-signature>
</function>
</taglib>
I created a index.jsp where I use the above EL function for testing. In it I define a string with spaces " abc ", store it in a hidden variable, call the EL function on it and store the return value in another hidden variable, and then after load alert values of both hidden variables:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://test001.srh.com/functions" prefix="fr" %>
<!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>Insert title here</title>
<script type="text/javascript">
function afterLoad() {
alert("h_mystring_org=" + document.getElementById("h_mystring_org").value);
alert("h_mystring_new=" + document.getElementById("h_mystring_new").value);
}
</script>
</head>
<body onload="afterLoad();">
<%
String mystring = " abd ";
System.out.println("index.jsp: mystring=" + mystring);
%>
<form action="">
<input type="hidden" id="h_mystring_org" name="h_mystring_org" value="<%=mystring%>">
<input type="hidden" id="h_mystring_new" name="h_mystring_new" value="${fr:notNullTrim(mystring)}">
</form>
</body>
</html>
I deploy the WAR to JBoss. Then go to URL
http://localhost:8080/Test001_WAR/index.jsp
It did not work. The function in StringUtil class was called but the parameter value it received was not the same as being passed from the JSP.
In the server.log file I see:
2016-01-10 10:58:37,295 INFO [STDOUT] index.jsp: mystring= abd
2016-01-10 10:58:37,298 INFO [STDOUT] StringUtil.java:
notNullTrim(String): string=
The alert values were
h_mystring_org= abd
h_mystring_new=
What I am doing wrong here?

Why don't you use the standard JSTL fn:trim() function that does exactly that?
Anyway, the JSP EL uses page/request/session/application attributes. Not scriptlet local variables.
Your code would (probably) work if the scriptlet did
page.setAttribute("mystring", " abd ");
or, if you did the right thing and forgot completely about scriptlet:
<c:set var="mystring" value=" abd "/>

Related

reCAPTCHA Unexpected token in JSON at position 0

We use reCAPTCHA ver 2 as checkbox "I am not bot". Since from 2020-11-05 19:23:00Z during our page loading we get exception:
recaptcha__ru.js:211 Uncaught (in promise) SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at recaptcha__ru.js:211
at recaptcha__ru.js:209
at Array.<anonymous> (recaptcha__ru.js:132)
at Array.<anonymous> (recaptcha__ru.js:208)
at GM.$ (recaptcha__ru.js:211)
at Array.<anonymous> (recaptcha__ru.js:253)
at QS.next (recaptcha__ru.js:416)
at y (recaptcha__ru.js:355)
Exception occurs in https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LcOyt8ZAAAAAD9WJMwwwvgvSGp8Bi0zWYS-FMX5&co=aHR0cDovL2JsYWNrYmlyZDo0ODA4MA..&hl=ru&v=1AZgzF1o3OlP73CVr69UmL65&size=normal&cb=a79dhaz0etu
Our page has not been changed. The reCAPTCHA breaks unexpectedly in one moment. On other page reCAPTCHA is still working (may be it is important the working page is a embedded inside iframe).
Any hints? What went wrong?
UPDATED
We try to isolate reCAPTCHA inside iframe in our JSP page as #user2384519 suggested:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%# taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%# taglib uri="http://richfaces.org/rich" prefix="rich"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Captcha test</title>
<script>
function extractRecaptchaResponse() {
var c = document.getElementById('g-recaptcha-isolator');
if (c) {
var src = c.contentWindow.document
.getElementById('g-recaptcha-response');
if (src) {
var target = document.getElementById('g-recaptcha-response');
target.value = src.value;
}
}
return true;
}
</script>
</head>
<body>
<h:form id="g-recaptcha-form">
<h:panelGroup>
<iframe id="g-recaptcha-isolator" src="/recaptcha.htm"
onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));'
style="height: 78px; width: 100%; border: none; overflow: hidden;">
</iframe>
</h:panelGroup>
<textarea id="g-recaptcha-response" name="g-recaptcha-response"
style="display: none"></textarea>
<h:panelGroup>
<h:commandLink onclick="extractRecaptchaResponse()"
actionListener="#{recaptcha.submit}">
<span>Submit</span>
</h:commandLink>
</h:panelGroup>
</h:form>
</body>
</html>
recaptcha.htm:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<script src="https://www.google.com/recaptcha/api.js"></script>
</head>
<body>
<div class="g-recaptcha" data-sitekey="xxxxxxx"></div>
and it solves the problem with JSON error, but reCAPTCHA shows popup with image selector and iframe cuts the popup.
If you are using Prototype.js:
The Prototype JS library overrides the method reduce in the class Array.
The issue is resolved if you just add the following script after all imports (preferentially after the body tag):
Array.prototype.reduce = function(callback, initialVal) {
var accumulator = (initialVal === undefined) ? undefined : initialVal;
for (var i = 0; i < this.length; i++) {
if (accumulator !== undefined)
accumulator = callback.call(undefined, accumulator, this[i], i, this);
else
accumulator = this[i];
}
return accumulator;
};
We also faced the same issue on 11/5. For quick fix, we have embedded recapcha in iframe. It was getting block by ajax4jsf/framework.pack.js
We had the same problem, then identified that the issue was a conflict caused by another minified js file loaded on the same page.
We trimmed down what js was loaded on the page down to a bare minimum, eliminating the collision, and now it works fine again.

SSRS report server Data issue

I have deployed SSRS report on Production environment. When 3 or more user run the same report on production then report server load other user requested data.
For Example-
Below 3 request-
User A requested Report X with Paremeter A
User B requested Report X with Paremeter B
User C requested Report X with Paremeter C
Output from SSRS server -
User A requested Report X with Paremeter A
User B requested Report X with Paremeter A
User C requested Report X with Paremeter C
Note- This problem occur when all the users request report in same time.
We had same issue, if you are using ReportViewerForMVC from NuGet Package manager which is third party control may cause problem, follow below points
we will re-use code from ReportViewerForMvc and modify as per our need
1
Install-package ReportViewerForMvc and press enter. After few minutes the package will be installed
2
This installation will add to the project: 2 assemblies (Microsoft.ReportViewer.WebForms & ReportViewerForMvc)to references an .aspx page (ReportViewerWebForm.aspx) and httphandlers settings in the web.config file.
Note: the .aspx page added does not have a .cs file.
You can now use this .aspx page and code everything in controller, but I am using a slightly different path for code reusability and consistency)
Add a new folder ‘Reports” to the project, and then add a new webform .aspx page (ReportTemplate.aspx to the Reports folder
3
Copy the contents (as shown in fig) from ReportViewerWebForm.aspx and replace the content of ReportTemplate.aspx with this.
Note: Please do not copy #page directive, copy only the highlighted section.
4
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<%--<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">--%>
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="scriptManagerReport" runat="server">
</asp:ScriptManager>
<rsweb:ReportViewer runat ="server" ShowPrintButton="false" Width="99.9%" Height="100%" AsyncRendering="true" ZoomMode="Percent" KeepSessionAlive="true" id="rvSiteMapping" SizeToReportContent="false" >
</rsweb:ReportViewer>
</div>
</form>
</body>
</html>
5
The ReportTemplate.aspx will change to this
6
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ReportTemplate.aspx.cs" Inherits="ASPNETMVC_SSRS_Demo.Reports.ReportTemplate" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<%--<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">--%>
<!doctype html>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="scriptManagerReport" runat="server">
<Scripts>
<asp:ScriptReference Assembly="ReportViewerForMvc" Name="ReportViewerForMvc.Scripts.PostMessage.js" />
</Scripts>
</asp:ScriptManager>
<rsweb:ReportViewer runat ="server" ShowPrintButton="false" Width="99.9%" Height="100%" AsyncRendering="true" ZoomMode="Percent" KeepSessionAlive="true" id="rvSiteMapping" SizeToReportContent="false" >
</rsweb:ReportViewer>
</div>
</form>
</body>
</html>
7
Next delete the below scripts tag from ReportTemplate.aspx page
<Scripts>
<asp:ScriptReference Assembly="ReportViewerForMvc" Name="ReportViewerForMvc.Scripts.PostMessage.js" />
</Scripts>
8
Add additional attributes to the ReportViewercontrol as below
<rsweb:ReportViewer id="rvSiteMapping"runat ="server"ShowPrintButton="false"Width="99.9%"Height="100%"AsyncRendering="true"ZoomMode="Percent"KeepSessionAlive="true"SizeToReportContent="false"></rsweb:ReportViewer>
9
Now open ReportTemplate.aspx.cs file and add below code to the Page_load event, you need to the SSRS Server URL and SSRS report Folder path.
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ASPNETMVC_SSRS_Demo.Reports
{
public partial class ReportTemplate : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
String reportFolder = System.Configuration.ConfigurationManager
.AppSettings["SSRSReportsFolder"].ToString();
rvSiteMapping.Height =
Unit.Pixel(Convert.ToInt32(Request["Height"]) - 58);
rvSiteMapping.ProcessingMode =
Microsoft.Reporting.WebForms.ProcessingMode.Remote;
rvSiteMapping.ServerReport.ReportServerUrl = new Uri("SSRS
URL"); // Add the Reporting Server URL
rvSiteMapping.ServerReport.ReportPath =
String.Format("/{0}/{1}", reportFolder, Request["ReportName"].ToString());
rvSiteMapping.ServerReport.Refresh();
}
catch (Exception ex)
{
}
}
}
}
}
10
Add the SSRSReportFolder path to the app settings in the web.config file.
<add key="SSRSReportsFolder" value="BIC_Reports"/>
11
Next, create an entity class ReportInfo.cs under Models folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ASPNETMVC_SSRS_Demo.Models
{
public class ReportInfo
{
public int ReportId { get; set; }
public string ReportName { get; set; }
public string ReportDescription { get; set; }
public string ReportURL { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string ReportSummary { get; set; }
}
}
12
Next, we will add code to the Controller and the View Pages. There is no
change to the HomeController.cs. Add the following code to Home/Index view
page.
#{
ViewBag.Title = "Index";
}
<h2>Reports List</h2>
<a id="ReportUrl_Performance" href="#Url.Action("ReportTemplate", "Report", new { ReportName = "Performance", ReportDescription = "Performance Report", Width = 100, Height = 650 })">
Performance Report</a>
13 Next
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ASPNETMVC_SSRS_Demo.Models;
namespace ASPNETMVC_SSRS_Demo.Controllers
{
public class ReportController : Controller
{
//
// GET: /Report/
public ActionResult ReportTemplate(string ReportName, string
ReportDescription, int Width, int Height)
{
var rptInfo = new ReportInfo
{
ReportName = ReportName,
ReportDescription = ReportDescription,
ReportURL = String.Format("../../Reports/ReportTemplate.aspx?
ReportName={0}&Height={1}", ReportName, Height),
Width = Width,
Height = Height
};
return View(rptInfo);
}
}
}
14
Final Step is to open the ReportTemplate view page under Report and add the following code.
#model ASPNETMVC_SSRS_Demo.Models.ReportInfo
<H1>
#Model.ReportDescription
</H1>
<iframe id="frmReport" src="#Model.ReportURL" frameborder="0" style="#String.Format("width:{0}%; height: {1}px;", Model.Width, Model.Height)" scrolling="no">
</iframe>

Issue with web application using JSP and Hibernate

Below is my index.html and action.jsp code
When I am submitting the values from index.html to action.jsp instead of getting the output of out.println in action.jsp I am getting the complete action.jsp as my output.
Advise what is the issue and how to rectify it also advise if the directory structure is correct i.e.; all files are placed where they are usually supposed to be placed or not
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="action.jsp" method="post">
Name <input type="text" name = "name"> <br>
Password <input type="password" name="password"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
// Below is action.jsp
<%#page import="p1.NewHibernateUtil"%>
<%#page import="org.hibernate.Transaction"%>
<%#page import="p1.User"%>
<%#page import="org.hibernate.Session"%>
<%#page import="org.hibernate.SessionFactory"%>
<%#page import="org.hibernate.cfg.Configuration"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println("In scriplet tag");
Configuration cfg = new Configuration();
out.println("Configuration object created");
cfg.configure("hibernate.cfg.xml");
out.println("Configured");
// SessionFactory sf = NewHibernateUtil.getSessionFactory();
// out.println("SessionFactory created");
// Session ses = sf.openSession();
// Transaction t = ses.beginTransaction();
// String n = request.getParameter("name");
// String p = request.getParameter("password");
//
// out.println("Welcome " + n);
// User u1 = new User(n, p);
// ses.save(u1);
// t.commit();
// ses.close();
// out.println("Data inserted successfully");
%>
</body>
</html>
As per my assumption you are running the given example without using web server. You will require web server to run given code.
Consider using web server (ex. Tomcat http://tomcat.apache.org/tomcat-8.0-doc/index.html )

How to get value of generated row value for another action when generated submit button is clicked

I want to know how to get dynamically generated table row value (eg. empp_id) when clicking submit button that is generated for each row dynamically.
Below is my code. I used to generate each row and submit button for each row. I don't know how to use submit button to get and pass the value of 'id' column to another action.
Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="edit" class="com.ojt.database.EditUserAction" method="execute">
<result name="success">edituser.jsp</result>
<result name="error"></result>
</action>
</struts>
EditUserAction.java
package com.ojt.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class EditUserAction extends ActionSupport {
List<User> liUser=null;
public List<User> getLiUser() {
return liUser;
}
public void setLiUser(List<User> liUser) {
this.liUser = liUser;
}
#Override
public String execute() throws Exception {
Connection conn;
String ret = "error";
try {
String url = "jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, "root", "root");
String sql = "SELECT * FROM user";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
liUser=new ArrayList<User>();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
liUser.add(user);
}
conn.close();
ret = "success";
System.out.println(ret);
} catch (Exception e) {
e.printStackTrace();
ret = "error";
System.out.println(ret);
}
return ret;
}
}
edituser.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="display" uri="http://displaytag.sf.net/el"%>
<!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>Edit</title>
</head>
<body>
<table cellpadding="20" align="center">
<tr>
<th>Id</th>
<th>Name</th>
<th>Password</th>
</tr>
<s:iterator value="liUser">
<tr>
<td><s:property value="id" /></td>
<td><s:property value="name" /></td>
<td><s:property value="password" /></td>
<td><s:submit value="Edit" theme="simple" action="review" method="POST"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
I need your help please.
I can't go any further, i am stuck here.
When you use <s:property/>, you are not creating a form tag, but just simple text. To send something printed with <s:property/>, use an <s:hidden/> in conjunction with it.
To send a list of object from JSP, you need to use the IteratorStatus object to specify an index.
You are not even using a form. You need a form to POST something in the standard, non-AJAX way.
You need two action's methods, or two actions: one to display the data, the other to edit it. In your execute() method you are initializing your list every time: liUser=new ArrayList<User>();, so the one coming from the page will always be lost.
You are in deep water. I suggest you to stop for a moment and take a closer look at HTML, HTTP, Struts2 and its tags, otherwise you will get frustrated quite soon.

problem loading values to my extjs grid using json

I am loading the values coming from database via a json object using java struts,
but the values are not populating in my extjs grid: I keep getting an empty grid.
I have included my code below.
home.jsp
A button will be there on this page. On clicking the getvalues.jsp should come.
In getvalues.jsp an extgrid should be presen with the content coming from database
<%# page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<form action="getvalues.do">
<input type="submit"></input>
</form>
</body>
</html>
Below is my Java code. I am populating a JSON object with the values from my database.
public class Json extends Action {
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
ArrayList<Employee> emp=new ArrayList<Employee>();
Myservice serve=new Myservice();
emp=serve.getemployeesservice();
Iterator<Employee> empitr=emp.iterator();
JSONArray json=new JSONArray();
JSONObject JSONobj=new JSONObject();
while(empitr.hasNext()){
JSONObject jobj=new JSONObject();
Employee empl=new Employee();
empl=empitr.next();
jobj.put("empid",empl.getEmpid());
jobj.put("empname",empl.getEmpname());
json.add(jobj);
}
JSONobj.put("employee",json);
System.out.println(JSONobj.toString());
return mapping.findForward("success");
}
}
getvalues.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/ext-all.css">
<script type="text/javascript" src="js/ext-base.js"></script>
<script type="text/javascript" src="js/ext-all.js"></script>
<script type="text/javascript">
Ext.onReady(function() {
var store=new Ext.data.JsonStore({
proxy:new Ext.data.HttpProxy({
url:'http://localhost:8080/JsonExample/getvalues.do'
}),
reader:new Ext.data.JsonReader({
root:'employee',
fields:['empid','empname']
})
});
store.load();
var recs=store.getRange();
alert(recs.length);
var grid = new Ext.grid.GridPanel({
title:'employee information',
columns: [{
header:"employeeid",
width:100,
dataIndex:'empid',
sortable:true
},{
header:"employeename",
width:100,
dataIndex:'empname',
sortable:true
}],
store: store,
width:300,
height:300,
renderTo:Ext.getBody()
});
});
</script>
</head>
<body>
hi
</body>
</html>
But the values are not being populated for some reason. Please help me solve this issue.
Thanks in advance!
I'm not good at Java. But, I suspect, your JSON list is not sent to client, you are just printing, but not including it in response.