I am trying post a request to my controller and everytime when I hit submit button it gives an error of bad request.
I am not able to find out what is wrong with the code.
Home.jsp
<div id="setReminder">
<label class="generalReminder" style="text-decoration: none;">General
Reminder</label>
<table>
<tr>
<td>Date</td>
<td><input type="text" readonly="readonly"
id="birthdayDate"></td>
</tr>
<tr>
<td>Time</td>
<td><input type="text" readonly="readonly" id="callTime"
></td>
</tr>
<tr>
<td>Message</td>
<td><textarea id="reminderTag" rows="5"></textarea></td>
</tr>
</table>
</div>
<div id="reminderDot" style="margin-top: 24%; position: relative;">
<button class="submitReminder" onclick="saveReminderDetails();">Submit</button>
</div>
Home.js
function saveReminderDetails(){
var x="";
x=scheduleBirthdayReminder();
if(x){
$.ajax({
type:"POST",
url:"submitBirthdayRequest.do",
data : {
birthdayDate :$("#birthdayDate").val(),
birthdayTime : $("#callTime").val(),
birthdayReminder : $("#reminderTag").val()
},
success : function(data) {
alert('data is'+data);
$("#birthdayDate").val('');
$("#callTime").val('');
$("#reminderTag").val('');
}
});
}
}
Controller.java
#RequestMapping(value="submitBirthdayRequest.do",method=RequestMethod.POST)
public #ResponseBody String submitSchedulerDetails(#RequestParam("birthdayDate")String birthdayDate,#RequestParam("callTime")String birthdayTime,#RequestParam("reminderTag")String reminderTag,HttpServletRequest request ){
System.out.println("adding reminder details with birthdayDate "+birthdayDate+"and time"+birthdayTime);
String userIdentity=((UserDetails)request.getSession(false).getAttribute("loginDetails")).getName();
try{
boolean schedulerObj= schedulerService.addSchedulerBirthdayDetails(userIdentity,birthdayDate, birthdayTime,reminderTag);
}catch(Exception e){
e.printStackTrace();
}
return birthdayTime;
}
Error
http://localhost:8083/Testing/submitBirthdayRequest.do 400 (Bad Request)
the names of the parameters in the request don't match the expected. Try changing the
#RequestParam("birthdayTime") String birthdayTime
#RequestParam("birthdayReminder") String reminderTag
or change the param names on the client side
Related
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 6 years ago.
I am very new to ajax and I am getting null values with ajax call to servlet,don't know why?any idea?here below i mentioned my code,For any help thanks in advance.
function addSubjectMarks(){
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
var selectedStudent=document.getElementById("selectedStudent").value;
var selectedSubject=document.getElementById("selectedSubject").value;
var marks=document.getElementById("stMarks").value;
$.ajax({
type: "POST",
url: "WeeklyMarks",
data:postData,
success: function(data,status){
//var res = data.split(',');
}
});
}
//servlet code is:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String selectedSubject=request.getParameter("stSubjectMarks");
System.out.println("selectedSubject :"+selectedSubject);//here getting null value
}
my html form is:
form id="ajaxform" action="weeklyMarks" method="post">
<table>
<td>
<label id="stForm" for="Marks">Marks Obtained:</label>
<input type="text" id="stMarks" name="stMarks" style="margin-left: 33px; width: 150px;" />
<label id="stMarksError" style="display: none; color: red;">*Please enter marks</label>
<br>
<br>
</td>
</tr>
<tr>
<td>
<input type="button" value="Add" id="addButton" class="btn-warning" style="margin-left: 200px;"" onclick="addSubjectMarks() ">
</td>
</tr>
</table>
</div>
</div>
postData = $('#ajaxform').serializeArray();
I have the following situation. In controller in method viewUserReminders I pass remindersListWrapper to my uReminder.jsp page.
#RequestMapping(value = "/user/reminders", method = RequestMethod.GET)
public ModelAndView viewUserReminders(Model model, #ModelAttribute("id_users") Long id_users) throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("user/uReminders");
List<Reminders> remindersList=userService.getUserReminders(id_users);
RemindersListWrapper remindersListWrapper=new RemindersListWrapper();
remindersListWrapper.setRemindersList(remindersList);
mv.addObject("remindersListWrapper", remindersListWrapper);
return mv;
}
In my uReminders.jsp file I have a form with modelattribute remindersListWrapper. This jsp page displays table of reminders. Next to every reminder there is a checkbox. The user can check several checkboxes, click button("Mark as read") and using Ajax I submit form and go to controller method
readReminders().
uReminders.jsp
<form:form action="/user/ajax/reminders/readReminders" method="POST" modelAttribute="remindersListWrapper" id="remindersForm">
<div id="main">
<table class="table">
<thead>
<tr>
<th></th>
<th></th>
<th>Reminder</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<c:forEach items="${remindersListWrapper.remindersList}" varStatus="status" var="reminders">
<tr id="row">
<td><form:hidden path="remindersList[${status.index}].idCalendar"/></td>
<td><form:checkbox path="remindersList[${status.index}].isRead"/></td>
<td><form:input path="remindersList[${status.index}].endDate"/></td>
</tr>
</c:forEach>
</c:when>
<c:when test="${empty remindersListWrapper.remindersList}">
<tr>
<td colspan="3">You have no reminders.</td>
</tr>
</c:when>
</c:choose>
</tbody>
</table>
<c:choose>
<c:when test="${not empty remindersListWrapper.remindersList}">
<input type="button" id="reminders" value="Mark as read"/>
</c:when>
</c:choose>
</div>
</form:form>
$(window).load(function () {
$("#reminders").click(function () {
sendAjax('readReminders', $("#remindersForm").serialize());
});
});
In this method I save read reminders and I build newRemindersListWrapper with the new list of reminders(I want to delete checked reminders and display only unchecked). My first question is: How to return to the page newRemindersListWrapper itself.
#RequestMapping(value = "/user/ajax/reminders/readReminders", method = RequestMethod.POST)
#ResponseBody
public String readReminders(#ModelAttribute("remindersListWrapper") RemindersListWrapper remindersListWrapper, #ModelAttribute("id_users") Long id_users) throws Exception {
for(Reminders reminders:remindersListWrapper.getRemindersList()){
if(reminders.getIsRead()){
userDao.saveReadReminders(reminders);
}
}
RemindersListWrapper newRemindersListWrapper=new RemindersListWrapper();
///////////////////
here I want to return the newRemindersListWrapper itself
//////////////////
}
And my second question is: How I can set newRemindersListWrapper as modelattribute in my form.
function sendAjax(ref, data) {
console.log(data);
$.ajax({
url: 'ajax/reminders/' + ref,
type: 'POST',
data: data,
success: function (response) {
////////////////////////////////
I want to get newRemindersListWrapper and set it as modelattribute in form.
////////////////////////////////
console.log("success");
},
error: function (request, status, error) {
console.log('error ' + ref + ' text=' + request.responseText + ' status = ' + status + ' error = ' + error);
}
});
}
Question 1: just change the return type to RemindersListWrapper and return it
Question 2: Since you are using ajax, you can't. You need to use javascript to parse the returned list and update the page as needed.
in my form I have table to show some of customer data.user can click on row to see all of customer data.
<div class="container">
<table class="table table-bordered" style="direction: rtl">
<thead>
<tr>
<th style="text-align: center">customer name</th>
<th style="text-align: center">customer ID</th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer" varStatus="loop">
<tr onclick="retrieveCustomer('${loop.index}')">
<td id="id-${loop.index}">${customer.customerId}</td>
<td>${customer.customerName}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<script>
function retrieveCustomer(id) {
debugger;
$.ajax({
url: "<%=request.getContextPath()%>/show_selected_customer",
data: {customerId: $('#id-' + id).text()},
type: "GET",
success: function (response) {
},
error: function (xhr, status, error) {
alert(error);
}
});
};
</script>
and in my controller:
#RequestMapping(value = "/show_selected_customer", method = RequestMethod.GET)
public ModelAndView showSelectedCustomer(#RequestParam("customerId") String customerId) {
Map<String, Object> model = new HashMap<>();
Customer customer = coreService.getCustomer(customerId);
model.put("customer", customer);
return new ModelAndView("showCustomerData", model);
}
tiles:
<definition name="showCustomerData" extends="base.definition">
<put-attribute name="title" value="customer data"/>
<put-attribute name="content" value="/WEB-INF/jsp/show_customer_data.jsp"/>
</definition>
until now every thing work correctly.
my problem is, it doesn't show show_customers.jsp page,and even I have no error in my log.
what is my problem,Is because of ajax call? I did`t use #responsebody and want to show customers.jsp page with return modelandview. thank you
Use the response body annotation and convert your entity to JSON and return it instead.
Hi I am reading image from MongoDB and trying to pass that to JSP page but it is not passing properly from my controller. i am thinking i am almost edge to the solution but not getting exactly where i am doing mistake. Please let me know if you find any mistake.
here insertMedia method reading image from file and storing into DB and then returning back that image.
i am passing userMediaSave as image value to JSP, you can get that at tag like
img src=${userMediaSave} alt="Profile images"
My Controller:
#RequestMapping(value = "/userMediaSave", method = RequestMethod.GET)
public ModelAndView mediaLoadSuccess(HttpServletRequest request,HttpServletResponse response,
#ModelAttribute("mediaBean") MediaBean mediaBean) throws IOException, ServletException {
ModelAndView model = null;
File filePart = mediaBean.getMediaImage();
if (filePart != null) {
InputStream inputStream = new FileInputStream(filePart);
GridFSDBFile imageForOutput = null;
try {
imageForOutput = loginDelegate.insertMedia(inputStream, request.getContentType(), filePart.getName());
mediaBean.setExistedMedia(imageForOutput);
OutputStream out= null;
if(imageForOutput!=null){
InputStream is = imageForOutput.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
byte[]imagenEnBytes = buffer.toByteArray();
buffer.flush();
response.setContentType("image/jpg" );
response.setContentLength(imagenEnBytes.length);
model = new ModelAndView("userMedia");
request.setAttribute("userMediaSave", imagenEnBytes);
return model;
} else {
System.out.println("inside uploadMedia page -ve");
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
//out.close();
}
}
return model;
}
JSP is:
<body onload="checkMessage()">
<form:form id="mediaForm" method="get" action="userMediaSave" modelAttribute="mediaBean">
<table border="1" cellpadding="1" cellspacing="1"
style="width: 500px;" align="center">
<tbody>
<tr>
<td colspan="4" align="center">Name : Welcome to Media App</td>
</tr>
<tr>
<td rowspan="3">Profile Image</td>
<td>Upload Images</td>
<td><input type="file" name="mediaImage" /></td>
</tr>
<tr>
<td> </td>
<td><input name="upload" type="submit" value="Upload" /></td>
</tr>
</tbody>
</table>
<table border="1" cellpadding="1" cellspacing="1"
style="width: 500px;" align="center">
<tbody>
<tr>
<td>User has some existed Media Album</td>
</tr>
<tr>
<td>
<img src=${userMediaSave} alt="Profile images" style="width:100px;height:100px;">
</td>
</tr>
</tbody>
</table>
</form:form>
am i passing image from controller to JSP properly? if not please let me know which way i have to pass it.
it shows data when get request is send properly but when i save data with post requset then again the page is rendered data is not coming on page
This is my controller code
#RequestMapping(value = "/incident", method = RequestMethod.GET)
public String add_incident(Model model,HttpSession session) {
try{
List<AddIncident> fetchincident = incService.fetchIncident();
String user_id = ""+session.getAttribute("session");
List<AddIncident> fetchuserincident = incService.fetchuserincident(user_id);
//group work
User user = new User();
model.addAttribute("user", user);
List<User> fetchListByUsername = userService.findListByUserName(user_id);
String department = fetchListByUsername.get(0).getDepartment();
List<AddIncident> fetchgroupincident = incService.fetchgroupincident(department);
System.out.println(fetchgroupincident.get(0).getAssignTo());
System.out.println(fetchgroupincident.get(0).getSeverity());
model.addAttribute("fetchincident", fetchincident);
model.addAttribute("fetchgroupincident", fetchgroupincident);
model.addAttribute("fetchuserincident", fetchuserincident);
}catch(Exception e){
e.printStackTrace(); }
AddIncident incident = new AddIncident();
model.addAttribute("incident", incident);
return "incident";
}
#RequestMapping(value = "/incident", method = RequestMethod.POST)
public String add_incident(
#Valid #ModelAttribute("incident") AddIncident incident,
BindingResult result, Model model,HttpSession session) {
if (result.hasErrors()) {
return "incident";
} else {
User user=new User();
System.out.println(""+session.getAttribute("session"));
String user_id = ""+session.getAttribute("session");
System.out.println(user_id);
List<User> fetchListByUsername = userService.findListByUserName(user_id);
String department = fetchListByUsername.get(0).getDepartment();
System.out.println(department);
try{
List<User> fetchgroupuser = userService.findListByGroup(department);
ArrayList<String> email=new ArrayList<String>();
System.out.println(email);
for(User use:fetchgroupuser){
email.add(use.getEmail());
}
String[] to = new String[email.size()];
to = email.toArray(to);
System.out.println(to);
/*new String[]{"irasoftwares6#gmail.com","bluemagictest#gmail.com"};*/
String from = "Anurag.yv19#gmail.com";
String sub= "Incident Management System";
String msgBody="New Incident created";
incService.save(incident);
emailService.sendEmail(to , from, sub, msgBody);
}catch(ArrayIndexOutOfBoundsException e){e.printStackTrace();}
incident_logger.log(INCIDENT, incident.getRef_id()+" \n Assigned to :"+session.getAttribute("session"));
model.addAttribute("message", "Saved incident details");
return "incident";
}
}
my jsp code
<div class="table-responsive" id="inc-table" style="min-height: 280px;">
<form action="" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q" placeholder="Search for" required>
<span class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i></button>
</span>
</div>
</form>
<table class="table table-list-search table-bordered table-stripped table-hover">
<thead>
<tr>
<th>Ref. No.</th>
<th>Created</th>
<th>Severity</th>
<th>State</th>
<th>Assigned</th>
<th>Est</th>
<th>Description</th>
<th>Location</th>
<th>Config-item</th>
<th>Symptom Code</th>
<th>Closure Code</th>
<th>Submitted BY</th>
</tr>
</thead>
<tbody>
<c:forEach var="fetchuserincident" items="${fetchuserincident}">
<tr>
<td id="1" class="click" ><a href=""/>${fetchuserincident.ref_id}</td>
<td>${fetchuserincident.created}</td>
<td>${fetchuserincident.severity}</td>
<td>${fetchuserincident.state}</td>
<td>${fetchuserincident.assignTo}</td>
<td>${fetchuserincident.escalation}</td>
<td>${fetchuserincident.description}</td>
<td>${fetchuserincident.location}</td>
<td>${fetchuserincident.config_Item}</td>
<td>${fetchuserincident.symptom_code}</td>
<td>${fetchuserincident.closure_code}</td>
<td>${fetchuserincident.submittedby}</td>
<td> <button id="editbtn" class="fa fa-pencil">Edit</button></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<hr>
<br>
My Group Work
Ref. No.
Created
Severity
State
Assigned
Est
Description
Location
Config-item
Symptom Code
Closure Code
Submitted BY
${fetchgroupincident.ref_id}
${fetchgroupincident.created}
${fetchgroupincident.severity}
${fetchgroupincident.state}
${fetchgroupincident.assignTo}
${fetchgroupincident.escalation}
${fetchgroupincident.description}
${fetchgroupincident.location}
${fetchgroupincident.config_Item}
${fetchgroupincident.symptom_code}
${fetchgroupincident.closure_code}
${fetchgroupincident.submittedby}
Edit