When I want to save data into database it's throws exception.
My Jsp as follows:
list.jsp
<body>
<s:form action="userActionForm">
<s:submit value="Add"/>
</s:form>
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>First Name</th>
<th>Last Name</th>
<th>Contact</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<s:iterator value="userList" status="userStatus">
<tr
class="<s:if test="#userStatus.odd == true ">odd</s:if> <s:else>even</s:else>">
<td><s:property value="fName" /></td>
<td><s:property value="lName" /></td>
<td><s:property value="contact" /></td>
<td><s:url id="editURL" action="editUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
<s:a href="logOut">LogOut</s:a>
</body>
register.jsp
<body>
<s:form action="saveOrUpdateUser" method="post">
<s:push value="userdata">
<s:hidden name="id" />
<s:textfield name="First name" label="Enter Name"/>
<s:textfield name="Lst Name" label="Enter Lst Name"/>
<s:textfield name="Contact" label="Enter Contact"/>
<s:submit />
</s:push>
</s:form>
</body>
UserAction.java
public class UserAction extends ActionSupport implements ModelDriven<UserData> {
private UserData userdata = new UserData();
private UserDAO userDAO = new UserDAOImpl();
setters & getters
#Override
public UserData getModel() {
System.out.println("userdata = ==" + userdata.getName());
return userdata;
}
public String saveOrUpdate() {
System.out.println("user data" + userdata);
userDAO.saveOrUpdateUser(userdata);
return SUCCESS;
}
}
UserDAO
public interface UserDAO
{
public void saveOrUpdateUser(UserData userData);
}
UserDAOImpl
public class UserDAOImpl implements UserDAO
{
#SessionTarget
private Session session;
#TransactionTarget
Transaction transaction;
public void saveOrUpdateUser(UserData userdata) {
try {
session.saveOrUpdate(userdata);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
Struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="hibernate-default">
<interceptors>
<interceptor name="mylogging" class="Demo.AuthenticationInterceptor"> </interceptor>
<interceptor-stack name="loggingStack">
<interceptor-ref name="mylogging" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="loggingStack"></default-interceptor-ref>
<action name="saveOrUpdateUser" method="saveOrUpdate" class="Demo.UserAction">
<result name="success" type="redirect" >list.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
</struts>
When I run the application I got exception like NullPointer Exception
java.lang.NullPointerException
at Demo.UserDAOImpl.saveOrUpdateUser(UserDAOImpl.java:36)
at Demo.UserAction.saveOrUpdate(UserAction.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
AuthenticationInterceptor:
public class AuthenticationInterceptor implements Interceptor
{
public String intercept(ActionInvocation ai) throws Exception
{
System.out.println("inside the interceptor()......new");
Map session = ai.getInvocationContext().getSession();
String name = (String) session.get("name");
System.out.println("inside the session or loginaction=" + name);
if ((session.get("name") != null) || ((session.get("name") == null))) {
System.out.println("inside the session or loginaction ");
return ai.invoke();
} else {
return "login";
}
}
}
This exception I got how to overcome I don't know
You have a logic error. I have noticed that you have a nonsense if statement that seems that it will always return true.
if ((session.get("name") != null) || ((session.get("name") == null)))
Your are checking with an or statement here ( || = OR ) the statement will be true in both cases if it is null or not.
you probably want something more along the lines of:
if (session.get("name") != null)
{
do the is NOT null actions
}else if(session.get("name") == null)
{
do the IS null actions
(probably put a warning message here to help you better diagnose null problems with your session)
}
this could be the cause of your current nullPointerException, or it might not, but either way this will fix possible problems in the future involving that statement.
Related
I have a form in JSP having two fields, and in action class I have an instance variable for each field, but those attributes are null when action class is executing.
I have used validate() method that is not even executing.
JSP
<s:form action="addAuthority">
<table>
<caption> <b><big>Add New Authority</big></b>
</caption>
<s:if test="hasActionErrors()">
<tr>
<td><s:actionerror />
</td>
</tr>
</s:if>
<s:if test="hasActionMessages()">
<tr>
<td><s:actionmessage />
</td>
</tr>
</s:if>
<tr>
<td></td>
<td>
<s:textfield name="role" label="Authority Name"></s:textfield </td>
<td></td>
<td>
<s:select name="dependentAuthority" list="#request.authorityList" label="Dependent Authority" listKey="roleId" listValue="role"></s:select>
</td>
<td>
<s:submit value="Add"></s:submit>
</td>
</tr>
</table>
</s:form>
Action
public class AddAuthorityAction extends ActionSupport {
private String dependentAuthority;
private String role;
private Map<String, Object> session;
private HttpServletRequest request;
public String execute() throws Exception{
HttpServletRequest request = ServletActionContext.getRequest();
//System.out.print(role + " " + dependentAuthority+" ");
role = request.getParameter("role");
dependentAuthority = request.getParameter("dependentAuthority");
//System.out.print(role+" "+ dependentAuthority);
//insert the data
int count = new DBInsert().addRoleDependency(role, Integer.parseInt(dependentAuthority));
if(count==0){
addActionError("There is some error while inserting. Please try again");
}else{
addActionMessage("Information successfully inserted");
}
return SUCCESS;
}
#SuppressWarnings("unchecked")
public String moveAddAuthority() {
Map request = (Map) ActionContext.getContext().get("request");
List<Role> authorityList = new DBSelect().getAuthorityId();
request.put("authorityList", authorityList);
List<Role> roleWithDependency = new DBSelect().getRoleWithDependence();
request.put("roleWithDependency", roleWithDependency);
return SUCCESS;
}
public void validate() {
if (role == null || role.trim().equals("")) {
addFieldError("role", "The name is required");
}
}
public String getDependentAuthority() {
return dependentAuthority;
}
public void setDependentAuthority(String dependentAuthority) {
this.dependentAuthority = dependentAuthority;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}}
when I am using HttpServletRequest request = ServletActionContext.getRequest(); I can get the value;
but through implementing ServletRequestAware request become null;
without using both instance variable is null;
I could not get ActionMessage in JSP page.
struts.xml
<action name="addAuthority" class="nodue.action.AddAuthorityAction"
method="execute" >
<interceptor-ref name="authonticateInterceptor"></interceptor-ref>
<result name="success" type="redirect">moveAddAuthority</result>
</action>
<action name="moveAddAuthority" class="nodue.action.AddAuthorityAction"
method="moveAddAuthority">
<interceptor-ref name="authonticateInterceptor"></interceptor-ref>
<result name="success">/authority.jsp</result>
</action>
I have made some modification on datatype of dependentAuthority previously it was Integer, and also added in JSP page the <s:if> tag.
You are probably using a single Interceptor, while you should use an entire stack with your interceptor in it.
You are returning the redirect result that should be used to reach external URLs or non-action URLs. To redirect to an action you should use redirectAction result.
No matter if redirect or redirectAction, when you redirect you lose the request parameters, and this is why you don't see action errors and messages. There are different solutions to this.
You use the validate() method, that returns INPUT result when things go south. But you haven't defined any INPUT result for your actions; be sure to understand how the INPUT result works, along with ValidationInterceptor and ParameterInterceptor.
This is my code I had written a logic to fetch the username and password from and database and after login the login time and logout time should enter into the database the time should be taken from the system
action class:
public class Login {
private String username;
private String password;
private String login_time;
private String logout_time;
private String status;
private String late;
//getters and setters
#SuppressWarnings("unused")
public String execute(ServletRequest req) throws Exception,SQLException{
int i=0;
try{
SessionUtils su = new SessionUtils();
HttpSession session =((Request) req).getSession();
String hql="select * from login where username='"+username+"'and
password='"+password+"'";
Query query1=((SessionUtils) session).createQuery(hql);
query1.setParameter(1,getUsername());
query1.setParameter(2,getPassword());
int result = query1.executeUpdate();
while(i!=0)
{
RequestDispatcher rd
=req.getRequestDispatcher("DailyInOut.jsp");
return hql;
}
} catch (Exception e)
{
return late;
}
return status;
}
public String chandu(ServletRequest req,ServletResponse res) throws
Exception,SQLException{
int j=0;
try
{
java.util.Date myDate = new java.util.Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
String strDates1 = formatter.format(myDate);
#SuppressWarnings("unused")
SessionUtils su = new SessionUtils();
String hql="update attendance where date='"+strDates1+"' name='"+username+"'
login='"+login_time+"' logout='"+logout_time+"' status='"+status+"'
late='"+late+"'";
HttpSession session =((Request) req).getSession();
Query query2=((SessionUtils) session).createQuery(hql);
session.setAttribute("date", strDates1);
session.setAttribute("login_time",login_time);
session.setAttribute("logout_time",logout_time);
session.setAttribute("status",status);
session.setAttribute("late",late);
#SuppressWarnings("unused")
int result = query2.executeUpdate();
System.out.println(" update row updated");
if(j!=0)
{
System.out.println("success1");
return "success";
}
}
catch(Exception e)
{
e.getMessage();
}
System.out.println("failure page");
return "failure";
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1//EN"
"http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<package namespace="/" name="packageOne" extends="struts-default">
<action name="login" class="com.tribro.chandu.Login" method="post">
<result name="success">DailyInOut.jsp</result>
</action>
</package>
</struts>
logina.jsp
<html>
<head>
<title>Home Page</title>
</head>
<body bgcolor="cyan" text="magenta">
<form action="login" method="execute">
<img src="WebContent/Images/java.jpg" height="80"/>
<pre><marquee behavior="scroll" direction="right"><font size="4">Welcome to TRIBRO
Limited</font></marquee><br/></pre>
<table>
<tr>
<td>
<div>
<img src="WebContent/Images/banner.png" height="300" width="900"></img>
</div>
</td>
<td>
<div>
<table>
<tr>
<td colspan="2" style="text-align:center;">
<h4>Login Form</h4>
</td>
</tr>
<tr>
<td>
<h4>Username :</h4>
</td>
<td>
<h4><input type="text" name="Username"/></h4>
</td>
</tr>
<tr>
<td>
<h4>password:</h4>
</td>
<td>
<h4><input type="password" name="password"/></h4>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<input type="submit" value="Login"/>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
But I am getting an error as
java.lang.NoSuchMethodException: com.tribro.chandu.Login.post()
but I am getting java.lang.NoSuchMethodException: com.tribro.chandu.Login.post()
This makes me think you have written method="post" a <s:submit/> tag (or in struts.xml):
<s:form action="login">
<s:submit method="post" />
</s:form>
where method refers to an Action method, not to an HTTP method (like in <s:form />).
Then remove method from the submit tag, and leave it on the form:
<s:form action="login" method="post">
<s:submit />
</s:form>
if i used this tag i am getting the Exception as java.lang.NoSuchMethodException: com.tribro.chandu.Login.execute()
You are putting parameters in your Action methods:
public String execute(ServletRequest req) throws Exception,SQLException{
this is not how it works, Action methods have no arguments, the parameters are passed through getters and setters, including ServletRequest and ServletResponse (read more here).
Then rewrite your methods as:
public String execute() throws Exception{
and they will be found by Struts.
When you submit a form it has an incorrect method
<form action="login" method="execute">
In the action mapping you have configured the method post() will be mapped to the login action. But, your action class doesn't have such method. If you change this mapping to
<action name="login" class="com.tribro.chandu.Login">
this will map to the execute() method by default. This method you should create in the action class. It has different signature which has not any parameters.
If you need to know how to get servlet objects such as HttpServletRequest then you can read this answer.
You can get the request from the action context like
HttpServletRequest request = ServletActionContext.getRequest();
That way is useful in interceptors, but in action better to implement ServletRequestAware
protected HttpServletRequest request;
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
from so many days i am trying to get this done,but m failing.
Have a look at my jsp once below:
Here i have one table and all each row i have refresh icon,i want to refresh individual row when clicked the icon.
onclick i am calling a function-> refreshRecord(value); value(parameter) is the fileid(unique)->i.e the first column of the table i am passing as a parameter to the function.
ajax is calling the checkStatusAndNumRecs aciton with the fileId,in action class i am calling my JPA method to get data from the database,its reading the row with that fileId what i have passed and putting it in JSONObject.
In jsp in ajax part its executing suuccess some time and error its executing most of the time,
when it is success,inside success part ,its failing to execute this line->var obj = jQuery.parseJSON(eval(data));
that means some times data is returning to ajax sometimes data is not coming back to ajax from action class.
THis is my jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>File Upload</title>
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/style1.css" />
<link rel="stylesheet" type="text/css" href="css/button.css" />
<link href="css/common-style.css" rel="stylesheet" type="text/css" />
<style>
a{
color:white;
text-decoration:none;
}
</style>
<script type="text/javascript">
var id;
function refreshRecord(value)
{
id = value;
}
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
alert(data);
var obj = jQuery.parseJSON(eval(data));->THis statement is not executing
aler("after JSON OBJECT"+obj.status);
$("#div1").html(obj.status);
$("#div2").html(obj.records);
},
error:function(data)
{
$("#div1").html("It was a failure !!!");
}
});
});
});
</script>
</head>
<body>
<%#include file="index1.html" %>
<div class="box2">
<div class="box3">
<s:property value="userId"/>
</div>
<center><h2>FILE STATUS</h2></center>
<center>
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Upload your file:</label>
<input type="hidden" name="upload" value="upload"/>
<input type="file" name="myFile" size="40" class="file"/>
<input type="submit" value="Upload" class="button"/>
<input type="submit" value="Refresh" class="button"/>
</form>
</center>
<center>
<s:if test="%{user.roles == 'admin'}">
<form action="manage" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Click to manage service providers:</label>
<input type="submit" value="Manage" class="button"/>
</form>
</s:if>
</center>
<center>
<table border="1" class="displaytab" id="rtable">
<s:if test="%{user.roles == 'admin'}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center>Admin</center></td></tr>
</s:if>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="uploadList" var="m">
<tr>
<td><s:property value="%{#m.fileId}" /></td>
<td><s:property value="%{#m.fileName}" /></td>
<td><s:property value="%{#m.uploadDate}" /></td>
<td><div id="div2"><s:property value="%{#m.numRecords}" /></div></td>
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"></td>
<td><img src="images/refresh.png" title="Refresh" id="refresh" onclick="refreshRecord(<s:property value="%{#m.fileId}" />);"></td>
<s:if test="%{user.roles == 'admin'}">
<td><img src="images/details.png">
<img src="images/plus.png" title="Add Instance">
<img src="images/minus.png" title="Remove Instance">
<img src="images/download.png" title="Download">
<img src="images/reconnect.png" title="Reconnect"></td>
</s:if>
</tr>
</s:iterator>
</table>
</center>
<br>
<br>
<br>
<br>
<center>
<s:if test="%{user.roles == 'admin'}">
<!-- <select name="user names">
<s:iterator value="userNamesList">
<option value="emailColumn" > <s:property/>
</option>
</s:iterator>
</select> -->
<table border="1" class="displaytab" id="usertab">
<s:if test="%{uploadListMap.size() != 0}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;">User Job Details</center></td></tr>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="%{uploadListMap}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center><s:property value="key"/></center></td>
<s:iterator value="value" var="u">
<tr>
<td><s:property value="%{#u.fileId}" /></td>
<td><s:property value="%{#u.fileName}" /></td>
<td><s:property value="%{#u.uploadDate}" /></td>
<td><s:property value="%{#u.numRecords}" /></td>
<td><s:property value="%{#u.status}" /></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"></td>
<td><img src="images/refresh.png" title="Refresh" id="refresh" onclick="refreshRecord(<s:property value="%{#u.fileId}" />);"></td>
<td><img src="images/details.png">
<img src="images/plus.png" title="Add Instance">
<img src="images/minus.png" title="Remove Instance">
<img src="images/download.png" title="Download">
<img src="images/reconnect.png" title="Reconnect"></td>
</tr>
</s:iterator>
</tr>
</s:iterator>
</s:if>
</table>
</s:if>
</center>
</div>
</body>
</html>
This is my action class:
p
ackage com.mxui;
import com.mxui.db.api.PersistenceService;
import com.mxui.db.service.*;
import org.json.simple.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
public class checkStatusAndNumRecsAction extends ActionSupport
{
/**
*
*/
private String status;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
private long numRecords;
public long getNumRecords()
{
return numRecords;
}
public void setNumRecords(long numRecords)
{
this.numRecords= numRecords;
}
private String fileId;
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
public String execute()
{
JSONObject obj = new JSONObject();
System.out.println("here inside action-------------");
PersistenceService svc = PersistenceServiceImpl.getInstance();
status = svc.getStatusByFileId(fileId);
System.out.println("status is "+status);
numRecords = svc.getNumRecordsByFileId(fileId);
System.out.println("num records are "+numRecords);
obj.put("status", status);
obj.put("records", numRecords);
System.out.print("json data is "+obj);
return "SUCCESS";
}
}
Please guide me in this ,i am struggling for this from so many days,and also i am new to ajax.
Thankyou in advance.
This is my struts.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<constant name="struts.multipart.maxSize" value="1000000" />
<result-type name="json" class="org.apache.struts2.json.JSONResult" default="false" />
<package name="struts" extends="struts-default">
<action name="RegisterationProcess" class="com.mxui.RegisterationFormAction">
<result name="SUCCESS">registerationform.jsp</result>
<result name="customerRegister">successregisteration.jsp</result>
</action>
<action name="CheckUserValidation" class="com.mxui.CheckUserAction">
<result name="SUCCESS">noofrows.jsp</result>
</action>
<action name="ProcessLogin" class="com.mxui.LoginAction">
<result name="LOGIN" >login.jsp</result>
<result name="REGISTER">registerationform.jsp</result>
<result name="ERROR" type="redirect">login.jsp</result>
<result name="FILEUPLOAD" type="redirect">Upload</result>
</action>
<action name="Upload" class="com.mxui.UploadFileAction">
<result name="SUCCESS">fileupload.jsp</result>
<result name="LOGINERROR" type="redirect">ProcessLogin</result>
<result name="PREVIEW" type="redirect">FilePreviewAction</result>
<result name="ERROR">error.jsp</result>
</action>
<action name="FilePreviewAction" class="com.mxui.FilePreviewAction">
<result name="SUCCESS">filepreview.jsp</result>
<result name="JOBCREATED" type="redirect">Upload</result>
<result name="ERROR" type="redirect">ProcessLogin</result>
</action>
<action name="ServiceProviderProcess" class="com.mxui.ServiceProviderAction">
<result name="SUCCESS">CreateProvider.jsp</result>
<result name="serviceprovider" type="redirect">Upload</result>
</action>
<action name="UpdateServiceProviderProcess" class="com.mxui.UpdateServiceProviderAction">
<result name="SUCCESS">updateserviceprovider.jsp</result>
<result name="updated" type="redirect">Upload</result>
</action>
<action name="manage" class="com.mxui.ManageServiceProviderAction">
<result name="SUCCESS">manageserviceprovider.jsp</result>
</action>
</package>
<package extends="struts-default,json-default" name="name" namespace="">
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
<action name="checkStatusAndNumRecs" class="com.mxui.checkStatusAndNumRecsAction" method="execute">
<result type="json"></result>
</action>
</package>
</struts>
In JSP Page
$.ajax({
type: 'POST',
url: 'checkStatusAndNumRecs',
data:{fileId:fileId},
dataType: 'json',
async: false ,
contentType: 'application/json; charset=utf-8',
success: function(data){
alert(data);
var obj = jQuery.parseJSON(eval(data));->THis statement is not executing
alert("after JSON OBJECT"+obj.status);
$("#div1").html(obj.status);
$("#div2").html(obj.records);
},
error:function(data)
{
$("#div1").html("It was a failure !!!");
}
});
});
});
Struts.xml
Define a global result as
<result-type name="json" class="org.apache.struts2.json.JSONResult" default="false" />
For the action
<package extends="struts-default,json-default" name="name" namespace="">
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor" />
<action name="YouAction" class="YourActionClass" method="executeMethod">
<result type="json"></result>
</action>
</package>
Is there any alternative validation framework while building complex web app? Or any guide for validation. Links to example is not required as it working on simple Form but not in complex Form with multiple links.
This is my action class
package com.tpc.action;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.tpc.domain.LeadFacultyModel;
import com.tpc.service.LeadFacultyServiceInterface;
public class LeadFacultyAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private LeadFacultyModel leadFacultyModel;
private String lead_faculty_formAction;
// Injecting leadFacultyServiceImpl bean
LeadFacultyServiceInterface leadFacultyServiceImpl;
//variable to store the action message to pass to other pages through get request
private String action_msg = null;
private List<LeadFacultyModel> leadFacultyModelList = new ArrayList<LeadFacultyModel>();
public String execute() throws Exception {
return SUCCESS;
}
public String formAction() throws Exception
{
if(lead_faculty_formAction.equals("Save"))
{
System.out.println("Inside Update");
return this.updateLeadFaculty();
}
else if(lead_faculty_formAction.equals("Submit"))
{
System.out.println("Inside Save");
return this.saveLeadFaculty();
}
else if(lead_faculty_formAction.equals("Delete"))
{
System.out.println("Inside Delete");
return this.deleteLeadFaculty();
}
else
{
return SUCCESS;
}
}
public String saveLeadFaculty() throws Exception {
boolean result =leadFacultyServiceImpl.createLeadFaculty(leadFacultyModel);
if(result == true)
{
addActionMessage(getText("message.save_success"));
return "SAVE_SUCCESS";
}
else {
addActionError(getText("message.save_error"));
return "SAVE_ERROR";
}
}
public String viewAllLeadFaculty(){
// TODO Auto-generated method stub
System.out.println("view all method is called");
try{
leadFacultyModelList = leadFacultyServiceImpl.getAllLeadFaculty();
System.out.println("Action page "+leadFacultyModelList.size());
return SUCCESS;
}catch(Exception ex){
ex.printStackTrace();
return ERROR;
}
}
//Section of getter/setter methods in this class
public void setLeadFacultyModel(LeadFacultyModel leadFacultyModel) {
this.leadFacultyModel = leadFacultyModel;
}
public LeadFacultyModel getLeadFacultyModel() {
return leadFacultyModel;
}
public String getLead_faculty_formAction() {
return lead_faculty_formAction;
}
public void setLead_faculty_formAction(String lead_faculty_formAction) {
this.lead_faculty_formAction = lead_faculty_formAction;
}
public void setLeadFacultyServiceImpl(
LeadFacultyServiceInterface leadFacultyServiceImpl) {
this.leadFacultyServiceImpl = leadFacultyServiceImpl;
}
public void setAction_msg(String action_msg) {
this.action_msg = action_msg;
}
public List<LeadFacultyModel> getLeadFacultyModelList() {
return leadFacultyModelList;
}
public void setLeadFacultyModelList(List<LeadFacultyModel> leadFacultyModelList) {
this.leadFacultyModelList = leadFacultyModelList;
}
public String getAction_msg() {
return action_msg;
}
}
This is LeadFacultyAction-validation.xml:
<!DOCTYPE validators PUBLIC "-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="leadFacultyModel.lead_string_FacultyName">
<field-validator type="requiredstring">
<message>Name is required.</message>
</field-validator>
</field>
</validators>
this is struts.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<package name="default" extends="struts-default">
<!-- /** defining result types for implementing tiles **/ -->
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<global-results>
<result name="error">/404_error.jsp</result>
</global-results>
<action name="">
<result></result>
</action>
<action name="baseTemplate" >
<result type="tiles">baseTemplate</result>
</action>
<action name="setup_lead_faculty">
<result type="tiles">setup_lead_faculty</result>
</action>
<action name="setup_LeadFacultyAction" class="com.tpc.action.LeadFacultyAction" method="formAction">
<result name="SAVE_SUCCESS" type="tiles">setup_lead_faculty</result>
<result name="UPDATE_SUCCESS" type="tiles">setup_lead_faculty</result>
<result name="DELETE_SUCCESS" type="tiles">setup_lead_faculty</result>
<result name="SAVE_ERROR" type="tiles">setup_lead_faculty</result>
<result name="UPDATE_ERROR" type="tiles">setup_lead_faculty</result>
<result name="DELETE_ERROR" type="tiles">setup_lead_faculty</result>
<result name="input" type="tiles">setup_lead_faculty</result>
</action>
<action name="setup_LeadFaculty_list_view_Action" class="com.tpc.action.LeadFacultyAction" method="viewAllLeadFaculty">
<result type="tiles" name="success">setup_lead_faculty_list_view</result>
</action>
<action name="setup_LeadFacultyAction_selected_from_list" class="com.tpc.action.LeadFacultyAction" method="getByIdLeadFaculty">
<result type="tiles" name="success">setup_lead_faculty</result>
</action>
</package>
This is my JSP file:
<%# 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"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<c:set value="/lms/" var="baseUrl" />
<s:form method="post" action="setup_LeadFacultyAction">
<div class="buttontab">
<input type="submit" name="lead_faculty_formAction" value="Save"
class="form_button" /> <input type="submit"
name="lead_faculty_formAction" value="Submit" class="form_button" />
<input type="submit" name="lead_faculty_formAction"
value="Delete" class="form_button" /> <input
type="submit" name="lead_faculty_formAction" value="Reset" disabled="disabled"
class="form_button" /> <span class="span"
style="float: right;"> <i><a href="${baseUrl}lead/setup_LeadFaculty_list_view_Action"> <img
src="${baseUrl}icons/gridview.png" width="12px" height="12px" /></a> </i> </span>
<span class="span" style="float: right;"> <i><img
src="${baseUrl}icons/formview.png" width="12px" height="12px" /> </i> </span>
<span class="span" style="float: right;"> <i><img
src="${baseUrl}icons/tileview.png" width="12px" height="12px" /> </i> </span>
</div>
<div id="content_wrap">
<div class="unidiv1">
<s:if test="hasActionErrors()">
<div class="errors">
<s:actionerror/>
</div>
</s:if>
<s:if test="hasActionMessages()">
<div>
<p><s:actionmessage/></p>
</div>
</s:if>
<s:if test="hasFieldErrors()">
<div>
<p><s:fielderror/></p>
</div>
</s:if>
<div class="field_wrapper">
<div class="left_box">
<label>ID</label>
</div>
<div class="right_box">
<input type="text" name="leadFacultyModel.lead_string_FacultyId" value="${leadFacultyModel.lead_string_FacultyId}"
class="input_id" />
</div>
</div>
<div class="field_wrapper">
<div class="left_box">
<label>Faculy</label>
</div>
<div class="right_box">
<input type="text" name="leadFacultyModel.lead_string_FacultyName" value="${leadFacultyModel.lead_string_FacultyName }" />
</div>
</div>
<div class="field_wrapper">
<div class="left_box">
<label>Remarks</label>
</div>
<div class="right_box">
<textarea name="leadFacultyModel.lead_string_FacultyRemarks"
class="textarea_address">${leadFacultyModel.lead_string_FacultyRemarks}</textarea>
</div>
</div>
</div>
</div>
The difference is only if Struts discover validation annotations while intercepting the action it processes those annotations to perform validations by applying validation rules exposed by annotations. The same thing is when parsing -validation.xml. You can use both validation methods xml based and annotation based together, or with addition to custom validation (excluding custom validators).
For example, if I have a phone field and I want to validate it is not empty and contains a predefined format I will just put two annotations on it.
private String phone;
public String getPhone() {
return phone;
}
#RequiredStringValidator(type= ValidatorType.FIELD, message="Phone required.")
#RegexFieldValidator(type= ValidatorType.FIELD, message="Invalid Phone",
regexExpression="\\([0-9][0-9][0-9]\\)\\s[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]")
public void setPhone(String phone) {
this.phone = phone;
}
then I have an execute action I don't want to validate
#SkipValidation
public String execute() throws Exception {
then I have another action save that I want to validate questions but I don't want to validate a phone.
private String myQuestionq1;
private String myQuestionq2;
public String getMyQuestionq1() {
return myQuestionq1;
}
public void setMyQuestionq1(String myQuestionq1) {
this.myQuestionq1 = myQuestionq1;
}
public String getMyQuestionq2() {
return myQuestionq2;
}
public void setMyQuestionq2(String myQuestionq2) {
this.myQuestionq2 = myQuestionq2;
}
#Action(value="save", results = {
#Result(name="input", location = "/default.jsp"),
#Result(name="back", type="redirect", location = "/")
},interceptorRefs = #InterceptorRef(value="defaultStack", params = {"validation.validateAnnotatedMethodOnly", "true"}))
#Validations(requiredFields = {
#RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "myQuestionq1", message = "You must enter a value for field myQuestionq1."),
#RequiredFieldValidator(type = ValidatorType.FIELD, fieldName = "myQuestionq2", message = "You must enter a value for field myQuestionq2.")
})
public String save() throws SQLException {
this will execute only validators on this action.
More examples you could always find on Apache web site:
Validation using annotations examples.
I have a jsp page and struts 2 Action class . When I submit the form in the jsp , I am getting null values into the action.
The JSP code looks like :
<s:form id="user" name="user" action="initUserAdmin">
<s:textfield name="userName" cssClass="txtbox" size="30" />
<div class="btn"><a href='<s:url action="searchUserAdmin"/>'
title="Search" id="button" class="btn" ><span>Search</span></a></div>
</s:form>
The struts.xml has this part
<action name="*UserAdmin" method="{1}" class="com.mphasis.im.web.action.UserAction">
<result name="init" type="tiles">user</result>
<result name="search" type="tiles">user</result>
<result name="reset" type="tiles">user</result>
<result name="createNew" type="tiles">createNewUser</result>
</action>
And the Action class has this :
public class UserAction extends BaseAction
{
public String userName;
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public String search()
{
searchProcessed = true;
System.out.println("******** inside search ******");
System.out.println("username = "+ userName);
return TilesConstants.SEARCH;
}
And the output comes as below when I type a string in the text box in jsp page.
******** inside search ******
username = null
What might be the problem ? Am I missing something ?
<a href='<s:url action="searchUserAdmin"/>'
title="Search" id="button" class="btn" >
It's just a href to the URL of action and with no parameter. Therefore, the 'userName' in the action is null.
<s:form id="user" name="user" action="initUserAdmin">
<s:textfield name="userName" cssClass="txtbox" size="30" />
<div class="btn"><a href='javascript:submitme()'
title="Search" id="button" class="btn" ><span>Search</span></a></div>
</s:form>
Javascript
function submitme(){
document.user.submit()
}
Also in the action mapping you provided the action name you are using there is UserAdmin whereas in the form action you are using initUserAdmin.They must be the same