I have dynamically created buttons.
<form action="/" method="post">
<table cellpadding="4">
<%
List<Room> rl = (List<Room>) request.getAttribute("roomList");
if(rl != null) {
for (Room r : rl) {
String name = r.getName();
%>
<tr>
<td><%=name%></td>
<td><input type="submit" value="Add a Booking" name=<%=name%> /></td>
</tr>
<%
}
}
%>
</table>
I know which button was clicked with the following code;
String addButton = req.getParameter("addButton");
However, in this situation, I am not able to know the name of the button. Because the name of the button could be anything. How could I know which button was pressed? Thanks in advance!
You can possibly have at least two solutions:
1. Solution in Java code on the server side
in JSP each of the submit button will be named with the submit_ prefix
<input type="submit" value="Add a Booking" name=<%="submit_"+name%> />
When request is send to the server you will loop parameters and search for one with this prefix, saving its value to submit attribute:
private void setSubmitValue(HttpServletRequest request) {
String SUBMIT_PREFIX = "submit_";
for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
String key = (String) e.nextElement();
if (key.startsWith(SUBMIT_PREFIX)) {
String value = key.substring(SUBMIT_PREFIX.length());
request.setAttribute("submit", value);
break;
}
}
}
2. Solution with JavaScript on the client (browser) side
Introduce in the form new hidden widget that will hold the number of room clicked. When button is clicked its value is stored in that widget.
When request is send, on the server side you just read the value of that parameter (widget name).
Below is an example: room-nr will have value of clicked button
var form = document.forms['add-room'];
$(form).on('click', 'button', function(e) {
e.preventDefault();
var name = $(this).attr('name')
form['room-nr'].value = name.replace(/\D+/, '');
console.log(form['room-nr'].value);
//form['add-booking'].click();
});
.hide {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="add-room" action='.'">
<input type="hidden" name="room-nr" value="" />
<table cellpadding="4">
<tr>
<td>room1</td>
<td>
<button type="button" name="room-1">Add</button>
</td>
</tr>
<tr>
<td>room2</td>
<td>
<button type="button" name="room-2">Add</button>
</td>
</tr>
<tr>
<td>room3</td>
<td>
<button type="button" name="room3">Add</button>
</td>
</tr>
</table>
<input type="submit" value="Add a Booking" name="add-booking" class="hide" />
</form>
You need to do the following:
<input type="submit" value="<%name%>" name="Add Booking"
/>
Related
I have a list of objects as JSON which is inside a workLists. I created a table by iterating using each on workLists and create a table in thymeleaf?
Now how can I pass work that is a single object back to the controller, what I tried is using th:object
I thought it would work but on the controller end null values are coming.
Thymeleaf section
<tr th:each="work , status : ${workLists}">
<td scope="row" th:text="${status.count}"></td>
<td>
<form th:action="#{/edit/work}" th:object="${work}" method="post">
<button type="submit" class="dropdown-item">Edit</button>
</form>
</td>
</tr>
Controller Section
#PostMapping("/edit/work")
public String editWork(#ModelAttribute("work") GetWorkkDto getWorkDto){
logger.debug(" Inside of edit work method");
return "listOfwork";
}
You need to give the contoller 2 attribues which are the workLists and a work. It will be something like:
#GetMapping("/edit/work")
public String editWork(Model model){
model.addAttribute("workLists", workLists);
model.addAttribute("workDTO", new Work());
return "listOfwork";
}
Then in your HTML page through hidden fields you give the values of the work selected:
<table>
<tr th:each="work, stat : ${workLists}">
<td>
<form action="#" th:action="#{/edit/work}" th:object="${workDTO}" method="post">
<input type="hidden" th:attr="name='id'" th:value="${work.id}" />
<input type="hidden" th:attr="name='name'" th:value="${work.name}" />
<input type="hidden" th:attr="name='description'" th:value="${work.description}" />
<p th:text="'Id : '+${work.id}"></p>
<p th:text="'Name : '+${work.name}"></p>
<p th:text="'Description : '+${work.description}"></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</td>
</tr>
</table>
You can see in the proposed code that I give the value of work.id to the workDTO.id through the name attribute (don't ask me why it is like this)
Finaly you retrieve the object in your controller (as you do already) with something like this:
#PostMapping("/edit/work")
public String editWork(#ModelAttribute Work workDTO, Model model){
System.out.println(workDTO.toString());
model.addAttribute("workLists", workLists);
model.addAttribute("workDTO", new Work());
return "listOfwork";
}
I am populating my dropdown from DB but after selecting I am getting null value in my method present in my java code when submit button is clicked.
Though, if I am hard coding values in my dropdown, whole functionality is working perfectly. Please, tell me what I am doing wrong?
Java Code for passing List value obtained from DB which I am passing to my JSP:
EventService eventService = new EventServiceImpl();
List<Event> theEvents = eventService.showEventListMethod();
// add the event list to the model
theModel.addAttribute("event", theEvents);
return "eventPostponeCancelCompletePage";
My JSP form where I am selecting value from dropdown:
<form action = "eventCancelCompleteMethod" modelAttribute="event" method = "post">
<table id="table" align="center">
<tr>
<td width="50%">Event Name: </td>
<td width="50%">
<select name="eventName">
<c:forEach var="tempEvent" items="${event}">
<option value="tempEvent.eventName">${tempEvent.eventName}</option>
</c:forEach>
</select>
<!-- <select name="eventName">
<option value="Birthday Party for May">Birthday party for May</option>
</select> -->
</td>
</tr>
<tr>
<td align="center" width="34%" >
<!-- <input type = "submit" value = "Postpone"/> -->
<input class="btn btn-default custom" type = "button" value = "Postpone Event" onclick="openPage('showPostponeEventPage')"/>
</td>
<td align="center" width="33%">
<input class="btn btn-default custom" type = "submit" value = "Cancel/Complete Event"/>
</td>
</tr>
</table>
</form>
Java method which will be called once submit button is clicked:
#PostMapping("/eventCancelCompleteMethod")
public String eventCancelCompleteMethod(#ModelAttribute("event") Event theEvent)
{
EventService eventService = new EventServiceImpl();
System.out.println("Event Name: "+theEvent.eventName);
//theEvent.setEventName("New testing event July");
theEvent.setEventState("inactive");
System.out.println("New Event Data: "+theEvent);
System.out.println("Successfully Cancelled/Completed the event");
String action = eventService.eventCancelCompleteMethod(theEvent.eventName, theEvent.eventState);
System.out.println("Action: " + action);
if(action.equalsIgnoreCase("success"))
{
System.out.println("Successfully added contributor data!!");
return "redirect:/showEventPostponeCancelComplete";
}
else
{
System.out.println("Failed to add!!");
return "redirect:/showEventPostponeCancelComplete";
}
}
I think you should use form:select as below:
<form:select path="BEAN.YourBeanAttrName" style='width: 110px;' id="">
<form:options items="${FORM.actionList}" itemValue="key" itemLabel="value"/>
</form:select>
I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?
Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }
String isno1=request.getParameter("isbn");
String bktitle2=request.getParameter("booktitle");
String authr3=(String) request.getParameter("author");
System.out.println(isno1+bktitle2+authr3);
Enumeration paramaterNames = request.getParameterNames();
when i am taking the parameters in servlet then i am gettin my values as 'null'
what wrong am i doing.
this is the way i am setting the parameters...
from a jsp page using script tag
<script type="text/javascript">
function getHTTPObject()
{
var httpobject;
if(!httpobject && typeof(XMLHttpRequest) != 'undefined')
{
try{
httpobject=new XMLHttpRequest();
}
catch(e){
xmlhttp=false;
}
}
return httpobject;
}
var httpob=getHTTPObject();
function handleHttpResponse(){
if(httpob.readyState==4){
//alert("sd");
var result=httpob.responseText;
alert(result);
/* document.write("hi your book is submitted !!!!!"); */
}
}
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
httpob.open("POST","addbook",true);
httpob.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close");
/* httpob.setRequestHeader("Content-type","application/x-www-from-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close"); */
httpob.onreadystatechange=handleHttpResponse;
httpob.send();
}
</script>
and this my form.....
<form style="margin: 100px;" name="mayurform">
<table align="center">
<tr>
<td align="center">ISBN NO.</td>
<td><input align="middle" type="text" size="20" name="id" id="isbn">
</tr>
<tr>
<td align="center">Book-Title</td>
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
</td>
</tr>
<tr>
<td align="center">Author</td>
<td><input align="middle" type="text" size="20" name="pwd" id="author">
</tr>
<tr>
<td><input align="middle" type="button" size="20" name="Add-Book" onclick="auth()">
</tr>
</table>
</form>
You are fetching parameters with ID's you should give Names.
for example
String isno1=request.getParameter("isbn"); //here is isbn is id
you should write
<input align="middle" type="text" size="20" name="id" id="isbn">
String isno1=request.getParameter("id");-----------^
and also
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
<td><input align="middle" type="text" size="20" name="pwd" id="author">
both inputs have the same **name** please check it
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html
Use like below ajax send() to send data
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
.......
...
httpob.send(params);//change is here
}
call httpob.send(),passing in the parameters that will be sent (without the "?" prefix).
I have the following class that I'm using in my Java with JSP applicaton.
//
public class QuestionBO implements Serializable{
private int questionId;
private int testID;
private String question;
private TutorBO infoAboutTutor;
private SubjectBO infoAboutSubject;
private TestBO infoAboutTest;
private List<AnswerBO> answers;
public QuestionBO() {
}
public QuestionBO(String question) {
this.question = question;
}
getter & setter....
The JSP page has a form where each Question (its String representation) has a checkbox next to it. A user marks some of the questions and submits the form to the server for processing by a servlet.
What is the conventional way of binding the Question objects with the checkboxes so that I could find out what Questions have been selected?
Currently I'm using the following approach for constructing the form:
//
<c:if test="${not empty questionsForSubject}">
<form action="/TutorWebApp/controller" method="POST" name="addQuestionForm">
<input type="hidden" name="command" value="add_question_list" />
<input type="hidden" name="testName" value="${testName}"/>
<table border ="1">
<tbody>
<c:forEach items="${questionsForSubject}" var="question">
<tr>
<td>
<input type="checkbox" name ="choosen_question"
value="${question.getQuestion()}">
${question.getQuestion()}
<br />
</td>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" value="Add questions "/>
</form>
And I shouldn't use frameworks.
Thanks
And I have last question
<c:if test="${not empty questionsForSubject}">
<form action="/TutorWebApp/controller" method="POST" name="addQuestionForm">
<input type="hidden" name="command" value="add_question_list" />
<input type="hidden" name="testName" value="${testName}"/>
<input type="hidden" name="questionsForSubject" value="${questionsForSubject}"/>
<table border ="1">
<tbody>
<c:forEach items="${questionsForSubject.keySet()}" var="questionID">
<tr>
<td>
<input type="checkbox" name ="choosen_question" value="${questionID}">
${questionsForSubject.get(questionID).getQuestion()}
<br />
</td>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" value="Добавить вопросы"/>
</form>
How I can get map from this page on servlet?
Give each checkbox an unique value. For example, the unique question identifier:
<c:forEach items="${questionsForSubject}" var="question">
<tr>
<td>
<input type="checkbox" name="chosen_question" value="${question.questionId}" />
${question.question}
<br />
</td>
</tr>
</c:forEach>
This way you'll be able to grab all checked values by just the following call in the servlet:
String[] chosenQuestions = request.getParameterValues("chosen_question");
Generate an unique name for each checkbox as follows:
<input type="checkbox" name="${question.questionId}" />
or:
<input type="checkbox" name="choosen_question_${question.questionId}" />
After that, you're already able to identify each checkbox in your servlet