I have a problem that should be straight forward and I'm clearly doing something wrong.
I have a simple site written in Spring MVC. My JSP model doesn't know my NewItem class..
#RequestMapping(value = "/", method = RequestMethod.GET)
public String newsFeed(Model model) {
try {
initDB();
} catch (Exception e) {
e.printStackTrace();
}
ScanRequest scanRequest = new ScanRequest()
.withTableName("Table1");
ScanResult result = _database.get(scanRequest);
//This will just return a list with filled NewsItems from the database
List<NewsItem> list = getNewsItems(result.getItems());
model.addAttribute("newsList",list);
return "newsfeed";
}
public class NewsItem {
private String url="";
String getUrl(){
return url;
}
void setUrl(String text) {
url = text;
}
private String title="";
void setTitle(String text) {
title = text;
Image = text;
}
String getTitle(){
return title;
}
String Description="";
String Image="";
String Time="";
String Since="";
}
And when im using ${newsList.getTile()} on the JSP side im getting a
javax.servlet.jsp.JspException: javax.el.MethodNotFoundException:
Method not found: class java.util.ArrayList.getTile() or
java.lang.NumberFormatException: For input string:.. when Im trying to
use ${newsList.Image}. Does anyone know what Im missing here?
stuff im using in jsp. taglib uri="http://tiles.apache.org/tags-tiles"
prefix="tiles" taglib prefix="spring"
uri="http://www.springframework.org/tags" taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c" page
import="com.kiiak.tennman.NewsItem"
Call getTitle (note spelling) on a NewsItem rather than on the List itself
<c:forEach var="newsItem" items="${newsList}">
${newsItem.title}
</c:forEach>
Related
I have an ApplicationAdvice class that passes a reference to a profile picture on every page:
#ControllerAdvice
public class ApplicationAdvice {
...
#ModelAttribute("currentProfilePicture")
public String currentProfilePicture(Principal principal, Model model) {
if (principal != null) {
String currentProfilePicture = "#{/images/default-profile-picture.png}";
log.info(currentProfilePicture);
model.addAttribute("currentProfilePicture", currentProfilePicture);
return currentProfilePicture;
} else {
String currentProfilePicture = "#{/images/default-profile-picture.png}";
log.info(currentProfilePicture);
model.addAttribute("currentProfilePicture", currentProfilePicture);
return currentProfilePicture;
}
}
}
HTML:
<img class="profilePicture hvr-pulse-grow" th:src="${currentProfilePicture}" />
Am I not escaping the static reference properly? #{/images/default-profile-picture.png} The url string prints out fine... I basically just want to pass a string to a static file to the img tag.
It should look like this:
String currentProfilePicture = "/images/default-profile-picture.png";
<img class="profilePicture hvr-pulse-grow" th:src="#{${currentProfilePicture}}" />
You can't pass an entire thymeleaf string to be evaluated without doing some tricks with the preprocessing, but the above should do what you want.
I'm working a dynamic website with jsp.
Now my problem: when I use <%, to write my java, everything works perfectly fine.
<%
out.println("<p>test</p>");
%>
But when i use the <%! like this:
<%!
private void test() {
out.println("<p>test</p>");
}
%>
My output will get displayed in my code editors console and not on my website as expected.
As import I used <%# page import="static java.lang.System.out" %>. Is this the correct import or is the problem somewhere else?
If more information is needed please comment! :)
As you probably know, JSPs are turned into servlets on-the-fly by the Java EE container. In a <% ... %> block, out is a local variable in the generated _jspService (or similar) method in the generated servlet. It's a JspWriter for writing to the output for the page.
In a <%! ... %> block, you're outside that generated _jspService (or similar) method, and so your static import means your out reference is to System.out, which isn't where the page output should be sent.
If you want to define methods in your JSP in <%! ... %> blocks, you'll have to pass out into them:
<%!
private void test(JspWriter out) throws IOException {
out.println("<p>test</p>");
}
%>
About that JSP -> servlet thing, say we have this JSP:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<%
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
%>
<%!
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
%>
</body>
</html>
Note that it has a <%...%> block and a <%! ... %> block.
The Java EE container turns that into something somewhat like the following. Note where our test method ended up, and where the code in our <%...%> block ended up (along with our raw JSP text/markup):
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private void test(JspWriter out, String msg) throws java.io.IOException {
out.println(msg);
}
/* ...lots of setup stuff omitted... */
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("<!doctype html>\n");
out.write("<html>\n");
out.write("<head>\n");
out.write("<meta charset=\"utf-8\">\n");
out.write("<title>Example</title>\n");
out.write("</head>\n");
out.write("<body>\n");
out.println("The current date/time is " + new java.util.Date());
this.test(out, "Hi, Mom!");
out.write("\n");
out.write("</body>\n");
out.write("</html>\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else log(t.getMessage(), t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
I am developing one sample web application using JSP and Servlets, in this application i have set some object in the Servlets, i can retrieve that value in JSP by using request.getAttribute("Object"). Here i want to iterate that array of value in JSP. How can i achieve this any one help me.
My servlet code:
ArrayList<Performer> Performerobj=new ArrayList<Performer>();
ResultSet rst = stm1.executeQuery("some query");
while (rst.next())
{
Performer obj=new Performer();
obj.setProject(projectname);
obj.setCount(rst.getString("COUNT"));
obj.setDate(rst.getString("DATE"));
obj.setEmpid(rst.getString("empid"));
Performerobj.add(obj);
}
request.setAttribute("Performer", Performerobj);
Performer.java
public class Performer {
private String project;
private String empid;
private String date;
private String count;
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
/*setter and getter...... for all*/
Perform.jsp
<% List<Performer>obj1=List<Performer>)request.getAttribute("Performerobj"); %>
<script>
var obj=<%=obj1%>
for(obj object : list)
{
/*IS it correct way or how can i iterate*/
}
</script>
You can do that if you transform the ArrayList object into a JSON using a library like Jackson:
<% List<Performer>obj1 = (List<Performer>) request.getAttribute("Performerobj"); %>
<script>
var obj=<%=new ObjectMapper().writeValueAsString(obj1)%>;
for(obj object : list)
{
/*IS it correct way or how can i iterate*/
}
</script>
Another option is to use JSTL:
<c:forEach var="performer" items="${Performerobj}">
<c:out value="${performer.project}"/>
</c:forEach>
I got a string replace issue when I pass Java String into android webView through JavaScriptInterface.
Below is the HTML (utf-8 file) inside the webView:
<html>
<head>
<script type="text/javascript">
a=window.MyAndroid.getPicEncStr(); //get string from Java side.
function getValue(){
b="ue";
if(a==b) {
d="match";
} else {
d="not match";
}
c=d+":"+a.replace("u","0")+b.replace("u","0");
document.getElementById("test").innerHTML=c;
}
</script>
</head>
<body>
<span id="test">test</span>
</body>
</html>
JavaScriptInterface code are below:
import java.io.UnsupportedEncodingException;
import android.content.Context;
public class JavaScriptInterface {
private String unicodeToUtf8(String s) {
String str=null;
try {
str=new String( s.getBytes("utf-8") , "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
public String getPicEncStr() {
//return "ue"; //not work
return this.unicodeToUtf8("ue"); //not work
}
}
The result in span("id"="test") is "match:ue0e" when I call webView.loadUrl("javascript:getValue()") no matter I convert from "unicode" to "utf-8" or not.
Basically string "a" equals to string "b", but the replace function doesn't work on a, only works on b.
Could someone help me with that?
Thanks.
It seems I find a way to solve the problem:
<html>
<head>
<script type="text/javascript">
a=window.MyAndroid.getPicEncStr(); //get string from Java side.
function getValue(){
b="ue";
if(a==b) {
d="match";
} else {
d="not match";
}
a=new String(a); //<-- force convert java string to javascript string.
c=d+":"+a.replace("u","0")+b.replace("u","0");
document.getElementById("test").innerHTML=c;
}
</script>
</head>
<body>
<span id="test">test</span>
</body>
</html>
Still don't understand why. When I dump "a", it shows "ue", when I try to dump "a[0]", it shows "undefined", however "b[0]" is "u", I only can image Java/Javascript string are not compatible with each other, so, a explicit conversion is necessary.
Say I have my custom taglib:
<%# taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
Inside the taglib class I need to process a template and tell the JSP to re-evaluate its output, so for example if I have this:
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
The output I have is:
<c:out value="My enclosed tag"/>
Test
When I actually need to output this:
My enclosed tag
Test
Is this feasible? How?
Thanks.
Tiago, I do not know how to solve your exact problem but you can interpret the JSP code from a file. Just create a RequestDispatcher and include the JSP:
public int doStartTag() throws JspException {
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
RequestDispatcher disp = request.getRequestDispatcher("/test.jsp");
try {
disp.include(request, response);
} catch (ServletException e) {
throw new JspException(e);
} catch (IOException e) {
throw new JspException(e);
}
return super.doStartTag();
}
I tested this code in a Liferay portlet, but I believe it should work in other contexts anyway. If it don't, I would like to know :)
HTH
what you really need to have is this:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
and change your doTag to something like this
#Override public void doTag() throws JspException, IOException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
// do something to the body here.
JspWriter out = bc.getEnclosingWriter();
if(body != null) {
out.print(buff.toString());
}
} catch(IOException ioe) {
throw new JspException("Error: "+ioe.getMessage());
}
}
make sure the jsp body content is set to jsp in the tld:
<bodycontent>JSP</bodycontent>
Why do you write a JSTL tag inside your doTag method?
The println is directly going into the compiled JSP (read: servlet) When this gets rendered in the browser it will be printed as it is since teh browser doesn't understand JSTL tags.
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
You can optionally add HTML tags to the string.