简体   繁体   中英

Passing value of a java method to a javascript variable using Struts 2 tag

I have a JSP file

<%@ taglib prefix="s" uri="/struts-tags"%>
<% response.setContentType("application/javascript"); %>

var collegename = '<s:text name="student.collegename"/>';

student.collegename defined in messages.properties file. now i can use collegename variable in java script file.

Is there any tag in Struts2 by using those i can pass the java value to a java script variable ?

for example:

var jsvariable = 'string value of a java method';

I have used this but its not worked: Servlet code: HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("collegename", collegename);
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("collegename", collegename);

JSP code: var collegename= '<%=request.getAttribute("collegename")%>'; Java Script code: alert("collegename"+collegename)
it show on IE: 'collegename' is undefined

please suggest

i have also try this: Action class: import javax.servlet.http.HttpServletRequest; HttpServletRequest request; HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("collegename", collegename); System.out.println("now getting attribute-----"); String attr=(String) request.getAttribute("cname"); System.out.println("attr is:::"+attr); import javax.servlet.http.HttpServletRequest; HttpServletRequest request; HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("collegename", collegename); System.out.println("now getting attribute-----"); String attr=(String) request.getAttribute("cname"); System.out.println("attr is:::"+attr);

getter/setter for collegename property.

JSP code: <%@ taglib prefix="s" uri="/struts-tags"%> <% response.setContentType("application/javascript"); %> var collegename= '<%=request.getAttribute("collegename")%>'; <%@ taglib prefix="s" uri="/struts-tags"%> <% response.setContentType("application/javascript"); %> var collegename= '<%=request.getAttribute("collegename")%>';

Java Script code: alert("collegename"+collegename) it show on IE: 'collegename' is undefined

although it show getting attribute (college name) on console but it is not show on java script alert.
it show on IE: 'collegename' is undefined

please review.

You can use some like code.

var jsvariable = '<%=request.getAttribute("testattribute")%>';

Hope it helps

这将在您的操作类上调用getSomeValue()方法。

var collegename = '<s:property value="someValue" escapeJavaScript="true"/>';

如何使用$ {userName}或OGNL%{userName}之类的EL ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM