Doing an ActionRequest call from JS/jQuery/Ajax in Spring MVC - java

I'm trying to redirect to a portlet with specific parameters from JavaScript. I take parameters based on which link the user clicks (this part is OK, I get all the data I need), and afterwards construct an URL which I try to get with simple JS window.location..
My Controller:
#RenderMapping
public String view(Model model){
model.addAttribute("some", "stuff");
return "myPortlet/view";
}
#ActionMapping(params = "action=importantAction")
public void doAction(ActionRequest request, ActionResponse response){
String foo = request.getParameter("one");
String bar = request.getParameter("two");
System.out.println("Got " + one + " & " + two);
}
My JS:
function myFunction(one_val, two_val){
window.location = "http://www.my.url.com/nameOfMyPortlet?one=" + one_val +
+ "&two=" + two_val + "&action=importantAction";
}
This redirects to the correct page, however the action parameter keeps getting ignored and the whole doAction method doesn't get executed.
How to pass the action parameter to the target portlet from JavaScript?
I'm using Liferay & Spring MVC..
Thanks!

Did you try creating action URL using below way ?
var portletURL = new Liferay.PortletURL('ACTION_PHASE');
portletURL.setWindowState("maximized");
In portletURL you can set your desired parameter for calling your action.
Below link for reference
http://www.liferay.com/web/eduardo.lundgren/blog/-/blogs/liferay-portleturl-in-javascript

I've managed to find a way how it works - it's very similar to what #Ankit P wrote:
I have created hidden fields for the parameters and then sent the form which creates the URL:
JSP:
<liferay-portlet:actionURL var="link">
<liferay-portlet:param name="action" value="importantAction"/>
</liferay-portlet:actionURL>
<form action="${link}" method="POST" name="the-form" id="the-form">
<input type="hidden" value="" name="one" id="one"/>
<input type="hidden" value="" name="two" id="two"/>
</form>
JS:
function myFunction(one_val, two_val) {
document.getElementById("one").value = one_val;
document.getElementById("two").value = two_val;
document.getElementById("the-form").submit();
}
Controller stays the same. To use #ActionMapping you have to use POST method.

Related

Getting 404error when trying to display a jsp

I am trying to get the value of a form from a jsp to use in a function in the controller and display another jsp
<form action="/uc">
<input name="cnp" type="text">
<br>
<br>
<input type="submit" value="Find">
</form>
This one is my Controller method
#RequestMapping(value = "/uc", method = RequestMethod.GET)
public String userContracts(#RequestParam("cnp") String cnp, Model model)
{
List<Contract> ContractList = new ArrayList<Contract>();
ContractList = cl.getContractsOfUser(cnp);
model.addAttribute("ContractList", ContractList);
System.out.println("In uc");
return "UserContracts";
}
Thanks pedram ezzati for the help!
The problem was that I had to use
<form action="http://localhost:8080/SpringWebTemplate/uc.html">
My previous attempts where either without the .html or just using /uc
Make sure your package is scan while spring come up.
In app-config.xml file check below tag
context:component-scan base-package="com.test.ashok"

Getting data from jsp to Servlet [duplicate]

public class Relay extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
RequestDispatcher rd =request.getRequestDispatcher(command);
rd.forward(request, response);
System.out.println("Request forwarded to " + command + " servlet");
}
}
This is my Relay servlet, I'm sending data from this form
<form action="Relay" method="POST" enctype="multipart/form-data"> /
<input type="hidden" name="command" value="AddProduct" />
<input type="text" name="pname" value="" />
<input name="" type="submit" value="Add Product">
</form>
It is throwing a java.lang.NullPointerException.
But works fine when I remove this:
enctype="multipart/form-data"
Why do you need to add it then? Just keep it out.
If you need it in order to upload a file by <input type="file"> which you intend to add later on, then you should put #MultipartConfig annotation on your servlet, so that request.getParameter() will work and that all uploaded files can be retrieved by request.getPart().
#WebServlet("/Relay")
#MultipartConfig
public class Relay extends HttpServlet {
// ...
}
See also:
How to upload files to server using JSP/Servlet?
Parameters encoded with multipart/form-data are sent in POST body - not as regular request parameters, therefore can't be read using request.getParamter(...).
Check out Commons file upload package for multipart requests processing.
I am including this just for additional information for troubleshooting.
if you are stuck and want to know about what all parameters are coming through multipart request you can print all parameters using following code.
MultipartRequest multi = <Your code to retrieve multipart request goes here. Sorry but can not post code as I use proprietary APIs>
Enumeration en1 = multi.getParameterNames();
while (en1.hasMoreElements()) {
String strParamName = (String)en1.nextElement();
String[] strParamValues = multi.getParameterValues(strParamName);
for (int i = 0; i < strParamValues.length; i++) {
System.out.println(strParamName + "=" + strParamValues[i]);
}
}
remove the form tag and use
echo <?php form_open_multipart('Controller/function');
I got the same issue whenever I use enctype="multipart/form-data"
I didn't get the file name and when I remove that it was working fine
try it it worked for me

Set param in url from jsp form

i have a few questions to jsp and spring mvc..
I need get id value from jsp form and set in url for send request on /request/{id}
My jsp page:
<form action="/get-by-id/{id}" method="post">
<input type="text" name="id">
<input type="submit" name="Submit">
</form>
and code controller for 3 question:
#RequestMapping(value = "/change-pupil/{id}", method = RequestMethod.GET)
public String changePupil(#PathVariable("id") int id, #ModelAttribute Pupil pupils){
System.out.println(id + " " + pupils.toString());
return "redirect:/main";
}
#RequestMapping(value = {"/","/main"}, method = RequestMethod.GET)
public String index(){
return "index";
}
how to get value from input and install it in the url?
I create method in controller which get id and send this id to next page and from next page send request with id in url to controller, but this method very bad
how move from page to page without using a controller methods?
How return main page without index()?
Thanks for the help!

