Why won't the link go to controller, Spring mvc? - java

I am having trouble in redirecting the link of below code to my controller class.
This is the code:
$('#ticketDT').DataTable({
"dom": '<"toolbar">frtip',
"responsive": true,
"ordering": false,
"scrollY": "300px",
"scrollCollapse": true,
"ajax": "ticketList.json",
"bDestroy": true,
"deferRender": true,
"aoColumns": [
{"mData": "ticketNumber"},
{"mData": "category"},
{"mData": "subcategory"},
{"mData": "status"},
{"mData": "requestedBy"},
{"mData": "ticketNumber",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a class='linkColor' href='${pageContext.request.contextPath}/assignMessageTicket?sender_assign=" + encodeURIComponent(sender) + "&portId_assign="+portId+"&messageId=" + encodeURIComponent(messageId) + "&ticketNumber_assign=" + encodeURIComponent(oData.ticketNumber) + "'><span data-toggle='tooltip' title='Assign'><i class='ti-plus btn btn-simple btn-assign btn-icon' data-mode='assignTicket'></i></span></a>");
}
}
],
This is my handler for the controller class:
#RequestMapping(value = {"assignMessageTicket"}, method = RequestMethod.GET)
#PreAuthorize("hasAnyRole('CWO_ENCODER,ADMIN')")
public ModelAndView assignMessageTicket(#RequestParam(value = "sender_assign",required = true) String sender,
#RequestParam(value = "portId_assign",required = true) String portId,#RequestParam(value = "messageId",required = true) String messageId,
#RequestParam(value = "ticketNumber_assign",required = true) String ticketNumber,
ModelMap model,HttpServletRequest request) throws UnsupportedEncodingException {
String currentUser = request.getRemoteUser();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/YYYY");
Date date = new Date();
String currentDate = formatter.format(date);
dashboardService.assignMessageSmsMessages(messageId,ticketNumber);
dashboardService.assignMessageSmsReply(messageId,ticketNumber);
dashboardService.addRecentlyAssignedMessage(sender,portId,ticketNumber,currentUser,currentDate);
String newSender = URLEncoder.encode(sender, "UTF-8").replaceAll("\\+", "%2B");
String newPortId = URLEncoder.encode(portId, "UTF-8").replaceAll("\\+", "%2B");
boolean hasError = false;
model.clear();
return new ModelAndView("redirect:conversation?sender="+newSender+"&portId="+newPortId+"&hasError="+hasError);
}
This is my updated code.
The link to the controller is
$(nTd).html("<a class='linkColor' href='${pageContext.request.contextPath}/assignSpecificMessage?messageId="+messageId+"&sender_assign=" + encodeURIComponent(sender) + "&portId_assign="+portId+"&ticketNumber_assign=" + encodeURIComponent(oData.ticketNumber) + "'><span data-toggle='tooltip' title='Assign'><i class='ti-plus btn btn-simple btn-assign btn-icon' data-mode='assignMessageTicket'></i></span></a>");
The controller is
#RequestMapping(value = {"assignSpecificMessage"}, method = RequestMethod.GET)
#PreAuthorize("hasAnyRole('CWO_ENCODER,ADMIN')")
public String assignSpecific(#RequestParam(value = "sender_assign",required = true) String sender,
#RequestParam(value = "portId_assign",required = true) String portId,#RequestParam(value = "messageId",required = true) String messageId,
#RequestParam(value = "ticketNumber_assign",required = true) String ticketNumber,
ModelMap model,HttpServletRequest request) {
return "conversation";
}
I tried to create a new handler to test it, Still, The same error appears.

Ensure that href value for your link is getting build properly.
Go to browser elements tab and check the value for link href and make sure that it is not breaking.
or you can do that using jquery or javascript like below.
$("#idOfAnchorTag").on("click", function(){
var href = $(this).find('a').attr('href');
....
})
UPDATE: As you provided link in one of my comments, it is clear that your request parameters names are not matching with the controller one.
link :
http://localhost:8084/cwms/assignSpecificMessage?assign_sender=%2B639062165304&assign_portId=6&messageId=15416427366198288583&assign_ticketNumber=ADM-1809-00473
Controller :
#RequestParam(value = "sender_assign",required = true) String sender,
#RequestParam(value = "portId_assign",required = true) String portId,#RequestParam(value = "messageId",required = true) String messageId,
#RequestParam(value = "ticketNumber_assign",required = true) String ticketNumber,
You are using wrong parameter names in request so change all the parameters to controller one.
For example sender_assign you are sending as assign_sender and so on.
SO to make it work use sender_assign instead of assign_sender and all other parameters also from client side(anchor href)

Related

GetMapping After Postmapping

I am trying a GetMapping After a PostMappng. Postmapping basically does an Update.
What I am doing is, if the condition satisfies then no need to update but simply redirect to another page. But seem it is not working, It seems a GetRequest is not Possible from a Postrequest but I have read articles and even seen solutions on Stack but dont know why dont they work for me. Any help or hint will be appreciated
#PostMapping(path = "/campaign/services/migrate")
public String migrateCampaigns(
#RequestParam(required = false, value = "campaignCount") int campaignCount,
#RequestParam(required = false, value = "client-email") String clientEmail,
#RequestParam(required = false, value = "campaign-id") List<String> campaignIds,
#RequestParam(required = false, value = "selectAllCampaigns") String selectAllCampaigns,
HttpServletRequest request,
HttpServletResponse httpResponse,
Model model) throws ServletException, IOException {
logger.info("Retrieving source and destination credential from cookies");
String url = null;
if(campaignCount >= 20) {
url = "redirect:/login/oauth/login-with-eloqua";
}
String adminsEmail = contactService.getEmail(siteNameForEmail);
String userEmail = cookieService.retrieveCookieValue(cookieDefinitionUserEmail);
String clientsEmailAddresses = adminsEmail + "," + userEmail;
migrateResponse = migrationService.migrate(campaignIds, request.getCookies(), clientsEmailAddresses);
}
//return migrateResponse;
return url;
}
#GetMapping(path = "/login/oauth/login-with-eloqua")
public String eloquaOauthLoginPage(HttpServletRequest request, Model model, HttpServletResponse response) {
return "login/oauth/login-with-eloqua";
}
There are many ways to get this approach, it's up on to you. I can see you have a class called HttpServletResponse, you can use a method that name isĀ of the class.
Example:
httpSrvltResponse.sendRedirect("/login/oauth/login-with-eloqua")`

HttpMediaTypeNotSupportedException

I have this class in my .NET application to send some data from client(.NET) to server(Spring) :
class NetworkController
{
private static readonly HttpClient client = new HttpClient();
public static async Task SendUserDataAsync()
{
var values = new Dictionary<string, string>
{
{ "firstName", "sunny" },
{ "lastName", "leone" },
{ "timeStamp", "test" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://localhost:8080/user", content);
var responseString = await response.Content.ReadAsStringAsync();
}
}
Reference
And in my Spring Boot application, I a class called User :
#Entity
public class User
{
#Id
private String firstName;
private String lastName;
private String timeStamp;
public User(){}
#Override
public String toString() {
return "firstName : "+this.firstName + "\n"+"lastName : " + this.lastName;
}
}
In my rest-controller I have this method to insert User :
#PostMapping("/user")
User addUser(#RequestBody User user)
{
System.out.println(user);//this always prints an empty line, maybe receiving nothing
return userRepository.save(user);
}
I get this warning Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
I have created this class(with the concept of Spring) in .NET, but it seems no use :
class User
{
String firstName;
String lastName;
String timeStamp;
public User()
{
firstName = "1"
lastName = "2"
timeStamp = "test"
}
}
Wouldn't sending an object instead of dictionary be more gentle and tidy ? How to do so ?
How can I resolve this problem ?
In your .NET application, the line var content = new FormUrlEncodedContent(values); indicates that the request will have a HTTP header Content-Type set to application/x-www-form-urlencoded.
It means the data stored in var values = new Dictionary... will be formatted by .NET as a query string such as firstName=sunny&lastName=leone&timeStamp=test.
That is what your Sprint server receives. However it wants to receive JSON data, not a query string. So it complains.
In order to get rid of the miscommunication, your .NET application should send JSON data, such as
{"firstName": "sunny", "lastName": "leone", "timeStamp": "test"},
as expected by the Spring server.
Here is an example code:
HttpClient client = new HttpClient();
object anonymousObject = new
{
firstName = "sunny",
lastName = "leone",
timeStamp = "test"
};
string jsonContent = JsonConvert.SerializeObject(anonymousObject);
var request = new HttpRequestMessage(HttpMethod.Post, "http://127.0.0.1:8080/user");
request.Content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.SendAsync(request);
Console.WriteLine(await response.Content.ReadAsStringAsync());
You need to install the package Newtonsoft.Json in order to call JsonConvert.SerializeObject(anonymousObject), as pointed by this SO answer mentionned by #alfcope.

Sending data to spring controller using AJAX

I know that this question has been asked many times, but I have looked at every variation I could find and have still not been able to find out my issue.
Here is my ajax call:
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
contentType: "application/json",
data: JSON.stringify(input),
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
The endpoint works. You can take my word for it.
Spring controller:
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
And here is my model class:
public class FormInput {
private String userInputOne;
private String userInputTwo;
private String userInputThree;
private String userInputFour;
private String userInputFive;
public FormInput(String userInputOne, String userInputTwo, String userInputThree, String userInputFour, String userInputFive) {
this.userInputOne = userInputOne;
this.userInputTwo = userInputTwo;
this.userInputThree = userInputThree;
this.userInputFour = userInputFour;
this.userInputFive = userInputFive;
}
public String getUserInputOne() {
return this.userInputOne;
}
public String getUserInputTwo() {
return this.userInputTwo;
}
public String getUserInputThree() {
return this.userInputThree;
}
public String getUserInputFour() {
return this.userInputFour;
}
public String getUserInputFive() {
return this.userInputFive;
}
}
I keep getting a HTTP status code of 415, which means unsupported media type. I set the contentType to "application/json", and I also tried to add "consumes= 'application/json'" to my Spring controller and that didn't help either. Thank you for any help you can give.
EDIT: I am now getting the following error after changing RequestMethod.GET to RequestMethod.POST: "Error 405: Request method 'GET' not supported"
There is no need to send parameter as json,you have made things complicated
In javascript code,you can remove contentType: "application/json", and change the format of data property to send data directly
function sendFormData(endpoint) {
console.log("CLICKING BUTTON");
var input = {
"userInputOne": "hello1",
"userInputTwo": "hello2",
"userInputThree": "hello3",
"userInputFour": "hello4",
"userInputFive": "hello5"
}
$.ajax({
type:"post",
//contentType: "application/json",
data: input,//send data directly
url: endpoint,
asynch: false,
success: function() {
alert("success");
}
});
}
In java code,you can remove #ResponseBody annotation before FormInput
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
The java controller method you have written is of type 'GET', it should be changed to 'POST', as the ajax call you are making is also of type POST
Try this and it will work
#RequestMapping(value = "endpoint", method = RequestMethod.POST)
private #ResponseBody String getFormData(#RequestBody FormInput userInput, HttpServletRequest request, final ModelMap model) {
String userInput1 = userInput.getInputOne();
String userInput2 = userInput.getInputTwo();
String userInput3 = userInput.getInputThree();;
String userInput4 = userInput.getInputFour();
String userInput5 = userInput.getInputFive();
return "success";
}
I guess main problem in not match http methods. You sent by POST method, but controller wait for GET method.
This is because your method signature doesn't match. Just remove contentType: "application/json".

Trying to pass Json object to Jersey restfull service as FormDataParam

I do not know how to pass Java object to Jersey restfull service as FormDataParam. The service works perfectly with curl, but Swagger responds with error. The problem is most probably with annotation #FormDataParam. Swagger does not throw 415 Error Unsupported Media File, but it
Here is the code Jersey service:
#POST
#ApiOperation(value = "Upload", notes = "", response = ImageAPIResponse.class)
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, "application/x-javascript" })
#Consumes(MediaType.MULTIPART_FORM_DATA)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Successful or application error (see notes)", response = ImageAPIResponse.class) })
public ImageAPIUploadUpdateResponse upload(
#ApiParam(required = true, value = "user name part of credentials") #FormDataParam("user_name") String userName, //
#ApiParam(required = true, value = "") #FormDataParam("file") File file, //
#ApiParam(required = true, value = "") #FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
#ApiParam(required = false, value = "") #FormDataParam("file_name") String fileName,
#ApiParam(required = false, value = "") #FormDataParam("meta_data") ImageMetaData metaData) {
ImageAPIResponse imageAPIResponse = new ImageAPIResponse();
//metaData object keeps being null...
return imageAPIResponse;
}
public class ImageMetaData{
public String fileName;
public String fileType;
}
Did anyone encounter a similar problem with FormDataParam? It would be great if I could use this Jersey annotation in my parameters.

redirect flash attribute not working for List<>

I would like to redirect a message list from a post to a get.
#RequestMapping(method = RequestMethod.GET, value = "/ManageNonRoutedActivities")
public ModelAndView manageNonRoutedActivities(ModelAndView modelAndView,
ArrayList<Message> messages,
#ModelAttribute("nonRoutedActivity") NonRoutedActivity nonRoutedActivity,
#RequestParam(value = "search", defaultValue = "") String search,
#RequestParam(value = "orderField", defaultValue = "Description") String orderByField,
#RequestParam(value = "orderDirection", defaultValue = "asc") String orderByDirection) {
ManageNonRoutedActivitiesRequest request = new ManageNonRoutedActivitiesRequest(new ManageNonRoutedActivitiesDAOImpl(), search, orderByField, orderByDirection);
System.out.println(messages.size());
modelAndView.setViewName("default");
modelAndView.addObject("viewModel", new ManageNonRoutedActivitiesImpl(request, search, orderByField, messages));
return modelAndView;
}
#RequestMapping(method = RequestMethod.POST, value = "/ManageNonRoutedActivities")
public String updateOrCreateActivity(#Valid NonRoutedActivity nonRoutedActivity,
BindingResult result,
RedirectAttributes redirectAttributes) {
SecurityAccessor securityAccessor = new SecurityAccessor();
ArrayList<Message> messages = new ArrayList<>();
if (result.hasErrors()) {
return manageErrorsForManageNonRoutedActivities(result, nonRoutedActivity, redirectAttributes, messages);
}
if (nonRoutedActivity.shouldUpdateEndDate()) {
nonRoutedActivity.updateEndDate();
messages.add(new Message("endDate.add.success", "success"));
} else
messages.add(new Message("activity.add.success", "success"));
nonRoutedActivity.setModifiedBy(securityAccessor.getLoggedInUsersName());
nonRoutedActivity.save();
redirectAttributes.addFlashAttribute("messages", messages);
return "redirect:/ManageNonRoutedActivities";
}
The problem I'm having is that messages in the get part of the controller keeps coming out null. I originally had this messages instance as a List<Message> but this did not work since messages can be null. This caused an issue since List cannot be instanciated. This is why I am using ArrayList. This is not working though because the ArrayList is not binding correctly. Anyone know why this is happening and how to resolve this issue without creating a wrapper for the list?
So I'm not sure this is the best solution but the if I remove the name of the redirect attribute it works.

Categories

Resources