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.
Related
I have an application where i login and it takes me to the next page and displays a table.
I have handled session by implementing the SessionAware interface.
When i refresh the page with the refresh button on the browser or F5, it works fine. However, if i press enter on the url, it takes me to the login page because the username and password is null.
Please find below my java code and jsp code and struts.xml
JAVA class:
public String Authentication()
{
// return userInfo.getUserLoginId() + "_BUSINESS_SERVICES";
if(j_username == null)
{
status="failure3";
return status;
}
System.out.println("get username and get password" +j_username + j_password);
// if no userName stored in the session,
// check the entered userName and password
if (j_username != null && j_password != null) {
System.out.println("inside function");
// add userName to the session
sessionMap.put("j_username", j_username);
status = otlAuthenticationController.loginAuthentication(j_username,j_password);
if(status == "success")
{
this.otlUserList= otlAuthenticationController.obtainList();
System.out.println("size is"+otlUserList.size());
}
}
return status;
}
public String logout()
{
if (sessionMap instanceof org.apache.struts2.dispatcher.SessionMap) {
try {
//((org.apache.struts2.dispatcher.SessionMap) sessionMap).invalidate();
if (sessionMap.containsKey("userName")) {
sessionMap.remove(j_username);
System.out.println("session killed");
status ="success";
}
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
return "success";
}
JSP page:
<div class="label" style="margin-top:10px;"><s:text name="login.password" /></div><input id="j_password" name="j_password" type="password" placeholder="Password" size="31" autocomplete="off"/><br><br>
<div class="left" style="padding-left:150px; horizontal-align:right;text-align:center;"><input type="submit" name="login" value=<s:text name="login"/> class="button normal normal1" onClick="validate1()"/></div>
<br> <br><s:if test="status=='failure'">
<center><p style="color:RED" text-align :"center"><b> Invalid username. Please enter a valid username</b></p></center>
</s:if>
<s:if test="status=='failure2'">
<center><p style="color:RED" text-align :"center"><b> Invalid password. Please enter a valid password</b></p></center>
</s:if>
<s:if test="status=='failure3'">
<center><p style="color:RED" text-align :"center"><b> Login to the application to continue</b></p></center>
</s:if>
</div>
struts.xml:
<action name="logout" class ="com.opentext.planning.view.OTLAuthentication" method="logout">
<result name="success">/WEB-INF/index.jsp</result>
<result name="failure">/WEB-INF/error.jsp</result>
</action>
<action name ="Otl_Homepage"
class="com.opentext.planning.view.OTLAuthentication" method="Authentication">
<result name="success">/WEB-INF/Otl_Homepage.jsp</result>
<result name="failure">/WEB-INF/index.jsp</result>
<result name="failure2">/WEB-INF/index.jsp</result>
<result name="failure3">/WEB-INF/index.jsp</result>
</action>
The required parameters are in the action context, but if you are using the action, which for some reason doesn't get parameters from the params interceptor, then you still can get parameters if your action implements ParameterAware.
public class OLTAuthentication implements ParameterAware {
private Map<String, String[]> parameters;
public void setParameters(Map<String, String[]> parameters){
this.parameters = parameters;
}
public String Authentication() {
String j_username = parameters.get("j_username")[0];
String j_password = parameters.get("j_password")[0];
...
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;
}
I work with Struts 2.2.
I have iterated over an ArrayList of users. I have an edit link for each user.
When the edit link is clicked I want to find the user in a database and display its properties.
Unfortunately the link does not take me to the desired page, instead it redirects me to the same page. Any ideas?
display.jsp:
<logic:iterate id="customerElement" name="ACTIVE_PROFILES_LIST" property="list">
<tr>
<td>
<bean:write name="customerElement" property="lastName"/>
</td>
<td>
<bean:write name="customerElement" property="firstName"/>
</td>
<td>
<pdk-html:link action="/beforeEditProfile.do?toEdit=${customerElement.login}">Edit</pdk-html:link>
</td>
</tr>
</logic:iterate>
Action class:
public class BeforeBeforeEditProfileAction(){
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException,
ServletException {
// retrieve the parameter
String toModify= request.getParameter("toEdit");
SearchBean search = new SearchBean();
Cetatean cet = search.getSingleCitizen(toModify);
LogManager.info("BeforeEditProfileAction: ENTER");
if(cet!=null){
request.setAttribute("cetatean", cet);
LogManager.info("BeforeEditProfileAction: cetatean not null");
return mapping.findForward("succes");
}
else {
LogManager.info("BeforeEditProfileAction: cetatean null");
return mapping.findForward("failure");
}
}
}
struts-config.xml
<action path="/beforeEditProfile" type="pm.action.BeforeEditProfileAction" name="user" validate="true" scope="request" input="/htdocs/pages/display.jsp">
<forward name="success" path="/htdocs/pages/editProfile.jsp"/>
<forward name="failure" path="/htdocs/pages/profileEditedFailed.jsp"/>
I really new in Java....i work some research in java using tool Tapestry framework...
I have some problem with exception when i calling #Component "Form"...tapestry throws me exception :
Embedded component(s) loginForm are defined within component class com.fit.pages.Login (or a super-class of Login), but are not present in the component template (classpath:com/fit/pages/Login.tml).
context
eventType
activate
org.apache.tapestry5.ioc.internal.OperationException
Embedded component(s) loginForm are defined within component class com.fit.pages.Login (or a super-class of Login), but are not present in the component template (classpath:com/fit/pages/Login.tml).
trace
**Triggering event 'activate' on Index
Constructing instance of page class com.fit.pages.Login
Creating ComponentAssembler for com.fit.pages.Login**
my code looks something like this
public class Login {
private String userName;
#Property
private String password;
#Inject
#Property
private Users users;
#SessionState
private User user;
#Component(id="loginForm")
private Form loginForm;
#Inject
private Messages messages;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
void onValidate(){
User authenticatedUser = Security.authenticate(userName, password, users);
if(authenticatedUser != null){
user = authenticatedUser;
}else{
loginForm.recordError(messages.get("authentication-failed"));
}
}
#OnEvent
Object onSubmit(){
System.out.println("form was submited");
Class nextPage = null;
User authenticatedUser = Security.authenticate(userName, password, users);
if(authenticatedUser != null){
user = authenticatedUser;
nextPage = Index.class;
} else {
nextPage = Registration.class;
}
return nextPage;
}
and code in login.tml :
Please log in:
<t:form id="loginForm">
<table>
<tr>
<td>
<t:label t:for="userName"/>:
</td>
<td>
<input type="text" t:type="textfield" t:id="userName"
t:value="userName" t:validate="required"/>
</td>
</tr>
<tr>
<td>
<t:label t:for="password"/>:
</td>
<td>
<input type="text" t:type="passwordfield" t:id="password"
t:value="password" t:validate="required"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Log In"/>
</td>
</tr>
</table>
</t:form>
replace
<t:form id="loginForm">
with
<t:form t:id="loginForm">
I'm going to try to explain my problem as completely and shortly as I can...
A web application, made on Spring MVC 2.5 + Hibernate + Java 6 (not using annotation!).
I've got a controller extending SimpleFormController and a jsp page that is its formView and successView.
This controller should help me to insert into db an entity PracticeT that has connected (many to one) a lookup entity PracticeConfT (think about it as a "typology"). I need to choose that "typology" through a drop-down menu. In my webapp I need to be able to save data inserted and when I want, to submit the request for approval.
The page has some text fields and that drop-down menu. The bean called as default "command" is NewPracticeBean that has within a reference to an object PracticeT.
THE PROBLEM IS: I fill the form, I select a typology from the drop-down menu, I submit form and save data on DB but when I come back to the view, every property is there but the drop-down menu it is not: it has all the options allowed but no one selected. Some checks revealed that the entity PracticeConfT is null (but it has been recorded on db correctly and debugging it is still there in the model until the very end of the method onSubmit!!!).
I hope someone can help me. Thank you in advance!
Bye,
Dolfiz
Here some useful code:
(I don't think that hibernate config can be the problem, but if you need it, I can post it too)
newPractice.jsp
<form:form id="newPracticeForm" commandName="command">
<input type="hidden" name="action"/>
<spring:nestedPath path="practiceT">
<table class="table-data-form">
<tr>
<td class="left"><spring:message code="" text="Practice type" /></td>
<td>
<form:select path="practiceConfT" multiple="false">
<form:option value="" label="- seleziona -"/>
<form:options items="${practiceTypeList}" itemValue="idPracticeConf" itemLabel="practiceName"/>
</form:select>
</td>
</tr>
<tr>
<td class="left">
<spring:message code="" text="Opzione divisa" />
<br/><form:errors cssClass="errors" path="opzioneDivisa" />
</td>
<td><form:input path="opzioneDivisa" /></td>
</tr>
<tr>
<td colspan="1">
<input type="submit" name="submit" id="submit" value="Save" class="buttonEMS" style="width:100px;" />
</td>
</tr>
</table>
</spring:nestedPath>
</form:form>
NewPracticeBean.java
public class NewPracticeBean implements Serializable{
private PracticeT practiceT;
private String action;
private boolean typeSelected;
public NewPracticeBean(){
super();
this.practiceT = new PracticeT();
}
// getters & setters...
}
PracticeT.java
public class PracticeT implements java.io.Serializable {
private long idPractice;
private PracticeConfT practiceConfT;
private String opzioneDivisa;
// getters & setters...
}
PracticeConfT.java
public class PracticeConfT implements java.io.Serializable {
public static final String PRACTICE_NAME = "practiceName";
private long idPracticeConf;
private String practiceName;
// getters & setters...
}
NewPracticeController.java
public class NewPracticeController extends SimpleFormController{
protected SmartLogger log = SmartLogger.getLogger(this.getClass());
private PracticeSu practiceSu;
private ConfigurationSu configurationSu;
private HibernateEntityDataBinder practiceConfTBinder;
private HibernateEntityDataBinder practiceTBinder;
public NewPracticeController() {
setCommandClass(NewPracticeBean.class);
setCommandName("command");
}
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
log.trace("NewPracticeController -- initBinder");
super.initBinder(request, binder);
binder.registerCustomEditor(PracticeT.class, "practiceT", practiceTBinder);
binder.registerCustomEditor(PracticeConfT.class, "practiceT.practiceConfT", practiceConfTBinder);
}
#Override
protected Map referenceData(HttpServletRequest request) throws Exception {
log.trace("NewPracticeController -- referenceData");
Map model = new HashMap();
RetrieveAllEntitiesReq req = new RetrieveAllEntitiesReq();
req.setEntity(PracticeConfT.class);
req.setOrderProperty(PracticeConfT.PRACTICE_NAME);
RetrieveAllEntitiesResp resp = configurationSu.retrieveAllEntities(req);
List entitiesList = resp.getEntitiesList();
model.put("practiceTypeList", entitiesList);
return model;
}
#Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
NewPracticeBean practiceBean = (NewPracticeBean)command;
Map model = errors.getModel();
CreateNewPracticeReq req = new CreateNewPracticeReq();
req.setPracticeT(practiceBean.getPracticeT());
CreateNewPracticeResp resp = practiceSu.createNewPractice(req);
practiceBean.setPracticeT(resp.getPracticeT());
model.putAll(referenceData(null));
model.put(getCommandName(), practiceBean);
return new ModelAndView(getSuccessView(), model);
}
// setters and getters...
}
After spending some time with OptionsTag, OptionWriter and SelectValueComparator, I would say, then output of "selected" is based on Object.equals.
So if for any reason (Lazyloading...) the Object PracticeT.practiceConfT and the according Objects of model.put("practiceTypeList", entitiesList) are not the SAME (==) then forms:options will not select them as long as the equals method is not correct implemented.
So I guess you need to implement a correct equals method, even if this did not fix this problem, it is always better to have a correct equals method than a wrong or none.
Correct implemented means that it must pay attention to the fact that is used with Hibernate. (for example use if (Hibernate.getClass(this) != Hibernate.getClass(other)) instead of `if (this.getClass() != other.getClass() )