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.)
Related
I Have a class that find Google search results. And i have a JSP page that i want to show the results in. But i can't do it.
Heres my UrlOku class :
public static void GetUrl() {
final String keyword = "emre varol";
final String url = "https://www.google.com/search?q="+keyword;
try {
final Document document = Jsoup.connect(url).get();
List<String> myList = new ArrayList<String>();
for(Element row: document.select("div[class=g]")) {
final String title = row.select("div[class=TbwUpd NJjxre]").text();
myList.add(title);
}
}
And heres my JSP page :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="urlpaket.Urloku" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="menu.jsp"></jsp:include>
<%
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
WELCOME ${username}
<%
Urloku oku = new Urloku();
oku.GetUrl();
%>
<c:forEach items="${myList}" var="item">
<tr>
<td><c:out value="${item.title}" /></td>
</tr>
</br>
</c:forEach>
And there is nothing in the welcome.jsp file.
Any help would be appreciated!
How is myList variable available in you JSP? This needs to be set in pageContext before accessing it using ${myList}.
You can change the signature to public static List GetUrl()
and do something like this
Urloku oku = new Urloku();
List<String> myList = oku.GetUrl();
pageContext.setAttribute("myList ",myList );
Now it should be available.
I am getting values from DAO its stored in varaible editVal and page return to edit.jsp now how to get varaible editVal values in edit.jsp page..
Controller page:
#RequestMapping(value="edit", method=RequestMethod.GET)//String
public ModelAndView callgetSuccess(#ModelAttribute("id")String Id, BindingResult result, ModelMap model) {
ModelAndView shop=new ModelAndView();
shopModel shModel=new shopModel();
if(result.hasErrors()){
System.out.println("error");
return new ModelAndView("edit","shopModel",editVal);//"edit"
}else{
shModel = shopService1.editshop(Id);
model.addAttribute("shopModel",shModel);
shop.addObject("shopModel", shModel);
return new ModelAndView("edit","shopModel",shModel);
}
edit.jsp
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<html>
<body>
<h2>Hello World!</h2>
<form>
<h1>Success</h1>
edit page
<c:out value="${id}" />
</form>
</body>
</html>
Edit.jsp Page Imge
edit jsp page image
As editVal is a string, you can access it <c:out value="${shopModel}" />
If its a list of string, then the following can be used
<c:forEach var="shop" items="${shopModel}">
<c:out value="${shop}" />
</c:forEach>
If its a list of objects, then var.<object attribute name> as follows
<c:forEach items="${shopModel}" var="shop">
<tr>
<td>${shop.name}</td>
<td>${shop.number}</td>
...
</tr>
</c:forEach>
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 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); %>
I need to display all values of an enum as <option> elements. I have achieved this using scriptlets:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="errors" tagdir="/WEB-INF/tags/jostens/errors" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
...
<%
Class<?> c = CarrierCode.class;
for (Object carrier : c.getEnumConstants()) {
CarrierCode cc = (CarrierCode) carrier;
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
out.print(formatter.format("<option value='%s'>%s</option>\n", cc.getMfCode(), cc.name()));
}
%>
...
However, I would like to implement it using JSTL/EL code instead. How can I do it?
UPDATE:
Spring has a much easier way to do this now. First add the spring frame work tags
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
then if you just declare a select where the variable in path is an Enum,
spring automagically finds the other elements.
<form:select path="dataFormat.delimiter" class="dataFormatDelimiter">
<form:options items="${dataFormat.delimiter}"/>
</form:select>
Create a ServletContextListener implementation which puts the enum values in the application scope during webapp startup so that it's available in EL by ${carrierCodes}. This class is reuseable for all other things you'd like to do once during webapp's startup.
#WebListener
public class Config implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("carrierCodes", CarrierCode.values());
}
#Override
public void contextDestroyed(ServletContextEvent event) {
// NOOP
}
}
Note that I used Enum#values() instead of the clumsy Class#getEnumConstants() method. It returns an array of all enum values.
Then, in JSP, just use JSTL <c:forEach> to iterate over it.
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="carrierCode">
<c:forEach items="${carrierCodes}" var="carrierCode">
<option value="${carrierCode.mfCode}">${carrierCode}</option>
</c:forEach>
</select>