Set param in url from jsp form - java

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!

Related

How can I call a method from the controller into thymeleaf without changing the URL

I have a html page with Thymeleaf and i have a button in that page. That button it is calling a method from the controller that i have mapped with /addService but it return the /index page(Because I'm already in that page and i want to remain in it). Therefore, when i press the button it is redirecting me to the index page but the URL is changed with /addService. I would like to remain in the index page without the /assService in the URL. Below my code of the form and of the controller. How can I avoid this behaviour?
Thanks in advance.
My index.html
<form action="#" th:object="${serviceOffered}" th:action="#{addService}" method="POST">
<input type="hidden" th:value="${serviceOffered.name}" name="name"/>
<button type="submit" class="btn">
<i class="fas fa-plus"></i>
</button>
</form>
My controller
#RequestMapping(value="addService", method = RequestMethod.GET)
public ModelAndView getServiceSelected() {
ModelAndView modelAndView = new ModelAndView();
ServiceOffered serviceOffered = new ServiceOffered();
modelAndView.addObject("serviceOffered", serviceOffered);
modelAndView.setViewName("/index");
return modelAndView;
}
Use redirect
modelAndView.setViewName("redirect:/");
And define your url "/"
#GetMapping("/")
public String indexPage() {
return "index":
}
Assuming that you use Spring MVC you should change your RequestMethod to POST, because you're POSTing a form. Otherwise the request is not handled correctly.

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"

Http status 400 -The request sent by the client was syntactically incorrect. Spring MVC

I spent a lot of time on this problem, but can`t resolve it. Please Help! When I submit form from JSP I get this error.
My code:
<form action="/albums/add" method="post">
<%--<div><input type="file"></div>--%>
<div>Name: <input type="text" name="name" placeholder="Name"></div>
<div>Year: <input type="text" name="year" placeholder="Release year"></div>
<div>
<select name="singer" id="singer">
<c:forEach items="${singers}" var="s">
<option value="${s.id}">${s.name}</option>
</c:forEach>
</select>
</div>
<input type="submit" >
And my controller code:
#RequestMapping(value = "", method = RequestMethod.GET)
public String albumsGET(ModelMap map) {
List<Album> albums = albumDAO.getAllAlbums();
map.addAttribute("albums", albums);
return "forward:/Albums.jsp";
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String albumsAddGET(ModelMap map) {
map.put("singers", singerDAO.getAllSingers());
return "forward:/WEB-INF/Pages/Album/AddAlbum.jsp";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String albumsPOST(#ModelAttribute Album album, HttpServletRequest req) {
Singer s = singerDAO.getSingerById(Long.valueOf(req.getParameter("singer")));
s.getAlbumList().add(album);
album.setSinger(s);
singerDAO.updateSinger(s);
return "redirect:/albums";
}
}
You can throw custom exception provided by spring, create class with #ControllerAdvice annotation and throws custom exception with different HTTP status code
That is parameter mapping error for #ModelAttribute which HTTP return code 400.
There are some reasons that rises this error.
There is no parameter name for your Album Object.
There are NULL value for mapping Album Obejct.
So, if you can check item ${singers}, you should check substituted properly value.
Next, in Album Object, you should check getter/setter method.
I could have resolved that issue to setting default values for Object (etc. VO)

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

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.

Getting error msg upon form submission: "The request sent by the client was syntactically incorrect"

I'm working on a Web application developed using the Spring framework, version 3.1.0.
I have a JSP page containing a form which allows the user to select a country from a SELECT dropdown listbox. Submitting the form is supposed to run a database query and return the same JSP page which includes the form as well as an HTML table of author and institute data for the selected country.
Here's part of the code for the JSP page:
<c:url var="submitUrl" value="/authorsInstitutes.htm"/>
<form:form action="${submitUrl}" method="POST">
<select id="countryCode">
<option value="-1">-- Please Select --</option>
<c:forEach var="country" items="${countryList}">
<option value="${country.countryCode}">${country.countryName}</option>
</c:forEach>
</select>
<input type="submit"/>
</form:form>
and here's the code from the controller class, for the methods that handle the 'GET' and 'POST' requests:
#RequestMapping(value = "/authorsInstitutes", method = RequestMethod.GET)
public ModelAndView displayAuthorsInstitutesForm() {
ModelAndView mav = new ModelAndView("authorsInstitutes");
List<Country> countryList = countrySrv.findAll();
mav.addObject("countryList", countryList);
return mav;
}
#RequestMapping(value = "/authorsInstitutes", method = RequestMethod.POST)
public ModelAndView displayAuthorsInstitutes(
#RequestParam(value = "countryCode") String country) {
ModelAndView mav = new ModelAndView("authorsInstitutes");
List<Country> countryList = countrySrv.findAll();
mav.addObject("countryList", countryList);
if (country != null && !country.trim().equals("")) {
List<Affiliation> affiliationList =
affiliationSrv.getAffiliationsByCountryCode(country);
mav.addObject("affiliationList", affiliationList);
}
return mav;
}
The 'GET' request works fine, but when I select a country and submit the form, I get a 404 error message:
HTTP Status 400 - type Status report message
description The request sent by the client was syntactically incorrect
().
I'm sure it's something simple, but for the life of me, I'm just not seeing what it is that I'm doing wrong. I'd appreciate any help on resolving this, thanks.
Using Firebug or any similar tool , check if countryCode parameter is passed to server.
Also i see request mapping is
#RequestMapping(value = "/authorsInstitutes", method = RequestMethod.POST)
where as request is sent to /authorsInstitutes.htm
As we have a request parameter countryCode in the POST method mapping. The controller expects that the parameter is sent in the request. This is in the below code
#RequestMapping(value = "/authorsInstitutes", method = RequestMethod.POST)
public ModelAndView displayAuthorsInstitutes(#RequestParam(value = "countryCode") String country) {
}
Change the select tag in the jsp to include a name attribute like this.
<select id="countryCode" name="countryCode">
<option value="-1">-- Please Select --</option>
<c:forEach var="country" items="${countryList}">
<option value="${country.countryCode}">${country.countryName}</option>
</c:forEach>
</select>
<input type="submit"/>
This will assign the contryCode to the option selected.
Try this i hope it will work.
You need to remove slash from your url in url tag, like this:
<c:url var="submitUrl" value="authorsInstitutes.htm"/>
if you use absolute path with slash in jsp, form will not send data.

Categories

Resources