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"/>
Related
I want to get parameters from my jsp to my servelet.
so i used input form and it works for the name and the last name but it doesn't work for my ID.
Here is the code of my JSP:
<tr>
<td><form method="post" action="ServBddInsa">
<input type="hidden" name="id" id="id" value="testId"/>
<c:out value="${ utilisateur.id }" />
</form>
</td>
<td><c:out value="${ utilisateur.prenom }" /></td>
<td><c:out value="${ utilisateur.nom }" /></td>
<td><form method="post" action="ServBddInsa">
<p>
<label for="prenom"> Prenom :</label> <input type="text"
id="prenom" name="prenom" />
<label for="nom"> Nom :</label> <input type="text" id="nom"
name="nom" />
</p>
<input type="submit" name="editer" value="editer" />
</form></td>
</tr>
</c:forEach>
and this of my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BddInsa listU = new BddInsa();
request.setAttribute("utilisateur", listU.recupererList());
this.getServletContext().getRequestDispatcher("/WEB-INF/bddinsa.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Utilisateur utilisateurs = new Utilisateur();
utilisateurs.setNom(request.getParameter("nom"));
utilisateurs.setPrenom(request.getParameter("prenom"));
utilisateurs.setId(request.getParameter("id"));
System.out.println(utilisateurs.getPrenom());
System.out.println(utilisateurs.getNom());
System.out.println(utilisateurs.getId());
BddInsa listU = new BddInsa();
listU.Editer(utilisateurs);
request.setAttribute("utilisateurs", listU.recupererList());
this.getServletContext().getRequestDispatcher("/WEB-INF/bddinsa.jsp").forward(request, response);
}
}
I get NULL when I try to see the value of id
Thank you for your help !
Please can you try to use only one open and one close form tag? I think you problem is because you have two <form method="post" action="ServBddInsa"> . So the submit button is on the second form. In this case the hidden field of the first form is not considered and it is not sent.
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;
}
I wanna know how to show all products data on the first jsp page.
I retrieved products data from the database and returned List array. And then, I don't know how to show this array in jsp.
I want to call http://localhost:8080/StrutsPrj/jsp/showAllProduct.jsp that page will show on all of the products. But I don't know how to configure that first page at the struts-config.xml and how to call related action of this page.
Please check the following code:
ShowAllProductAction :::::::
Database db = new Database();
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res){
ProductForm myForm = (ProductForm)form;
List<ProductForm> prodList = db.getProduct();
myForm.setProdList(prodList);
return mapping.findForward("success");
}
struts-config.xml ::::::
<form-beans>
<form-bean name="ProdForm" type="action.ProductForm"/>
</form-beans>
<action-mappings>
<action name="ProdForm" path="/showProduct" type="action.ShowAllProduct" scope="request" >
<forward name="success" path="/jsp/showProduct.jsp"/>
</action>
</action-mappings>
path="/showProduct" is not had in any jsp but I added this path because tag must has path. :D
showAllProduct.jsp ::::::
<logic:notEmpty name="userBean" property="searchControl">
<c:forEach var="i" begin="${userBean.begin}" end="${userBean.end}" step="1">
${userBean.prodList[i-1].productName}<br/>
${userBean.prodList[i-1].modelNo}<br/>
${userBean.prodList[i-1].brief}<br/>
${userBean.prodList[i-1].price}<br/><hr/>
</c:forEach>
</logic:notEmpty>
I've an error : java.lang.IllegalArgumentException: The path of an ForwardConfig cannot be null
What's wrong at this code?
If you don't mind, please explain me.
Thanks.
it should be
Database db = new Database();
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) {
List<ProductForm> prodList = db.getProduct();
request.setAttribute("prodList", prodList);
return mapping.findForward("success");
}
In jsp
<logic:iterate name="prodList" id="product">
<p>
<bean:write name="product" property="productName"/>
<bean:write name="product" property ="modelNo"/>
etc ...
</p>
</logic:iterate>
You should call http://localhost:8080/StrutsPrj/showProduct.do but not http://localhost:8080/StrutsPrj/jsp/showAllProduct.jsp
<c:forEach var="it" items="${sessionScope.projDetails}">
<tr>
<td>${it.pname}</td>
<td>${it.pID}</td>
<td>${it.fdate}</td>
<td>${it.tdate}</td>
<td> Related Documents</td>
<td>${it.pdesc}</td>
<form name="myForm" action="showProj">
<td><input id="button" type="submit" name="${it.pID}" value="View Team">
</td>
</form>
</c:forEach>
Referring to the above code, I am getting session object projDetails from some servlet, and displaying its contents in a JSP. Since arraylist projDetails have more than one records the field pID also assumes different value, and the display will be a table with many rows.
Now I want to call a servlet showProj when the user clicks on "View Team" (which will be in each row) based on the that row's "pID".
Could someone please let me know how to pass the particular pID which the user clicks on JSP to servlet?
Instead of an <input> for each different pID, you could use links to pass the pID as a query string to the servlet, something like:
View Team
In the showProj servlet code, you'll access the query string via the request object inside a doGet method, something like:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pID");
//more code...
}
Here are some references for Java servlets:
HttpServletRequest object
Servlet tutorials
Pass the pID along in a hidden input field.
<td>
<form action="showProj">
<input type="hidden" name="pID" value="${it.pID}">
<input type="submit" value="View Team">
</form>
</td>
(please note that I rearranged the <form> with the <td> to make it valid HTML and I also removed the id from the button as it's invalid in HTML to have multiple elements with the same id)
This way you can get it in the servlet as follows:
String pID = request.getParameter("pID");
// ...
Define onclick function on the button and pass the parameter
<form name="myForm" action="showProj">
<input type='hidden' id='pId' name='pId'>
<td><input id="button" type="submit" name="${it.pID}" value="View Team" onclick="populatePid(this.name)">
</td>
.....
Define javascript function:
function populatePid(name) {
document.getElementById('pId') = name;
}
and in the servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String pID = request.getParameter("pId");
.......
}