applying display tag to my project but failed in struts config file - struts-1

I am applying display tag to my jsp in struts but not able to do it please check out
1.strutsconfig
<form-beans><form-bean name="DailysheetForm" type="com.myapp.struts.DailysheetForm"/>
</formbean>
<action input="/" path="/DailysheetList" name="DailysheetForm" scope="request" type="com.myapp.struts.DialysheetListAction">
<forward name="success" path="/DailysheetList.jsp"/>
</action>
2.Form
public class DailysheetForm extends ActionForm
{
// some getter and setter methods i used like receiptno
protected ArrayList arraylist;
public ArrayList getArraylist()
{
return arraylist;
}
public void setArraylist(ArrayList arraylist) {
this.arraylist = arraylist;
}
3.Action Class
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ArrayList dailysheetdata;
DailysheetForm dailyform = (DailysheetForm) form;
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost/Stonecrusher?"
+ "user=Stonecrusher&password=xxxxxx");
System.out.println("Connection"+connect);
dailysheetdata = StoneCrusherData.getDailysheetData(connect);
dailyform.setArraylist(dailysheetdata) ;
return mapping.findForward(SUCCESS);
}
JSP
<display:table id="data" name="requestScope.DailysheetForm.arraylist"requestURI="/DailysheetList" pagesize="10" >
<display:column property="receiptno" title="RECEIPTNO" sortable="true"/>
<display:column property="cutomername" title="CUSTOMER NAME" sortable="true"/>
</display:table>
<display:table id="data" name="requestScope.DailysheetForm.arraylist" requestURI="/DailysheetList" pagesize="10" >
<display:column property="receiptno" title="RECEIPTNO" sortable="true"/>
<display:column property="cutomername" title="CUSTOMER NAME" sortable="true"/>
</display:table>
It is not working and basically I am getting data to dailysheetdate which is arraylist in my Action Class and I want to display it in jsp with pagination. I know I was wrong please help me how to do it.

Check your jar files whether you placed all required jars in to lib or not..
still have a problem paste your Error here..
See the Tutorial for Display Tag
then you need not Specify input and name attributes in <action> in strutsconfig.xml
i.e your code should like ethis
<action path="/DailysheetList" scope="request" type="com.myapp.struts.DialysheetListAction">
<forward name="success" path="/DailysheetList.jsp"/>
</action>
then definitely Action Class will execute..
And one more thing by seeing your action class code i does't know whether StoneCrusherData object is created or not.. check below line also
dailysheetdata = StoneCrusherData.getDailysheetData(connect);

Related

custom validator call on button through ajax

