GetMapping After Postmapping - java

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")`

Related

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

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)

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.

ajaxform not submit the value if attachment is not available

I am a beginner in Java and go to create one web application. I am submitting one form to controller using ajaxform. There are few elements and one of them is type=file.
my controller method is as following
#RequestMapping(value = { "/addReplies" }, method = {
org.springframework.web.bind.annotation.RequestMethod.POST,
org.springframework.web.bind.annotation.RequestMethod.GET } )
#ResponseBody
public Map<String,Object> addReplies(
#Valid #ModelAttribute("Replies") Replies replies,
BindingResult result, HttpServletRequest request,
HttpServletResponse response,Locale locale,Principal principal,
#RequestParam(value = "fileData2",required=false) CommonsMultipartFile fileData2[]) throws ServletException,
IOException {
//perform some opraton
}
this everything is work properly if there is attachment available in data otherwise it does not go into this method.
if I remove #RequestParam(value = "fileData2",required=false) CommonsMultipartFile fileData2[] this parameter from method then work well but by this way I cannot get the attachment.
please try to understand my question and as soon as give me all possible solution.
This method is working well if I am not using ajax and submit form with regul
i also do this
but my coding also working
do this solution
#RequestMapping(value="/saveUserTask", method=RequestMethod.POST)
#ResponseBody
public Map<String,String> saveUserTask(
#RequestParam( value = "title" , required = false) String title,
#RequestParam( value = "projectid" , required = false) int projectid,
#RequestParam( value = "mileid" , required = false,defaultValue ="-1") int mileid,
#RequestParam( value = "responsible" , required = false) int responsible[],
#RequestParam( value = "startDate" , required = false) Date startDate,
#RequestParam( value = "endDate" , required = false) Date endDate,
#RequestParam( value = "description" , required = false) String description,
#RequestParam( value = "priority" , required = false, defaultValue="1") int priority,
#RequestParam( value = "workHours" , required = false) int workHours,
#RequestParam(value = "attachment" , required = false) MultipartFile myFile,
HttpServletRequest request,Principal principal,RedirectAttributes redirectAttributes,Locale locale) throws ParseException, IOException{
String fileAttachPath;
if(myFile!=null)
fileAttachPath=request.getSession().getServletContext().getRealPath("/WEB-INF/attechments/"+ new Date().getTime() + "_" + myFile.getOriginalFilename());
else
fileAttachPath="";
}
For uploading a file normally you need to use encType="multipart/form-data" in your form. If you want to use Ajax to upload a file, Along with Simple ajax call you need to use its methods
or
whey you are uploading the file, before Serialize the ajaxForm first check is it filepart is null or not, if its null then disable the element for longer availability and submit
beforeSerialize: function($form, options){
//before serializing the data have to disable element if the data is not avaliable
$(".attachfile").filter(function(){
return !this.value; }).attr("disabled", "disabled");
},
I just did this:
$("#myform").bind('ajax:complete', function() {
// tasks to do with ajax submit
});
And things worked perfectly.
See this api documentation for more specific details.
have you try this before to submit ajax form data object?
#RequestMapping(value ="/settingsSim",method=RequestMethod.POST)
#ResponseBody
public Map uploadSimSettings(#RequestBody String body) {
/*
some controller logic
*/
}

Catch GET request parameters in a Map<String,String>

I'm trying to catch key value pairs in a Map parameter at spring MVC side. This looks to me to be something simple but I can't wrap my head around it at the moment. Take following url
www.goudengids.be.localhost:8080/ms/view/sendContactForm.ajah?pageId=711408&listingId=685592&siteId=353009&url=http%3A%2F%2Fwww.goudengids.be.localhost%3A8080%2Fms%2Fms%2Fkbc-bank-versicherung-recht-4780%2Fms-353009-preview%2F&moduleId=65920100&mySiteId=353009&pageShortId=1&prefills[Naam]=janneke
You'll notice at the end my latest attempt to get this working prefills[Naam]=janneke. I like to catch this in the following controller.
public String getContactForm(#RequestParam(required = true) Long moduleId, #RequestParam(required = true) String url, #RequestParam(required=false) Map<String,String> prefills, Long mySiteId, Integer pageShortId,
DefaultPageParameters defaultPageParameters, ModelMap model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
However I'm recieving all parameters in the request in my prefills variable instead of just Naam,janneke. Is this even possible what I'm attempting or should I go with a large string with a token to tokenize ?
prefills=naam:janneke|title:maan|subject:space
I couldn't find a clean way out, so I went for the pragmatic solution
public String getContactForm(#RequestParam(required = true) Long moduleId, #RequestParam(required = true) String url, #RequestParam(required=false) List<String> prefills, Long mySiteId, Integer pageShortId,
DefaultPageParameters defaultPageParameters, ModelMap model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
private void prefillFieldsWithData(List<String> prefills, ModelMap model, BasicContactFormVo contactFormVo) {
if(prefills != null && !prefills.isEmpty()){
Map<String, String> valuesOfCustomFields = new HashMap<String, String>();
List<ContactFormElementVo> customFormElements = contactFormVo.getCustomFormElements();
for (String prefillData : prefills) {
if(prefillData.contains("|")){
String[] prefillFieldData = prefillData.split("|");
for (ContactFormElementVo contactFormElementVo : customFormElements) {
if(contactFormElementVo.getLabel().equals(prefillFieldData[0])){
valuesOfCustomFields.put("cfe"+contactFormElementVo.getId().toString(), prefillFieldData[1]);
break;
}
}
}
}
model.addAttribute("customFieldValues",valuesOfCustomFields);
}
}
It's a bit sad I have to do it this way, but it seems Spring has a generic way of detecting a Map as request parameter and filling it with all parameters in the request. There is no way around that except overloading that class which I rather do not considering it's part of the entire MVC mechanic.
I call the controller now with following URL. It works just ... meh ... not my favorite solution
http://www.goudengids.be.localhost:8080/ms/view/sendContactForm.ajah?pageId=711408&listingId=685592&siteId=353009&url=http%3A%2F%2Fwww.goudengids.be.localhost%3A8080%2Fms%2Fms%2Fkbc-bank-versicherung-recht-4780%2Fms-353009-preview%2F&moduleId=65920100&mySiteId=353009&pageShortId=1&prefills=Naam|janneke%20zag%20eens%20pruimen&prefills=E-mail|maan

Get a URL from an Action name: Struts 2

In struts 2 there is a struts tag where you can specify an action name and it gives you the url to that action:
<s:url action="action_name" />
I've been looking for a while now to see if it is possible to do this in an Struts2 Action/Interceptor. I found the class that relates to this struts tag I think (org.apache.struts2.components.URL) but can't figure out how to use it.
This is as far as I got but it might not be how to use it (if its possible at all) but any method I call after this just gives me NullPointerExceptions.:
public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
URL url = new URL(ai.getStack(), request, response);
url.setAction("login");
//e.g. url.start(<with stringwriter>);
}
Hoping this can be done as it would save a lot of troube!
Thanks.
EDIT
URL url = new URL(invocation.getStack(), request, response);
url.setActionMapper(new DefaultActionMapper());
String redirectUrl = url.getUrlProvider().determineActionURL("action_name",
invocation.getProxy().getNamespace(), invocation.getProxy().getMethod(),
request, response, request.getParameterMap(), "http", true, true, false, false);
This code does work and gives me a redirect URL but I was wondering if there was a way to get the CURRENT ActionMapper rather than create a new one. I've done a quick google but can't find anything.
Well this is the method in the component class inside struts2 which is creating action URL
protected String determineActionURL(String action, String namespace, String method, HttpServletRequest req, HttpServletResponse res, Map parameters, String scheme,
boolean includeContext, boolean encodeResult, boolean forceAddSchemeHostAndPort, boolean escapeAmp)
{
String finalAction = findString(action);
String finalMethod = method == null ? null : findString(method);
String finalNamespace = determineNamespace(namespace, getStack(), req);
ActionMapping mapping = new ActionMapping(finalAction, finalNamespace, finalMethod, parameters);
String uri = actionMapper.getUriFromActionMapping(mapping);
return UrlHelper.buildUrl(uri, req, res, parameters, scheme, includeContext, encodeResult, forceAddSchemeHostAndPort, escapeAmp);
}
now the question is how we can get various values for this
action=invocation.getAction();
namespace=invocation.getProxy().getNamespace();
methos= invocation.getProxy().getMethod();
similar other values can be find out from ActionIvocation
This is just an idea and i have not applied it myself.Hope it might help you.
Here is how I get the CURRENT ActionMapper rather than create a new one:
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.inject.Inject;
#Namespace("MyNamespace")
public class MyAction extends ActionSupport {
private ActionMapper actionMapper;
private UrlHelper urlHelper;
#Inject
public void setActionMapper(ActionMapper mapper) {
this.actionMapper = mapper;
}
#Inject
public void setUrlHelper(UrlHelper urlHelper) {
this.urlHelper = urlHelper;
}
private String getAbsoluteUrl(String actionName, String namespace) {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ActionContext context = ActionContext.getContext();
ActionInvocation invocation = context.getActionInvocation();
URL url = new URL(invocation.getStack(), request, response);
url.setActionMapper(actionMapper);
url.setUrlHelper(urlHelper);
return url.getUrlProvider().determineActionURL( //
actionName, //
namespace, //
"" , /* Method name */
request, response, //
request.getParameterMap(), "http", //
true, true, true, false);
}
// ...
}

Categories

Resources