Struts 2 - JSP : Render String as JSP - java

I have an action class with a String property named jspString. I create the content for the resulting JSP of this action class using the property jspString. I have included my action class and the resulting JSP codes. My problem is, when I try to include a JSP page , using jsp:include tag, it is not rendering the content of that page in the resulting page.
Action class :
public class HomeAction extends ActionSupport
{
private String jspString = "";
public String execute()
{
jspString += "<div>";
jspString += "<p>";
jspString += "<jsp:include page=\"check.jsp\">";
jspString += "</p>";
jspString += "</div>";
return "success";
}
public String getJspString()
{
return jspString;
}
public void setJspString(String jspString)
{
this.jspString = jspString;
}
}
Resulting JSP:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<s:property escapeHtml="false" value="jspString"/>
</body>
</html>
now div, p tags are created. But jsp:include is not working. It is not displaying the contents of check.jsp in the resulting page.

Use the s:action tag it allows execute action on the server and return jsp in the body of the tag.
<s:action name="home"/>

Related

Spring MVC form submission, populate on the same page

I am trying to create a simple function using a post method. What I want is whatever is entered in the form and submitted- it should appear on the same page below the form. However the text just disappears once I click "submit". Here is my code
Contoller
#Controller
public class SearchController {
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String goToSearch(Model model) {
model.addAttribute("item", new Item());
return "itemsearch";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Item item, Model model, #RequestParam String itemId) throws IOException{
model.addAttribute("item", new Item());
return "itemsearch";
}
}
Jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!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>
</head>
<body>
<h2>Search for an item</h2>
<sf:form action="search" method="POST" modelAttribute="item">
<label>Please enter the item Id number:<sf:input type="text" name="itemId" id="itemId" path="itemId" /></label><br/>
<input type="submit" value="Submit" path="submit" />
<br> You are trying to search for Id Number: <b><h3>${item.itemId}<h3></h3></b>
</sf:form>
Item class
public class Item {
private String itemId;
private List<String> itemDetails;
public List<String> getItemDetails() {
return itemDetails;
}
public void setItemDetails(List<String> itemDetails) {
this.itemDetails = itemDetails;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
Many thanks
I think you need a basic understanding how Spring MVC works.
Have a look at this picture:
You see an incoming request (your POST request) from the client which is redirected to the desired controller. The controller (your SearchController) makes some business magic and returns the model to the front controller. The model is by default empty. You can add objects that should be rendered via model.addAttribute("someId", someObject);
The passed model is now handled by the view template (itemsearch) which connects the template and the model to a (static) response that is passed to the client.
And there is the problem. You are passing in your controller new Item() to the model. It is an empty object which has no values (and no id which you want to render after the form submition). Therefore on your JSP page could be nothing displayed. Just pass the found item or the item from your request to the model.

How to pass the array list from servlet to JSP?

In the servlet:
List<myItem> yourObjectToReturn = search.parserContent();
request.setAttribute("yourObjectToReturn",yourObjectToReturn);
the array yourObjectToReturn consists 3 variable(id, txtfile, sentence) which you can see from
the myItem class
public class myItem{
String sentence;
int id;
String txtfile;
// public myItem(){
// }
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getTxtfile(){
return txtfile;
}
public void setTxtfile(String txtfile){
this.txtfile = txtfile;
}
public String getSentence(){
return sentence;
}
public void setSentence(String sentence){
this.sentence = sentence;
}
}
how to display the id, txtfile, sentence in the JSP separately? How to pass the arraylist from servlet to JSP .
the JSP : how to edit my JSP. I got error of my JSP:
type safety: unchecked cast from objectto arraylist
<%# page import="java.io.*" %>
<%# page import="java.net.*" %>
<%# page import="java.util.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# 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>
<% List<myItem> myList = (ArrayList<myItem>) request.getAttribute("yourObjectToReturn"); %>
The search Result SENTENCE IS: <%=myList %> --%>
</body>
</html>
Don't use scriptlets in your jsp page.
Include the JSTL standard taglib via:
<%# taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
Then in your JSP use the iteration tag:
<c:forEach items="${requestScope.yourObjectToReturn}" var="current">
<c:if test="${current.sentence== 'secret' }">
<h1>seeeeeeeeeecret revealed</h1>
</c:if>
</c:forEach>
Where:
${requestScope.yourObjectToReturn} is your collection object.
And (during each iteration):
${current} is your actual element.
For further reference look http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html
And to avoid weird errors: don't forget to import myItem class (Should really be MyItem, thou...)
EDIT: Before digging deep into JSTL, I suggest you to take a reading of this other question. Particularly focus on the selected answer, it provides great insights.
To retrieve the Id and Txtfile from the List you need to iterate with using for example a for loop like:
...
for (int i=0; i < myList.size(); i++) {
%>
<%=myList.get(i).getId()%>
<%=myList.get(i).getTxtfile())%>
<%}%>
You can use for loop and html together as follows:
<%
#SupressWarnings("unchecked")
List<mtItem> myList
for (MyItem myitem : myList)
{
%>
The search result is <%=myitem%>
<%
}
%>

Trying to pass a list from servlet to jsp but prints null

I am trying to pass an ArrayList of objects from a servlet to a jsp file but when I try printing it, it prints nothing. I used the exact lines from a similar post for the jsp...can someone help me because I have never used a jsp before.
The idea is to to traverse through an xml file using dom parser and then print its elements to an html table of a specific form. My java code successfully collects all the elements and stores them in a list which I want to pass in the jsp to format in the table asked...
SERVLET CODE (with missing pieces cause it's huge) :
import all the needed libraries
public class MyServlet extends HttpServlet {
private static xml_obj obj = null;
public static ArrayList<xml_obj> objList = new ArrayList<xml_obj>();
public static void main(String[] args){
try {
Start(); //starting the methods for the xml traversal and creates the list
//System.out.println("AA"+objList.get(1).getName());
}
catch(Exception e) {
e.getMessage();
}
}
public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
ArrayList list = getList();
//System.out.println(objList.get(1).getName());
request.setAttribute ("Xml_objList", objList );
RequestDispatcher view = request.getRequestDispatcher("DomNav.jsp");
view.forward (request,response);
}
static void Start(){
/*..........code missing.............*/
myDOMTreeProc dtp = new myDOMTreeProc();
dtp.processLvl(ListOfCh, 0); //processLvl -> method in myDOMTreeProc
}
public static ArrayList<xml_obj> getList() {
return objList;
}
}
class myDOMTreeProc {
/*........DOM XML TRAVERSE.......*/
}
class attribute {
private String Name;
private String Value;
/*.............setters/getters.......*/
}
class xml_obj {
public int Lvl;
private String Name;
private String Value;
private String Parent;
private ArrayList<attribute> attributes=null;
/*.............setters/getters.......*/
}
JSP CODE:
<%# 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"%>
<%#page import="java.util.*" %>
<!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>Expression Language Example</title>
</head>
<body>
<h1>TEST JSP</h1>
<% ArrayList list = (ArrayList) request.getAttribute("Xml_objList"); %>
<c:forEach var="item" items="${Xml_objList}">
${item.Lvl}
</c:forEach>
</body>
</html>
The list is correct I tested it. I think the problem is when I pass it in the jsp.
Follow Java Naming convention and everything will work fine. Just replace int Lvl with int lvl;
JSP:
<c:forEach var="item" items="${Xml_objList}">
${item.lvl}
</c:forEach>
Instead of ${item.lvl} you can try with ${item.getLvl()} or ${item['lvl']}

jsp can't redirect page using response

I can't redirect to the page with the response.sendRedirect(url);
I can redirect to a link in a common jsp page, but I failed to send it in a function I defined in a jsp page. So in my case, which redirecting within a function, how to solve that?
FYI, the error is "response cannot be resolved".
Below is part of my source code:
<%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%# page import="javax.mail.*"%>
<%# page import="javax.mail.internet.*"%>
<%# page import="javax.activation.*"%>
<%# page import="java.util.*,java.io.*"%>
<%# page language="java" %>
<%# page import="com.mysql.jdbc.Driver" %>
<%# page import="java.sql.*" %>
<%!
public void sendSMS(String nickName, String setAname, String currAname,
String toPhone){
String acctInfo="xxx";
String acctPwd="xxx";
String contents="Message from Miss U:( \n Please be reminded that your friend:"+nickName+" is OUT of your setting area: "+setAname+". The current area is "+currAname+".";
String smsURL="http://api.accessyou.com/sms/sendsms-utf8.php?msg="+contents+"&phone="+toPhone+"&pwd="+acctPwd+"&accountno="+acctInfo;
response.sendRedirect(smsURL);
}
%>
When you call your helper function you have to pass in the response object. Reason being that JSPs gets translated to Java Code, which is then compiled so it can run on JVM. Things between <%!...%> will get translated into helper methods that has different context than the code in <%...%>.
Your jsp will get translated into something like this:
public class MyJsp {
public void doPost(HttpServletRrequest request, HttpServletResponse response) {
/* tons of code compiled off JSP */
sendSMS(...)
}
private void sendSMS(String nickName, String setAnmae...) {
String acctInfo="xxx";
response.sendRedirect(...); // error, there is no response object in the local context
}
}
Something like this would work
%# page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<%# page import="javax.mail.*"%>
<%# page import="javax.mail.internet.*"%>
<%# page import="javax.activation.*"%>
<%# page import="java.util.*,java.io.*"%>
<%# page language="java" %>
<%# page import="com.mysql.jdbc.Driver" %>
<%# page import="java.sql.*" %>
<%
sendSMS(arg1, arg2, arg3, ar4, response)
%>
<%!
public void sendSMS(String nickName,
String setAname,
String currAname,
String toPhone,
ServletResponse response){
String acctInfo="xxx";
String acctPwd="xxx";
String contents="Message from Miss U:( \n Please be reminded that your friend:"+nickName+" is OUT of your setting area: "+setAname+". The current area is "+currAname+".";
String smsURL="http://api.accessyou.com/sms/sendsms-utf8.php?msg="+contents+"&phone="+toPhone+"&pwd="+acctPwd+"&accountno="+acctInfo;
response.sendRedirect(smsURL);
}
%>
Notice how in sendSMS you don't have direct access to the request and response object.
You can Do it as below
<%# page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Page Redirection</title>
</head>
<body>
<center>
<h1>Page Redirection</h1>
</center>
<%
// New location to be redirected
String site = new String("http://www.xyz.com");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
%>
</body>
</html>
Sample Code:
<%! public void sendSMS(HttpServletResponse response){
try{
response.sendRedirect("th.jsp");}
catch(Exception e){
e.printStackTrace();
}
} %>
<%sendSMS(response); %>

Custom list + JSP + java.lang.NumberFormatException

I want to implement custom JSP list tag, but have problem with accessing properties of custom list object. With example like below accessing a name property of List2 on test.jsp page give an error org.apache.jasper.JasperException: java.lang.NumberFormatException: For input string: "name". How to solve this ?
public class List2 extends ArrayList<String> {
public String getName() {
return "name";
}
}
test.jsp
<%-- java.lang.NumberFormatException --%>
${list.name}
<%-- this works ok --%>
<c:forEach items="${list}" var="item">
${item}
</c:forEach>
EDIT
Whole test.jsp working
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${list}" var="item">
${item}
</c:forEach>
Whole test.jsp NOT working
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
${list.name}
TestController.java:
#Controller
public class TestController {
#ModelAttribute("list")
public List2 testList() {
List2 l = new List2();
l.add("foo");
l.add("bar");
return l;
}
/* test.jsp */
#RequestMapping("/test")
public String test() {
return "test";
}
}
I think it's due to the fact that the JSP EL allows using . or [] to access object properties. But both have a special meaning for List instances: it means access to the nth element. You may thus write ${list[2]} or ${list.2}. Since EL detects that your object is an instance of a collection, it tries to transform name into a number, and you get this exception.
Note that this is only an explanation of the exception you get. I haven't checked the specification to see if it's a bug of Tomcat or if it's expected behavior.
You should very very rarely extend ArrayList. Most of the time, it's better to use delegation, and thus wrap the list inside another object. Couldn't you just have something like the following?
public class List2 {
private List list;
public String getName() {
return "name";
}
public List getList() {
return list;
}
}
Creating an extra class would be redundant, try using the following:
<c:set var="listName"><jsp:getProperty name="list" property="name"/></c:set>
<c:out value="${listName}"/>

Categories

Resources