How to retrieve form elements at controller in java - 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

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.

Spring Boot Forms; hiding the path value and showing placeholder

I am having a small issue with Spring Boot forms displaying the information of the path value instead of the placeholder once you get to the editProfile.jsp. I want the input field to look like this;
Edit Profile Page instead of this Wrong Edit Profile. I do not want my users to have to click, select and delete the auto completed value. I want it to show the placeholder only and allow them to overwrite what is shown with ease.
This is the editProfile.jsp
<%--#elvariable id="editProfile" type=""--%>
<form:form method="POST" modelAttribute="editProfile">
<div class="MyForm form-group">
<h1>Edit Profile</h1>
<form:input type="email" class="MyInput" id="email" path="email" placeholder="${editProfile.email}" />
<form:button type="submit" class="from-control">Submit</form:button>
</div>
<div>
<img src="images/reg1.png" alt="picture">
</div>
</form:form>
</body>
</html>
This is the code specified in the Controller
#RequestMapping(value = "edit/{email}", method = RequestMethod.GET)
public String getEditUserData(#PathVariable("email") String email, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
model.addAttribute("editProfile", accountInstance);
return "editProfile";
}
#RequestMapping(value = "edit/{email}", method = RequestMethod.POST)
public String enterEditUserData(#ModelAttribute("login") AccountEntity accountForm, #PathVariable("email") String email, Model model ) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
accountInstance.setEmail(accountForm.getEmail());
accountRepo.save(accountInstance);
return "redirect:/login";
}
I have figured it out; You have to add a model of a new Entity, so the path variable does not fill in with the instance of the specific path value. Here is the new code, and compare it to the one I sent above.
#RequestMapping(value = "edit/{email}", method = RequestMethod.GET)
public String getEditUserData(#PathVariable("email") String email, Model model) {
AccountEntity accountInstance = accountRepo.findByEmail(email);
model.addAttribute("editProfile2", new AccountEntity());
model.addAttribute("editProfile1", accountInstance);
return "editProfile";
}
<%--#elvariable id="editProfile" type=""--%>
<%--#elvariable id="editProfile2" type=""--%>
<form:form method="POST" modelAttribute="editProfile2">
<div class="grid form-group">
<h1>Edit Profile</h1>
<form:input type="email" class="MyInput" id="email" path="email" placeholder='${editProfile1.email}' />
<form:button type="submit" class="from-control">Submit</form:button>
</div>

Redirrect from to JSP to #RequestParam

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}" >

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)

Problems with bootstrap form and POST Method

i was making a simple page with a formulary using bootstrap and Eclipse (With JBoss).
Html code(Just < body > part):
<div class="jumbotron">
<div class="container">
<form method="POST" class="form-inline" action="validarIngresoAdmin.htm">
<h4>Ingrese sus datos:</h4>
<input type="text" class="form-control input-sm" placeholder="Email" name="txtEmail">
<input type="password" class="form-control input-sm" placeholder="Password" name="txtPsw">
<button type="submit" class="btn btn-danger">Iniciar sesi&#243n</button>
</form>
</div>
but when i try to get the attributes txtEmail and txtPsw they return null.
Eclipse code:
private void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter pw = response.getWriter();
String email = (String)request.getAttribute("txtEmail");
String pass = (String)request.getAttribute("txtPsw");
}
¿Why 'email' and 'pass' attributes return null?
P.S: Sorry about my english.
Thanks.
To retrieve http variables, you should be using getParameter rather than getAttribute.

Categories

Resources