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); %>
Related
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%>
<%
}
%>
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"/>
I am trying to pass a String[] from a java class to a jsp file, i manage to pass a simple String, but i am stuck on this one for few days now. Can someone help me, i wold like the answer to be more detailed since i am new at this.
Java class:
public class UserArray extends Applet {
public String javaArray [] =
{ "array 1", "array 2" , "array 3" };
public String [] getJavaArray() {
return javaArray;
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<jsp:useBean id ="array" class="eu.xyx.ztr.applet.UserArray"/>
</head>
<body>
<h4>
<jsp:getProperty name ="array" property="javaArray"/>
</h4>
</body>
So far i have maage to obtain the address of String[]. I just want to obtain the values of javaArray and if it is posible to obtain them in a form like this:
<script>
function addrow(tableID){
var numeuser=document.numeuser;
var nume=["adrian","cristi","levi",numeuser];
var prenume=["ric","dre","asd"];
var email=["rew#td","qq#eqwq","ee#ew"];
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList myArray = new ArrayList();
myArray.add("array 1");
myArray.add("array 2");
myArray.add("array 3");
request.setAttribute("myArray", myArray);
//then call jsp :
RequestDispatcher rd = request.getRequestDispatcher("mypage.jsp");
rd.forward(request, response);
}
jsp
<body>
<c:forEach var="myarr" items="${myArray}">
<c:out value="${myarr}" />
</c:forEach>
</body>
You should use javascript library like google JSON or jackson JSON for the same
have a look at these links
http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/
The code below doesn't print in jsp (the out.println in while{} ) but it works like a charm in Java program. Can you please explain me why won't print in jsp and what should I change in code? Thank you!
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.BufferedReader" %>
<%# page import="java.io.IOException" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.PrintWriter" %>
<%# page import="javax.servlet.ServletException" %>
<%# page import="javax.servlet.http.HttpServlet" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<%# page import="java.net.*" %>
<!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>
Test
<%try{
URL url = new URL("http://gesi-ro-test.banat.enelro:8010/dynamic/gesi/ri/elab/endcallrequest/wind.ser?id=008201dfa306f4a6&es=&is=2011/04/20%2013:09:46.593&rt=RE");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
in.close();
}catch(Exception e){
out.println(e);
}%>
</body>
</html>
Check your url again. I tried your code with another site and it works:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.io.BufferedReader" %>
<%# page import="java.io.IOException" %>
<%# page import="java.io.InputStreamReader" %>
<%# page import="java.io.PrintWriter" %>
<%# page import="javax.servlet.ServletException" %>
<%# page import="javax.servlet.http.HttpServlet" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<%# page import="java.net.*" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Test</title>
</head>
<body>
<%
URL url;
try {
url = new URL("http://www.w3schools.com/xml/note.xml");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
%>
<c:out value="<%=inputLine%>"/>
<%
}
in.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
%>
</body>
</html>
Personally, I dont like to put a lot of "if", "while" command in the jsp file (it will makes your system later become a big mess), so, try to handle eveything in your business logic and then send the result to the jsp as a attribute
This URL returns XML markup and it is not displayed. You have to add <pre> </pre> tag to show XML markup.
out.println("<pre>");
String inputLine = "";
while ((inputLine = in.readLine()) != null)
{
out.println(inputLine);
}
out.println("</pre>");
in.close();
You must have to use JSTL's <import/> instead of Java code in JSPs.
<c:import var="xmlData" url="http://your.url" />
<c:out var="${xmlData}"/>
I'm trying to use the following class in a JSP-based custom tag:
public class HelloWorldTest {
public void hello1() { }
}
The tag file is in WEB-INF/tags/hello.tag:
<%# tag language="java" pageEncoding="ISO-8859-1" %>
<% HelloWorldTest hello; %>
I'm trying to use the tag from index.jsp:
<%#taglib tagdir="/WEB-INF/tags" prefix="my"%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<my:hello></my:hello>
</body>
</html>
I get the following exception:
org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:178)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:370)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
The problem is trying to use the HelloWorldTest class, because a tag without it works fine:
<%# tag language="java" pageEncoding="ISO-8859-1" %>
<% for(int i = 0; i < 5; i++) { %>
<%= i %>
<% } %>
You need to actually import the class with an import directive.
<%# page import="my.package.HelloWorld" %>
(Where my.package is replaced with your class's actual package.)