How to process the value from a a:href - java

I have a JSP page:
<table width="40%" cellpadding="5" bordercolor="#000066"
bgcolor="#FFFFFF" border="1" cellspacing="0">
<c:forEach var="contactInfo" items="${contactsList}">
<tr>
<td><div align="center">
<b><a href="requestDelete.jsp? id=${contactInfo.userID}">
<c:out value="${contactInfo.contactName}"/></a></b>
</div></td>
</tr>
While clicking the link, i need to obtain the user_id, so that i can load details from the mysql db by passing the user_id and the details will be displayed in the requestDelete.jsp.
How to get the user_id in my servlet class after clicking the link.. or i need to redirect the action to my servlet class...from there i can call the response page requestDelete.jsp
Please help..

<c:outvalue="${conatctInfo.contactName}"/>
This will create link like for example
requestDelete.jsp?id=50
Now you want this to be passed to some servlet so lets create one servlet, currently this will create a GET to jsp.
Create a servlet
Map it to some url pattern lets say /deleteUser
and modify your hyperlink to produce
/deleteUser?id=50
and in servlet's doGet()
long id= request.getParameter("id");
// some validation ans checks..
// call service to delete ..

Related

How to catch a table in POST and use it as an array

so basically to lay this out I have
AffidavitController - Controller
Affidavit.jsp - GET view page
summary.jsp - POST view page
so basically I have a form that a user fills out and then they hit the submit button and it posts it.
This method is then called in the controller
#RequestMapping(value = "/affidavit", method = RequestMethod.POST)
public String post(AffidavitDetailDto affidavitDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
now within this method I catch the information that was passed over in the response object.
an example of this is I have a name field on the GET view page and the name of this field is 'custName'
so I catch it like so
String contactName = request.getParameter("custName");
model.addAttribute("contactName", contactName);
and then I can display it on my POST view page
<p>Name: ${contactName}</p>
but now I am trying to figure out how I can do the same with a table and treat it like an array
the following is how it is added on the GET view page
<table id="certEmail" name="certEmail">
<tr>
<td>${user.email}</td>
</tr>
</table>
the following is what I have attempted
String[] certEmail = request.getParameterValues("certEmail");
model.addAttribute("certEmail", certEmail);
and this is what I have on the view page to display it
<div id="Emails">
<c:forEach items="${certEmail}" var="email">
<p>${email}</p>
</c:forEach>
</div>
this does not currently work. I know I am probably just doing it wrong so can someone please at least point me in right direction. I just haven't figured out a good google query yet to get an answer.
Table is not a form element (https://www.w3schools.com/html/html_form_elements.asp). Only form element values on form are submitted to server. So instead of
<table id="certEmail" name="certEmail">
<tr>
<td>${user.email}</td>
</tr>
</table>
You should have something like
<table id="certEmail">
<tr>
<td>
<input type="text" name="certEmail" value="${user.email}" />
</td>
</tr>
</table>
if you want your data to be editable, or
<table id="certEmail">
<tr>
<td>
${user.email}
<input type="hidden" name="certEmail" value="${user.email}" />
</td>
</tr>
</table>
if you want it to be hidden and just resent to the server.
While I should denote that second variant generally should be avoided. I would recommend you to pass the user id and use it in back-end to load user and read his email.
Please learn how to use HTML forms: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Your_first_HTML_form

calling jsp file from servlet

i have three servlet. In first servlet i have Request Dispatcher so it is redirect to my Dynamic List.jsp file. The jsp file contains
<div class='feedItem'> <c:out value="${feed.tagRuleType}"> </c:out> </div>
<div class='feedItem'><input type="submit" value="Update" onClick="updateRows(${feed.configId})"></div>
<div class='feedItem'><input type="submit" value="Delete" onClick="deleteRows(${feed.feedId})"></div>
When i click on the update button i can able to call the servlet through javascript. Inside servlet i am using Request Dispatcher:
RequestDispatcher dispatcher = request.getRequestDispatcher("/FeedUpdate.jsp");
dispatcher.forward(request, response);
But it is not redirecting to FeedUpdate.jsp file
It is iterating the list object. Inside the tag i added update button. so when i click update button corresponding row id i will get for updating a record.
When i click the button i can able to call servlet and the get the id. when i redirect to the jsp page using Request Dispatcher inside the servlet it is not redirecting to jsp page.
Can anyone the give the suggestion why it is not redirecting to jsp file.
if you have used Jquery Ajax call to call your servlet, your dispatcher forward won't work. You may want do the redirect in the success method of Ajax:
jQuery.ajax({
type:"POST",
url : "servlet",
data : param,
success : function(data) {
windows.location.href='/myservlet?id='+data;
});
So basically you want to call other method in another JSP and takes id as the parameter, if yes, then you can do it this way :
<h3>Sections List</h3>
<c:if test="${!empty listSections}">
<table class="tg">
<tr>
<th width="80">Section ID</th>
<th width="120">Section name</th>
<th width="120">Section size</th>
<th width="120">Section position</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${listSections}" var="section">
<tr>
<td>${section.sectionid}</td>
<td>${section.sectionname}</td>
<td>${section.sectionsize}</td>
<td>${section.sectionposition}</td>
<td><a href="<c:url value='/editsection/${section.sectionid}' />" >Edit</a></td>
<td><a href="<c:url value='/removesection/${section.sectionid}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
The method editSetion and RemoveSection can be in different JSP files as well, depends how you have mapped it. Is this what you are looking for? I cannot understand exactly what you want, as you have not provided much information, no code too.. Please add more code and properly explain if this is not what you expected.

Why is my post not give data to my controller from my form?

I am developing a Sprin MVC application and I have a form containing a table in one of the UI jsp's, (welcome.jsp) and when the submit button is clicked, I am trying to print out the data in the form to the web applications console.From there i intend to parse the checkboxes that are selected and then have the controller send the 'selected' data back to the databased to be updated to the next status in the applications flow.
So far the form is 'successfully' posting as in no error or exceptions is being thrown, but the printed statement in the console is blank which makes me think that no data is being sent, and I would greatly welcome any help to fix this.
Here is the setup of what I have, not the actual code but a rough set up of the elements and methods.
welcome.jsp:
<form action="<c:url value="/postPage" />"method="post" modelAttribute="rTable">
<br/>
<table>
<thead>
<tr>
<th>title1</th>
<th>title2</th>
<th>title3</th>
<th><select>
<option>option1</option>
<option>option2</option>
</select></th>
</tr>
</thead>
<tbody>
<tr>
<td>value1</td>
<td>value1</td>
<td>value1</td>
<td><input type="checkbox" value="row_data_id" /></td>
</tr>
</tbody>
<tfoot>
<tr><td colspan="4"></td>
</tfoot>
</table>
<br/>
</form>
My controller has the following method in it with all the necessary libraries imported:
controller.java
#RequestMapping(value="/postPage", method = RequestMethod.POST)
public String processUpdate(#ModelAttribute("rTable") String table, ModelMap model) {
System.out.println(table);
return "postPage";
}
The console line that is print is this:
.
.
.
[3/19/14 16:36:53:625 EDT] 0000006a SystemOut O
.
.
.
Does anyone know why this is not printing anything? Am I really not successfully sending anything to the controller?
After a good deal of reading and trial and error I found my answer. I will explain in terms with spring framework forms. In order to pass data through the form from front-end to back end, first every input will need to be tied to the form using the spring form JSTL tag
ex.
form => form:form
input=> form:input
in the form:form it isn;t necessary but you should have a modelAttribute that is linked to a java class, then in each input their need to be a path attribute the is linked to a variable in the modelAttribute class and a value to assign to the variable. Then on a submit the values are linked to the back end via the getters and setters on the java class to be used in the back-end. I hope I am explained that clearly.

How can I delete database records from a jsp page?

The following code is a part of my project and the output of this code is that I get all the title of the posts in the database and a delete hyperlink in front of all enteries. When I click delete for a respective title it should be deleted from jsp page. How to write code for this?
<label><h3>Post published:</h3></label>
<%
rs = stmt.executeQuery("select title from Postdata");
%>
<table id="rounded-corner" summary="all posts">
<tbody>
<% while (rs.next()) {%>
<tr>
<td>
<%=rs.getString(1)%>
</td>
<td>
<a href><%=""%>Delete</a>
</td>
</tr>
<%}%>
</tbody>
</table>
Firstly you really want to use JSTL instead of 'raw' java in JSP files.
And, like the previous commenter already mentioned, you would put this
logic nowadays in a servlet/controller.
If you really like to do this with an jsp, the code should look something like this (using jstl):
<sql:setDataSource var="ds" ... />
<c:set var="title" value="${param['title']}"/>
<sql:update dataSource="${ds}">
DELETE FROM Postdata where title = ?
<sql:param value="${title}" />
</sql:update>
Where you create the link as following:
<td>Delete</td>
Create a POST form with the record ID as hidden input value and a submit button. I assume that your table has an id column and that you've selected it as well.
<form action="delete" method="post">
<input type="hidden" name="id" value="<%=rs.getLong("id")%>" />
<input type="submit" value="Delete" />
</form>
In the servlet (or JSP if you really need it to be), just grab the ID as request parameter
String id = request.getParameter("id");
Then just do your JDBC thing.
preparedStatement = connection.prepareStatement("DELETE FROM PostData WHERE id = ?");
preparedStatement.setLong(1, Long.valueOf(id));
preparedStatement.executeUpdate();
Unrelated to the concrete problem, putting Java code in a JSP file is considered a poor practice, for sure if it is database interaction code. I suggest to invest some time in learning servlets.
See also:
Our Servlets wiki page
How to avoid Java code in JSP files?
The ideal way to do this is to move all logic to a Servlet. This method I mention below is not recommended for many reasons you will learn as you gain more experience. However for now let us assume you are going to use only JSPs. There are many ways to do this, but this is one of the ways.
This method uses two JSPS, first JSP to display the records. The second JSP is a processing JSP which will do the deleting for you.
More in the detail below.
The first JSP will display the records.
The second JSP is invoked when you click on "delete".
The second JSP would delete the record and then redirect back to the first JSP. This is a very inefficient way to do this and is not recommended. But it is quick and dirty and will save you time from creating Servlets, Java files etc.
JSP1.jsp will have the same code as you posted. retrieve the primary key of the record as well. This will be used to identify the record that needs to be deleted.
This id will be passed as a parameter to the second JSP.
<%
rs = stmt.executeQuery("select primary_key_id, title from Postdata");
%>
<table id="rounded-corner" summary="all posts">
<tbody>
<% while (rs.next()) {
String primaryKey = rs.getString(1);
%>
<tr>
<td>
<%=rs.getString(2)%>
</td>
<td>
Delete
</td>
</tr>
<%}%>
</tbody>
</table>
JSP2.jsp
retrieve the parameter from the request. Then execute the Delete query for that id.
Then redirect back to JSP1.
<%
String recordToDelete = request.getParameter("deleteid");
// Use PreparedStatements here instead of Statment
rs = stmt.executeQuery("delete from Postdata where primary_key_id="+ recordToDelete );
response.sendRedirect("JSP1.jsp"); // redirect to JSP one, which will again reload.
%>
This method is not recommended, but you get an idea what needs to be done.

Updating the value of a iterator tag in struts2

I have a jsp in which I have a drop down as
<s:select name="newQuestion.CertificationId" list="certificationList"
listKey="certificationId" listValue="certificationName"
headerKey="" headerValue="Select Certification"
label="Certification Name"
onchange="getQuestionsList(this.value)" />
When the dropdown value changes I can getQuestionsList. In the javascript function I submit to an action class where I modify the value of a questionList which is displayed in my JSP via an iterator.
The values of the questionList contain all questions and when I select a value from the above drop down I need to populate only those questions which belong to the id selected in the drop down. (I query the DB to load the questions in action class.)
Initially when the page is loaded I have all questions in questionList but after selecting a value from drop down I have the updated questions in the action class.
For displaying the values of question list I use a iterator tag
<div id="questionDetails" class="registrationDetails" style="display: none;">
<span><b>Question List</b></span>
<br>
<table class="registrationDetailsTable">
<tr class="tabledataheader">
<td>Question Id</td>
<td>Question Description</td>
</tr>
<s:iterator value="questionList">
<tr class="tabledatarow">
<td><s:property value="questionId" /></td>
<td><s:property value="questionDesc" /></td>
</tr>
</s:iterator>
</table>
</div>
The div is initially hidden and on select of a value in drop down I need to display the values of questionList which is taking old values as the page is not reloaded.
When I again come back to this jsp I am not seeing the new value as it is not getting updated.
Any heads up please
Why don't you try Struts2 Jquery Plugin. Here is the showcase with code.
What you need is
<sj:select ...> tag.
Let me know if you still need an example.
You would need to make few changes to the code. Let me list them down:
Move the following part in your initial JSP to another jsp, say questionList.jsp. The below part should be the only thing which should be inside the newly created jsp.
<span><b>Question List</b></span>
<br>
<table class="registrationDetailsTable">
<tr class="tabledataheader">
<td>Question Id</td>
<td>Question Description</td>
</tr>
<s:iterator value="questionList">
<tr class="tabledatarow">
<td><s:property value="questionId" /></td>
<td><s:property value="questionDesc" /></td>
</tr>
</s:iterator>
</table>
In your main page, you would need to replace the above code part with
<jsp:include page="questionList.jsp" flush="true"/>
Now deploy and see if everything is in place as before.
In your getQuestionsList() javascript function, make an ajax call to another action mapping say showQuestionList.action?certification=12. Here, 12 will be the id of the certification, which you will handle in the action. If you use certification as an action property, add a variable with the same name with getter and setter methods.
In your action method say showQuestionList(), retrieve the questionList and assign to the action variable.
On return of SUCCESS of the above method, the result should send only questionList.jsp. This will have the part to list just the necessary fields.
In the getQuestionsList() javascript function, after the ajax call being success, get the data and put it into the div with id questionDetails.
Show the div.

Categories