I have problem with Tapestry 5. When i try to delete user from an table which have action link on cell it wont delete that user, it delete always last user that is on table... here is my code :
ViewAllUsers.java
public class ViewAllUsers {
#Inject
private Session session;
#Property
#SessionState
private User loginUser;
#Property
#Persist
private User user;
public List<User> getAllUsers() {
return session.createCriteria(User.class).list();
}
#CommitAfter
void onActionFromIzbrisi() {
session.delete(user);
}
}
ViewAllUsers.tml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
xmlns:p="tapestry:parameter">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
<title></title>
</head>
<body>
<t:Alerts />
<t:Grid t:source="allusers" t:add="Izbrisi,Edit" t:row="user">
<p:izbrisiCell>
<t:actionlink t:id="izbrisi" t:context="user">Delete</t:actionlink>
</p:izbrisiCell>
<p:editCell>
<t:PageLink t:page="EditUser" t:id="edit" t:context="user"> Edit </t:PageLink>
</p:editCell>
<p:deleteOptionCell>
</p:deleteOptionCell>
</t:Grid>
</body>
</html>
EDIT:
All i had to do here is to pass an parameter(Object or ID) in constructor of method for deleting files.
Just replaced
#CommitAfter
void onActionFromIzbrisi() {
session.delete(user);
}
with:
#CommitAfter
void onActionFromIzbrisi(User user) {
session.delete(user);
}
I don't think you can just pass your User instance in the t:context directly like that. A generic object instance cannot be passed between client and server directly. You will have to pass some kind of reference to your instance - usually an id - that your onActionFromIzbrisi() method can use to retrieve the actual object.
According to the doc for ActionLink the t:context attribute represents
The context for the link (optional parameter). This list of values
will be converted into strings and included in the URI.
That doc page also shows an example of how to pass an object.
Related
Spring boot Maven dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
#Service
public class MailContentBuilder {
private TemplateEngine templateEngine;
#Autowired
public MailContentBuilder(TemplateEngine templateEngine) {
this.templateEngine=templateEngine;
}
public String build(String templateName,String user,String email) throws IOException {
Context context=new Context();
context.setVariable("user", "Alpha");
context.setVariable("email", "alpha#gmail.com");
String test=templateEngine.process(templateName, context);
return test;
}
}
this is my mail sender method.
MimeMessage mimeMessage=javaMailSender.createMimeMessage();
//mimeMessage.setContent(mailContentBuilder.build("changepassword","alpha","ema il#email.com"), "text/html");
MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
helper.setTo(auth0UserService.getUser(userid).getEmail());
helper.setFrom(fromUsername);
helper.setSubject("Password Change Confirmation");
helper.setText(mailContentBuilder.build("changepassword","alpha","email#email.com"), true);
javaMailSender.send(mimeMessage);
this is my template, in src/resources/templates
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Change password</title>
</head>
<body >
helloooo th:text="${user}"
</body>
</html>
This is what it sends, it does not follow the expression language, but writes to the page as it is. no use of variables.
helloooo th:text="${user}"
th:text has to be an attribute to an html tag, so something like
<p th:text="helloooo ${user}" />
should work, judging from a glance at http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts
My template do not see objects, passed from Spring.
My code:
public class PublicModelAndView extends ModelAndView {
#Autowired
TemplateModulesHandler templateModulesHandler;
public void init() {
setViewName("index");
CSSProcessor cSSProcessor = new CSSProcessor();
cSSProcessor.setSiteRegion("public");
super.addObject("CSSProcessor", cSSProcessor);
JSProcessor jSProcessor = new JSProcessor();
super.addObject("JSProcessor", jSProcessor);
templateModulesHandler.setPublicModelAndView(this);
}
}
Contoller's code:
#SpringBootApplication
#Controller
public class IndexPage {
#Autowired
PublicModelAndView publicModelAndView;
#Autowired
OurServicesBean ourServicesBean;
#Autowired
PortfolioBean portfolioBean;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView indexPage() {
publicModelAndView.setTemplate("publicSiteIndexPage");
publicModelAndView.addObject("pageTitle", "TITLE!!!!!!!!!!!!!!");
publicModelAndView.addObject("ourServices", ourServicesBean.getMenu());
publicModelAndView.addObject("portfolioWorkTypes", portfolioBean.getWorkTypes());
publicModelAndView.addObject("portfolioWorks", portfolioBean.getWorks());
return publicModelAndView;
}
}
Main template's code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
>
<head th:include="headerAndFooter/fragments/header :: publicSiteHeader">
<title></title>
</head>
<body>
hello!
</body>
</html>
Fragment's code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:fragment="publicSiteHeader">
<title>${pageTitle}</title>
<!--[if lte IE 8]>
<script src="<?= SITE_TEMPLATE_PATH ?>/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
</body>
</html>
As result I do not see value of the object pageTitle, but I see in page output code like
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>${pageTitle}</title>
Why thymeleaf didn't paste value of the pageTitle to between title tag's open and close?
The same code works good with JSP, but do not work with thymeleaf.
Thymeleaf is not JSP, so that's why your template does not work as you expect.
Look here http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-texts and use something like:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<title th:text="#{pageTitle}">page title</title>
Edited - my solution is for localised texts which is good practice anyway. if you want to use content of variable than use $.
Hi I am new to JSP and JavaBean. I am practicing by writing an application where multiple pages will share a javabean component. The page "check.jsp" instantiates the bean and sets a property without any error. But whenever I try to getProperty in another jsp, survey.jsp, I get the error:
HTTP Status 500 - file:/survey.jsp(16,15) jsp:getProperty for bean with name 'survey'. Name was not previously introduced as per JSP.5.3
I have double checked that the name in the get and set properties are exactly the same as my bean id in the action element. Please I need help
CHECK.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<jsp:useBean id="survey" scope="application" class="appScope.SurveyBean"/>
<jsp:setProperty name="survey" property="quantity" value='<%= request.getParameter("title")%>' />
<form action="/appScope/survey.jsp" method="POST">
<h3> Thanks for your input</h3>
<h3> Please check the survey summary status if you want</h3><br/>
<input type="submit" value="Check Status" />
</form>
</body>
</html>
This is my javabean: SurveyBean.java:
package appScope;
public class SurveyBean {
private int javaQuantity = 0;
private int csQuantity = 0;
public int getJavaQuantity()
{
return javaQuantity;
}
public int getCsQuantity()
{
return csQuantity;
}
public void setQuantity(String bookTitle)
{
try
{
if(bookTitle.equals("java"))
{
javaQuantity++;
}
if (bookTitle.equals("c"))
{
csQuantity++;
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
and here is survey.jsp where i get the error:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h1>Survey Summary</h1>
//ERROR IS HERE
Java = <jsp:getProperty name="survey" property="javaQuantity" /> <br/>
C# = <jsp:getProperty name="survey" property="csQuantity" />
</body>
</html>
Name was not previously introduced
This indicates that you haven't told your JSP about this bean as of yet. You are directly using the <jsp:getProperty> before letting the JSP know about the bean.
You need to use the <jsp:useBean> tag to define the bean in the survey.jsp.The name attribute of the getProperty tag must match the id attribute of the useBean tag :
<jsp:useBean id="survey" class="appScope.SurveyBean" scope="request">
But this won't work , unless you set the bean named survey in the request scope in the check.jsp file and post that request to the survey.jsp.
This is the code to print to my jsp page. However I have other code in the page. When I call this function I want it to print the message right after where it is called. I can't check for sure because I am using xhtml negotiation, but I suspect it prints after the /html tag.
This is my function
public Print(HttpServletRequest request,HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
};
This is where I call it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<%# page import="com.otrocol.app.*" %>
<%
Print(request, response);
%>
</body>
</html>
This is what I think the result is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
</body>
</html>
"haha"
This is what I want the response to be:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
"haha"
</body>
</html>
This is the error I get:
The JSP uses its own PrintWriter, the JspWriter out. So pass this to the (static) function.
Otherwise you are taking a second writer, and with buffering everything goes haywire.
Also as output already did happen do not set the content type in the function.
At the top of the JSP is a nice location, also for the imports.
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
When having one writer the function would print at the correct spot in the body.
Nice intuition about the cause. BTW begin a function name with a small letter.
It's not a direct answer to your question but I believe what you're doing will cause you nothing but pain even if you get it to work. You're not using the right tool for the job; creating custom JSP tags is a better option for writing to JSP from Java code.
Code example:
register.jsp
<%# taglib prefix="custom" uri="/WEB-INF/custom-tags.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Register</title>
</head>
<body>
<p>
<c:out value="${custom:printHaha()}" />
</p>
</body>
</html>
custom-tags.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0"
xmlns="http://java.sun.com/xml/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd">
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>custom-taglib</shortname>
<uri>CustomTags</uri>
<function>
<name>printHaha</name>
<function-class>com.yourpackage.Tags</function-class>
<function-signature>
java.lang.String print()
</function-signature>
</function>
(...)
Tags.class
public class Tags {
public static String print() {
return "haha";
}
}
More info on Tags: official docs
I din't check your code ... you can't do a out.print again using get writer in a jsp page ... because the response for this request is already committed by rendering the jsp
now to print something on asp you can do this any number of ways
print by expression tag
use out (which is an object the server creates)
out.print("Blah...");
and more
to understand what happens to a jsp look into /work/catalina/blah.../
There are two pages. The first one is the Main Page. This one performs some
pseudo calcs.
Based on those calcs, either Success.jsp or Failure.jsp is returned.
This code will do what you wanted to have achieved.....
Even though as the others pointed out, there are more advanced techniques as of
late, still in order to dance, first you have to know the moves....
Primarily look at this
cObj.Print(request, response); in the 2nd jsp page.
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>JSP and JavaBean</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%
int x=cObj.setStoreCust();
if(x>=1)
{
%>
<jsp:forward page="Success.jsp" />
<%
}
else
{
%>
<jsp:forward page="Failure.jsp" />
<%
}
%>
</body>
</html>
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
<%# page import="rustler.Beans.Beany" %>
<%# page import="javax.servlet.http.HttpServletRequest" %>
<%# page import="javax.servlet.http.HttpServletResponse" %>
<!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>Failure!</title>
<%-- create an instance of Customer class --%>
<jsp:useBean id="cObj" scope="request" class="rustler.Beans.Beany">
<%-- Set the value of attribute such as CustID --%>
<jsp:setProperty name="cObj" property="*" />
</jsp:useBean>
</head>
<body>
<%cObj.Print(request, response);%>
</body>
</html>
Java Bean
package rustler.Beans;
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Beany implements Serializable
{
public Beany()
{
}
/**
*
*/
private static final long serialVersionUID = 1L;
private String custID;
private String custName;
private int qty;
private float price;
private float total;
private int storeCust;
public String getCustID() {
return custID;
}
public void setJunk(String sStr)
{
//System.out.println("What a punk!");
custName = sStr;//"What a punk!";
}
public void Print(HttpServletRequest request,HttpServletResponse response)
{
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<p>haha</p>");
}catch(IOException e){
e.printStackTrace();
}
}
public String prntJunk()
{
//System.out.println("What a punk!");
return custName;//"What a punk!";
}
public void setCustID(String custID) {
this.custID = custID;
}
public String getCustName() {
return custName;
}
public void setCustName(String custName) {
this.custName = custName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getTotal() {
return total;
}
public void setTotal(float total) {
this.total = total;
}
public int setStoreCust()
{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/usermaster","admin","password");
PreparedStatement pstmt=null;
String query=null;
query="insert into customer values(?,?,?,?,?)";
pstmt=con.prepareStatement(query);
pstmt.setString(1,custID);
pstmt.setString(2,custName);
pstmt.setInt(3,qty);
pstmt.setFloat(4,price);
pstmt.setFloat(5,total);
int i=pstmt.executeUpdate();
this.storeCust=i;
}
catch(Exception e)
{
}
return storeCust;
}
}
This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
I want to have a list box in JSF. I have written a simple code but it does not work. In demo page I see an empty box with out list and in user page I have error.
UserBean.java
#ManagedBean
#SessionScoped
public class UserBean implements Serializable{
public String favYear3;//list box
public String getFavYear3() {
return favYear3;
}
public void setFavYear3(String favYear3) {
this.favYear3 = favYear3;
}
public static class Year{
public String yearLabel;
public String yearValue;
public Year(String yearLabel, String yearValue){
this.yearLabel = yearLabel;
this.yearValue = yearValue;
}
public String getYearLabel(){
return yearLabel;
}
public String getYearValue(){
return yearValue;
}
}
public Year[] year3List;
public Year[] getFavYear3Value() {
year3List = new Year[3];
year3List[0] = new Year("Year3 - 2000", "2000");
year3List[1] = new Year("Year3 - 2010", "2010");
year3List[2] = new Year("Year3 - 2020", "2020");
return year3List;
}
}
demo.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>first jsf page</title>
</head>
<h:body>
<h1>JSF 2 check example</h1>
<h:form>
<h:selectOneListbox value="#{UserBean.favYear3}">
<f:selectItems value="#{UserBean.favYear3Value}" var="y"
itemLabel="#{y.yearLabel}" itemValue="#{y.yearValue}" />
</h:selectOneListbox>
</h:form>
</h:body>
</html>
user.xhtml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>second jsf page</title>
</head>
<h:body>
<h:outputText value="#{UserBean.favYear3}"/>
</h:body>
</html>
My problem: in demo page I have an empty box.
in user page the error is:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: javax.el.PropertyNotFoundException: /demo.xhtml #24,55 value="#{UserBean.favYear3}": Target Unreachable, identifier 'UserBean' resolved to null
javax.faces.webapp.FacesServlet.service(FacesServlet.java:321)
root cause
javax.faces.component.UpdateModelException: javax.el.PropertyNotFoundException: /demo.xhtml #24,55 value="#{UserBean.favYear3}": Target Unreachable, identifier 'UserBean' resolved to null
javax.faces.component.UIInput.updateModel(UIInput.java:848)
javax.faces.component.UIInput.processUpdates(UIInput.java:730)
javax.faces.component.UIForm.processUpdates(UIForm.java:268)
javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1109)
javax.faces.component.UIComponentBase.processUpdates(UIComponentBase.java:1109)
javax.faces.component.UIViewRoot.processUpdates(UIViewRoot.java:1218)
com.sun.faces.lifecycle.UpdateModelValuesPhase.execute(UpdateModelValuesPhase.java:74)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
What is wrong?
Your managed bean name in EL is wrong. You've declared the bean as follows:
#ManagedBean
#SessionScoped
public class UserBean implements Serializable{
When you don't specify the name attribute of the #ManagedBean, then it will conform the Javabeans Naming Conventions default to the classname with 1st character lowercased like so userBean, but yet you're trying to reference them with the exact classname #{UserBean}. You need to fix this name accordingly as #{userBean}.
The faces-config.xml registration is unnecessary for JSF 2.x. Remove it.
You have to make your bean reachable/managed. For this, you can either
annotate it with a CDI (#Named) or a JSF (#ManagedBean) annotation:
#Named
#SessionScoped
public class UserBean implements Serializable{...}
or describe it in the faces-config.xml as a managed-bean like this:
<managed-bean>
<managed-bean-name>userBean</managed-bean-name>
<managed-bean-class>com.example.UserBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>