Redirrect from to JSP to #RequestParam - java

So I'm having this code in a JSP file:
<form action="/demo/quests/view?questId=${m.id}" >
<button type="submit" class="btn btn-primary" >See quest</button>
</form
My method has this definition:
RequestMapping(value = "/view", method = RequestMethod.GET)
public String displayQuest(#RequestParam(value = "questId") String questId, Model model){}
The problem is that my form is redirrecting to quests/view?
How can I make it redirrect to quests/view?questId=asdasdasd
**Using #requestParam is a must, because with #PathVariable I get a weird bug

Your method definition is ok but you should use your form submission as :
<form action="${pageContext.request.contextPath}/demo/quests/view">
<input type="text" class="form-control" id="questId"
name="questId" required>
<button type="submit" class="btn btn-primary" >See quest</button>
</form
#RequestParam handles that there is a parameter with name questId which is described at your #RequestParam(value = "questId") method signature. You can check an exact example from my github repo.
Form Sample: modalAuthor.jsp#form
Handler Method Sample AuthorController#authorPost

Replace
<form action="/demo/quests/view?questId=${m.id}" >
with
<form action="view?questId=${m.id}" >

Related

BindingResult error from submitting a form with two request parameters

Below is code from a controller that I'm aiming to make sure it's receiving two input parameters (name and code) from a front-end interface.
It's a page that takes two parameters within a submit form, "name" and "code".
#RequestMapping(method = RequestMethod.POST)
public String transfer(#RequestParam(name = "name") String name,
#RequestParam(name = "code") String code,
Errors errors, RedirectAttributes redirectAttributes) {
if (errors.hasErrors()) {
return "htmlPageOne";
}
try {
User userToBeTransferred = usersRepository.findByName(name);
userToBeTransferred.setTransferred(true);
Region regionOfTransference = regionsRepository.findByCode(code);
regionOfTransference.setPopulationNumber(regionOfTransference.getPopulationNumber() + 1);
userToBeTransferred.setRegion(regionOfTransference);
usersRepository.save(userToBeTransferred);
regionsRepository.save(regionOfTransference);
return "redirect:/section/users/new";
} catch (IllegalArgumentException e) {
return "htmlPageOne";
}
}
The front-page form :
<form class="form-horizontal" method="POST" action="/section/users/new" th:object="${user}">
<input type="hidden" th:field="*{id}"/>
<div class="form-group row">
<label for="name" class="col-form-label">User name</label>
<input type="text" class="form-control" id="name" th:field="*{name}" name="name"/></div>
<div class="form-group row">
<label for="code" class="col-form-label">Code</label>
<input type="text" class="form-control" id="code" th:field="*{region.code}" name="code"/></div>
<button type="submit" class="btn btn-primary col-sm-6 ">Save</button>
</form>
For some reason, I'm getting the following error after I click to submit the form :
There was an unexpected error (type=Internal Server Error, status=500).
An Errors/BindingResult argument is expected to be declared immediately after the model attribute, the #RequestBody or the #RequestPart arguments to which they apply: public java.lang.String
I'm not sure if I'm using the requestparams correctly, so maybe it's got something to do with this? I don't know, I've been stuck on this for a few hours now, so would appreciate if someone could help me.

Pass data between different html pages and controllers in spring

Hi I'm new with Spring and I'm having problems in passing data between two pages using two different controllers.
I would like to know how I can handle this situations.
In my index.html I have a button that should redirect me to a new page passing some data. When i click the button it redirects me to the step2 page but I don't have to objects. How can I solve this? Is the GET method correct? Do I have to use the form just for passing some data between pages and controllers?
Below is what I have.
Index.html
<form th:action="#{/step2}" method="GET">
<input type="hidden" th:value="${mapSelectedServices}" name="mapSelectedServices"/>
<input type="hidden" th:value="${user}" name="loggedUser"/>
<div class="form-group d-flex align-items-center justify-content-between">
<button type="submit" class="btn btn-danger btn-rounded ml-auto" >SEE PRICES
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</div>
</form>
Step2Controller
#RequestMapping(value="step2", method = RequestMethod.GET)
public ModelAndView step2(ModelAndView modelAndView, #ModelAttribute("user") User user,
#ModelAttribute("mapSelectedServices") HashMap<String,List<ServiceOffered>> mapSelectedServices,
BindingResult bindingResult){
modelAndView.addObject("user", user);
modelAndView.addObject("mapSelectedServices", mapSelectedServices);
modelAndView.setViewName("step2");
return modelAndView;
}
Sorry for all the questions, but I'm new to spring development.
HTML page:
<form th:action="#{/step2}" method="POST">
<input type="hidden" th:value="${mapSelectedServices}" name="mapSelectedServices"/>
<input type="hidden" th:value="${user}" name="loggedUser"/>
<div class="form-group d-flex align-items-center justify-content-between">
<button type="submit" class="btn btn-danger btn-rounded ml-auto" >SEE PRICES
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</div>
</form>
Controller method:
public ModelAndView goToPgae2(#ModelAttribute ModelClass aClass)
{
ModelAndView mv=new ModelAndView("SecondHtlmPageName");//setting view name here
mv.addAttribute("aClass",aClass);
return mv;
}
Model Class with the specific variables passed from one page to another:
class ModelClass {
public Stirng mapSelectedServices; //use appropriate data type.
public String loggedUser;
//create getters and setters
}
Second page
<div>${aClass.loggedUser}</div>
DONE.
This way you can go to second page . And if you want to redirect to second page and the model attributes should be available there then you need to use flashattribute.

Submit text to same HTML page

I have made a text field and a submit button in my view in the admin page, and i want to do so the text i submit is shown below my textbox on the same page.
This is my controller for getting to the adminPage:
#RequestMapping(value = "/adminPage", method = RequestMethod.POST)
public String adminPage(Model model) {
return "adminPage";
}
this is what i have for my adminPage:
<form th:action="#{/adminPage}" method="post">
<textarea rows="4" cols="50">
</textarea>
<input type="submit" class="btn btn-lg btn-primary btn-block"
value="Submit Text"/>
</form>
I'm still very new at controllers and MVC in general, and i find it hard to use my knowledge in Java because Controllers doesn't look like any Java i've used before, so any help would be appreciated!
ok then, no Javascript. First, textarea needs a name attribute name="inputText".
That name will be used in the model object when your server method receives the request:
#RequestMapping(value = "/adminPage", method = RequestMethod.POST)
public String adminPage(#RequestParam("inputText") String input, Model model) {
//Do stuff
model.addAttribute("theText", input); //add the text which can be accessed on "adminPage"
return "adminPage";
}
then you can add a <div> in "adminPage.jsp" and append your text there, like:
<div>${theText}</div>
If, I have understood your problem correctly than here is the workaround that will do the job.
When user visits /adinPage from browser than input_data variable will be null and the if condition won't be executed.
The JSP page will be returned with second textarea as blank.
You have to use JSP because HTML pages can't be altered.
Controller.java
#RequestMapping(value = "/adminPage", method = RequestMethod.POST)
public String adminPage(#RequestParam(value = "input_data", required = false) String input_data,Model model)
{
if(input_data!=null)
model.addAttribute("output_data",input_data);
return "adminPage";
}
adminPage.jsp
<form th:action="#{/adminPage}" method="post">
<textarea id="input_data" rows="4" cols="50">
</textarea>
<textarea rows="4" cols="50">
${output_data}
</textarea>
<input type="submit" class="btn btn-lg btn-primary btn-block"
value="Submit Text"/>
</form>
When the user submits the form, the if condition will be executed and the returned view will contain the previously input data in second textarea
I haven't tested the code so, it might contain some syntax errors.

Different actions using same REST calls

I am building an application which has same functionalities both from AWS and Google Cloud. For example Creating an instance , Launching instance from Machine ID, Creating snapshot, Liting all Instances,etc. Which I called using REST calls.
For example:
<form method="post" action="rest/create/new" class="form-inline">
<label for="user">User Name</label> <input type="text" id="user"
name="user" class="form-control" size="50"
placeholder="Enter Username">
<button type="submit" class="btn btn-info">Start New Machine</button>
</form>
<form method="post" action="rest/launch/start" class="form-inline">
<label for="AMId">Launch Existing Machine</label><br> <input
type="text" id="AMId" name="AMId" class="form-control" size="50"
placeholder="Enter Instance ID">
<button type="submit" class="btn btn-info">Launch</button>
<br>
</form>
<br> <br>
<form method="get" action="rest/create/listAll" class="form-inline">
<label>Show All EC2 Instances</label><br>
<button type="submit" class="btn btn-info btn-lg">Show All</button>
</form>
<br> <br>
<form method="post" **action="rest/create/listRunning"**>
<label>Show All Running EC2 Instances</label><br>
<button type="submit" class="btn btn-info">Show All Running</button>
</form>
<br> <br>
<form method="post" action="rest/create/terminate" class="form-inline">
<label for="terminateID">Enter Instance ID</label><br> <input
type="text" id="terminateID" name="terminateID" class="form-control"
size="50" placeholder="Enter Machine ID">
<button type="submit" class="btn btn-info">Terminate</button>
</form>
<br> <br>
And I am catching these rest calls in classes.
For example,
#GET
#Path("/listAll")
public Response getAllAvailableImages(#Context ServletContext context)
Now what I want is how can I use both AWS and google cloud features, using these same calls or some other method,depending on requirement or choice?
How about:
GET /{provider}/images
POST /{provider}/images/{imageID}/start
where the variables in braces are placeholders for path parameters:
{provider} may resolve to AWS, Google or another provider
{imageID} references a unique image ID
Examples:
GET /AWS/images (gets all AWS images)
POST /GoogleCloud/images (creates new Google Cloud image)
POST /OpenStack/images/gfhdh45ff4/terminate (terminates a specific image)
If you are using Spring MVC for REST, the controller could look like:
#RestController
public class ImageController {
#Autowired
private ImageService imageService;
#RequestMapping(value = "/{provider}", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public List<Image> getImages(#PathVariable String provider) {
return imageService.getImagesByProvider(provider);
}
#RequestMapping(value = "/{provider}", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public Image createNewImage(#PathVariable String provider, #RequestBody Image image) {
return imageService.createImageForProvider(provider, image);
}
#RequestMapping(value = "/{provider}/images/{imageId}/start", method = RequestMethod.PUT)
#ResponseStatus(HttpStatus.NO_CONTENT)
public void startImageAtProvider(#PathVariable String provider, #PathVariable String imageId) {
return imageService.startImageAtProvider(provider, imageId);
}
}
The HTTP method for starting the image could be POST - and should be if starting an image is not idempotent. But I am assuming hat attempting to start an image which is already running will just be ignored.
Extra edit:
If the image IDs are unique across ALL providers, you could shorten the REST URLs regarding images:
POST /images/gfhdh45ff4/terminate (terminates a specific image)

How to retrieve form elements at controller in java

I am trying to submit a form to controller in using java spring, in following code i am retrieving file element by following way successfully but not getting how to retrieve other elements(shortname and full name)value.
please help me out.
<body>
<div style="text-align: center; margin-top: 60px;">
<form action="upload" enctype="multipart/form-data">
<input type="hidden" id="shortName" name="michael">
<input type="hidden" id="fullName" name="michael jackson">
Select file:
<input type="file" name="dataFile" id="fileAttachment"/><br/><br/>
<div style="text-align: center; margin-top: 100px;">
<input style="cursor: pointer;" onmouseover="" onclick="uploadAttachment()" class="dialogbox" type="submit" value="Upload Report" />
</div>
</form>
</div>
</body>
Controller side code :
#RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response,
#RequestPart("dataFile") MultipartFile file
){
System.out.println(file.getSize());
}
first change the input elements and create the name attribute for both shortName and fullName like so :
<input type="hidden" id="shortNameId" name="shortName" value="michael">
<input type="hidden" id="fullNameId" name="fullName" value="michael jackson">
however you can remove the default value attribute and just enter the value yourself when the page render so value="michael" & value="michael jackson" are optional !
Then you can retrieve those input elements like this :
#RequestMapping(value = "upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, HttpServletResponse response, #RequestParam("shortName")String shortName, #RequestParam("fullName")String fullName
#RequestPart("dataFile") MultipartFile file
){ .... }
Good Luck !
In your controller, try something like this,
#RequestMapping(value = "/your/url/{formParamenter}", method = RequestMethod.GET)
public String yourfunction(#PathVariable("formParameter") Type formParameter{}
The Type is the type of data, (String/int/float..etc).
In your case just change RequestPart to #PathVariable

Categories

Resources