hi i wrote a custom a validator which gets the system name and compare it against the id in database, now i wanna apply a check if this value is exactly the same, user must be allowed to click the button and move on else some error message should be displayed. and i am really confused how to call the validator() on through ajax.
my view page code is
<h:commandButton action="sample?faces-redirect=true" value="submit">
<f:ajax execute="#{csample.UserValidator}" render="#form" >
<h:inputText name="idtext" value="#{csampleBean.id}" />
</f:ajax>
</h:commandButton>
and my custom validator
public void UserValidator(FacesContext context, UIComponent toValidate, Object value)
throws UnknownHostException, ValidatorException, SQLException, NamingException
{
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
String machine= localMachine.getHostName();
String query = "select * from USER_ where USER_ID = '"+machine+"'";
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
Statement stat = conn.createStatement();
//get customer data from database
ResultSet result = stat.executeQuery(query);
if (query==machine)
// what to do here
conn.close();
need some guidance
You need to create a class implementing the Validator interface. On validation fail, just throw a ValidatorException with a FacesMessage. JSF will then take care that the FacesMessage ends up in the right <h:message> associated with the input component.
You can register the custom validator to JSF by annotating it with #FacesValidator with therein the validator ID. You can reference it in <h:inputXxx validator> or <f:validator validatorId>.
Here's a kickoff example:
#FacesValidator("userValidator")
public class UserValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
// ...
if (!valid) {
String message = "Sorry, validation has failed because [...]. Please try again.";
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
}
}
}
Which is been used as follows (note: <h:inputText> does not have name attribute! instead use id; also note that your initial code snippet has some nesting which isn't making any sense):
<h:inputText id="idtext" value="#{csampleBean.id}" validator="userValidator">
<f:ajax render="idtextMessage" />
</h:inputText>
<h:message id="idtextMessage" for="idtext" />
<h:commandButton action="sample?faces-redirect=true" value="submit" />
See also:
How to perform validation in JSF, how to create a custom validator in JSF
Unrelated to the concrete problem, your JDBC code is leaking DB resources. Please fix that as well.

Struts 2 Visitor Validator with OGNL expression context

I'm having an issue using the "Visitor" validator in Struts 2. It works correctly if I hard-code the "context" parameter. The problem lies in the fact that I need this to be an OGNL expression.
For instance:
<validators>
<field name="model">
<field-validator type="visitor">
<param name="context">%{myAlias}</param>
<param name="appendPrefix">false</param>
<message />
</field-validator>
</field>
</validators>
This will call the "getMyAlias" method in my action, (which it does successfully!) which returns a String.
public class ValidationAction extends ActionSupport implements ModelDriven<ValidationModel>{
private ValidationModel xyz = new ValidationModel();
#Override
public String execute() throws Exception {
return SUCCESS;
}
#Override
public ValidationModel getModel() {
return xyz;
}
public String getMyAlias(){
return "b";
}
}
I created a validation xml file named "ValidationModel-b-validation.xml" and placed it in the package with my ValidationModel.java file. Simply changing the "%{myAlias}" to "b" results in a successful validation.
So, I know that the Visitor validator works, but just not with the OGNL expression.
Any ideas why? Google has been no help at all. It seems nobody has ever tried this.

Storing object in session - struts2

Hi I have something like this in struts.xml
<action name="LoginAction" class="controller.LoginAction">
<result name="error">/Error.jsp</result>
<result name="success">/Wizard.jsp</result>
</action>
Edited:
Upon successful execution of execute in the action the next page has data which it accesses using the request scope. How can i store the same data in session scope instead?
I read that HttpServletRequest object is passed as a parameter to the execute() method in a Struts action, and I can always retrieve the HttpSession object by using the request.getSession() and attaching data to it.
So if I am using something like this in controller.LoginAction
public String execute(HttpServletRequest req) {
...
}
Do I have to change struts.xml? execute does not get called when HttpServletRequest is added as a parameter.
<action name="LoginAction" class="controller.LoginAction">
<result name="error">/Error.jsp</result>
<result name="success">/Wizard.jsp</result>
</action>
Also is using session this way the best method ? I am trying to familiarize my self with the struts method.
You can implement SessionAware interface:
public class LoginAction extends ActionSupport implements SessionAware {
private Map session;
public String execute() {
session.put("key", "value");
// Plus any additional action code
}
// Plus setter (and optionally getter) for session map.
}
Alternate way using ActionContext is explained here.
SessionAware is preferred over ActionContext. Here are some discussions on that:
Should I get the session through SessionAware or ActionContext?
SessionAware vs ActionContext access to session - confused

In Struts2 I can't use modeldriven with validate

In the struts.xml:
<action name="User_UserFormSubmit" class="actions.UserManager">
<result name="input" >/jsp/user_form.jsp</result>
<result name="success" type="redirectAction"> success_register</result>
</action>
My class:
public class UserManager extends ActionSupport implements ModelDriven<User>{
private User user = new User();
#Override
public User getModel() {
return user;
}
public String validate() {
addActionError("blabla");
}
public String execute() {
return SUCCESS;
} ...
then in the jsp:
<s:property value="getActionErrors()"/>
I expect in the input result :
<li> blabla </li>
I succefully arrived to user_form.jsp, but the actionError does not appear
I tried without the "implements ModelDriven" and it work
The model driven erase the actionErrors (I supposed)
I want to use validate and modeldriven ¿any idea?
Not a big fan of model driven... but here is an example.
Before the example please note that using validate() does not make much sense in terms of ModelDriven. The reason is that the Model should be used over several actions and so the validation should probably be consistent. You don't use model driven just to make property names a bit shorter (to do that you use the struts2 push tag). As such validation should be done with xml as the model is bigger than any one action. Each action which uses that model uses the Visitor validator. This validator merely looks up the xml validation file for the model. The following example however will use the validate() method in the action to save time.
The following example will use the struts2-conventions-plugin to reduce the example size (adding it to your project is simply a matter of adding one jar).
create: com.quaternion.action.AddUser
package com.quaternion.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class AddUser extends ActionSupport implements ModelDriven<User>{
User user = new User();
#Override
public User getModel() {
return user;
}
#Override
public void validate(){
if (user.age != 12) {
super.addActionError("bla bla bla");
}
}
}
create: com.quaternion.action.User
package com.quaternion.action;
public class User {
public String name;
public int age;
}
create: /WEB-INF/content/add-user-input.jsp
<%#taglib prefix="s" uri="/struts-tags"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Form</h1>
<s:actionerror/>
<s:form action="add-user">
<s:textfield name="name"/>
<s:textfield name="age"/>
<s:submit/>
</s:form>
</body>
</html>
create: /WEB-INF/content/add-user-success.jsp
<%#taglib prefix="s" uri="/struts-tags"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
To test:
Add /add-user-input as the action name on your context path. If you enter an age of 12 you will get the success page, if you enter anything else you will get an action error. This has been tested to work. It is possible a typo was made, but the main thing to take away is there is an error in your application, using both conventions or xml there should be no issues with what you are doing.
You can also validate with #validations too, you have access to model driven object in the validator.
#Action(value = "save-user")
#Validations(
stringLengthFields = {
#StringLengthFieldValidator(fieldName = "name", trim = true, key = "validate.required.string.length"),
#StringLengthFieldValidator(fieldName = "age", trim = true, key = "validate.required.string.length"),
#StringLengthFieldValidator(fieldName = "address.addLine1", trim = true, key = "validate.required.string.length")
})
public String save() {

How to manually validate data in struts 2

where and how to implement the validate(){} method for validating the data on the form, in struts 2, please help me, Thanks in advance.
I got it, the validate method is delcared in the ActionSupport class and we should override it in our Action class (First we should extend the ActionSupport Class) as follows,
public class Login extends ActionSupport {
//execute method goes here
//getter/setters goes here
#Override
public void validate() {
super.validate();
System.out.println("User Name " + getUserName());
if(getUserName().length()==0)
addFieldError("userName", "User Name Required");
}
}
and also you should define your action in strus.xml as follows
<action name="DemoLogin" class="com.demo.Login">
<result name="SUCCESS">/LoginSuccess.jsp</result>
<result name="ERROR">/LoginError.jsp</result>
<result name="input">/Login.jsp</result>
</action>
here <result name="input">/Login.jsp</result> this tag is imp bcoz, if dont add this tag the filter dispathcer, wont come to know which page to render if validation-error occur.

Resources