spring-mvc : how to pass parameters in mvc without method arguments at the controller

I was being tasked to create my controllers without passing any parameters at the method signature.
I am quite baffled as this is quite challenge and I haven't really seen any examples at the net.
For example: from my jsp page.
<form:form method="POST" action="/project/searchResults" id="productSearchResultsForm">
<input name="productRecord" id="productRecord" />
<input name="resultEntity" id="resultEntity" type="hidden" />
<input name="resultCode" id="resultCode" type="hidden" />
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form:form>
I wanted to pass these three inputs to my controller without using #RequestParameter and #ModelAttribute at the method signature. As of now this is the only way I know how to do this.
#RequestMapping(value = "/productSearch", method = RequestMethod.GET)
public ModelAndView init(#ModelAttribute ("showroomCode") String showroomCode, HttpServletRequest request) {
logger.info("<<<< initial page <<<<<<");
logger.info("Showroom Code : " + showroomCode);
HttpSession session = request.getSession();
ModelAndView model = new ModelAndView("productSearch", "command",
String.class);
ShowroomUser user = new ShowroomUser();
user.setUserId(1);
session.setAttribute("usersession", user);
session.setAttribute("showroomCode", showroomCode);
logger.info(">>>>> initial page >>>>> ");
return model;
}
I know that in Struts 2, you can just declare global variables in the Action class so you can automatically use them in the method without literally putting them in the method signature. Is there are way to remove this?
Thanks.
Update
I am asked not to use HttpServlet Request and Model Attributes at all anywhere in the code. :(
Please help!
1) Create a form POJO with your attribute productRecord, resultEntity, resultCode. Ex MyForm.java
2) Set this form in the model (in your init method) Ex : model.addAttribute("myForm", new MyForm())
3) In your jsp form declaration set :
<form:form commandName="myForm" >
4) In your controller (to retrieve result)
#RequestMapping(value = "/productSearch", method = RequestMethod.POST)
public ModelAndView postForm(MyForm myForm, HttpServletRequest request) {...}
Then you can access values using myForm.getProductRecord() for example.
I don't know why you'd ever want to do this..
But, Spring exposes the request as a ThreadLocal. You can access it on the current thread but you can't on any spawned threads without passing it.
Here's what you do:
#RequestMapping("/whatever")
public ModelAndView controllerMethod() {
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest();
// Do as you want with the request without having to pass it in
}

The request sent by the client was syntactically incorrect - Spring mvc

I am facing an issue with submitting the value to the controller in Spring MVC.
When I call the controller with href it gets submitted to the controller method, I have submitted the following way :
href='CIMtrek_Compliance_Daily_Shipments_Case_Pack_Calendar?date=<%=formatedDate%>'
but when I submitted the same through javascript I get this exception The request sent by the client was syntactically incorrect.
this is how I submit through javascript :
function getCasePackCalendar(date) {
viewName ="CIMtrek_Compliance_Daily_Shipments_Case_Pack_Calendar?date="+date+" ";
global.forms[0].action = viewName;
global.forms[0].method = "GET"
global.forms[0].submit()
}
and this is my controller method :
#RequestMapping(value = "/CIMtrek_Compliance_Daily_Shipments_Case_Pack_Calendar", method = RequestMethod.GET)
public ModelAndView CIMtrek_Compliance_Daily_Shipments_Case_Pack_Calendar(#RequestParam("date") String date,HttpServletRequest request) {
String[] data = new String[] {date};
HttpSession session = request.getSession(true);
String UserName = "";
if(session.getAttribute("CIMtrek_UserName")!=null)
UserName = session.getAttribute("CIMtrek_UserName").toString();
ViewContent vc = new ViewContent();
String HTML = vc
.getContent(
"com/cim/xml/CIMtrek_Compliance_Daily_Shipments_Case_Pack_sql.xml",
"com/cim/xsl/view.xsl", "1 and 10","1","","0",UserName,data,"");
List<String> ls = new ArrayList<String>();
ls.add(HTML);
logger.info("Welcome CIMtrek_Visitors_By___Unipart_Div__Date__Host___Visitor!");
Map<String, Object> model = new HashMap<String, Object>();
model.put("list", ls);
model.put("iSPost", "N");
logger.info("Welcome CIMtrek_Compliance_Daily_Shipments_Case_Pack!");
return new ModelAndView("view", model);
}
this is how I have form
<form id="CIMtrek_Compliance_Daily_Shipments">
<input type="hidden" id="CIMtrek_selectedIDs" name="CIMtrek_selectedIDs" value="" />
<input type="hidden" id="CIMtrek_xmlData" name="CIMtrek_xmlData" value="" />
<input type="hidden" id="CIMtrek_formName" name="CIMtrek_formName" value="CIMtrek_Compliance_Daily_Shipments" />
</form>
what could be the problem.
Please help me to find it.
Best Regards.
Please use some debug tool(for example in Chrome use F12->Network tab, or use Firefox Firebug to see the request formed from the browser) In this case you are putting form parameters into the view name (even adding some strange space symbol in quotes after the parameters) in your client js - it does not seem to be right.
I suggest you to make a separate controller method that processes your form.
In this case your form is incorrectly serialized(actually the correct html form serialization/parameter passing is regulated by several RFC).

Categories

Resources