Servlet + Jsp Issue - html

I have a JSP page, from where onClick I want to execute a servlet page. Can anybody help me, how can it possible ?

<input type="submit" value="Send" id="click" name="click"/>
if(request.getParameter("click")!=null)
{
request.sendRedirect("URL");
}
or
public class Dispatcher extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
RequestDispatcher dispatcher =
request.getRequestDispatcher("URL");
if (dispatcher != null) dispatcher.forward(request, response);
}
}
Google search for the difference between request.sendRedirect("URL"); and request.getRequestDispatcher("URL");

You could use an AJAX call to invoke the servlet if you don't want to reload the current page or perform a redirect using the window.location.href property. If you want to send some values to the server you could send them in the AJAX request body or as query string parameters if you decide to redirect.

<form method=GET action="servlet/nextPage">
some text here
<input type=submit>
</form>

You need a form with single button, and send form to the servlet
or you can use simple some text to be clicked or link under image
your Servlet must be described in web.xml or by annotation to let it be called.

Related

Thymleaf how to take an input and then redirect to another page

I'm learning Spring boot. I have a list of products with unique ids, and I want to implement a "lookup by id" functionality, but I don't know how to do it, I searched but got totally different stuff.
I already have a #Getmapping method like this:
#Getmapping(/products/{id})
If I manually type in the id in the url I'll get what I what. But I want to have an input box in the HTML page like:
<form>
Look up by id: <input/>
</form>
and after I submit the form it'll redirect to that page. For example, if I enter input of 1, it'll go to localhost:8080/products/1
I've been searching but all I got was stuff about #Postmapping.
Add a #PostMapping to your controller:
#Controller
#RequestMapping("/products")
public class ProductController {
#GetMapping //Controller method for showing the empty form
public String index(Model model) {
model.addAttribute("formData", new SearchFormData()); // Create an empty form data object so Thymeleaf can bind to it
return "index";
}
#PostMapping
public String searchById(SearchFormData formData) {
return "redirect:/products/" + formData.getId(); //Use the value the user entered in the form to do the redirect
}
#GetMapping("/{id}")
public String showProduct(#PathVariable("id") long id) {
...
}
}
With SearchFormData representing the form fields (there is only 1 field in this case):
public class SearchFormData {
private long id;
// getters and setters
And update Thymeleaf template like this:
<form th:action="#{/products}" th:method="post" th:object="${formData}">
<input th:field="*{id}" type="number">
<button type="submit">Search</button>
</form>
Note that the value of th:object needs to match with the name used to add the SearchFormData instance to the model.
See Form handling with Thymeleaf for more info.
The following simple code will direct you to a URL that is generated from a concatenation of the base address of the <form>'s action attribute and the value of its first <input>:
document.querySelector("form").addEventListener("submit",function(ev){
ev.preventDefault();
this.action="/product/"+this.querySelector("input").value;
console.log(this.action);
// in real code: uncomment next line!
// this.submit()
})
<form>
Look up by id: <input type="text" value="123" />
</form>
In the real code you will delete the console.log() und uncomment the following line: this.submit().
Alternatively you could also do:
document.querySelector("form").addEventListener("submit",function(ev){
ev.preventDefault();
location = "/product/"+this.querySelector("input").value;
})
This will redirect you to the page without actually submitting the form.

Submitting a post request but remain on the page using spring mvc

I have a simple reset password form screen. When the user submits via the Recover button the page posts to http://localhost:8080/api/v1/accountmanagement/user/password_reset . In that endpoint the user's email is validated then a hash is generated that is concatenated into a link which is sent by the system to the user via email. Everything works fine, its just that, what I want to happen is when the user clicks the recover button, I want them to remain on the recover password page. What I plan to do is to just unhide a div saying "Thank you for submitting a recover your password request etc.". Showing the div is not a problem (might be using plain javascript -- I don't have a js framework -- maybe use jQuery), its just that when the user clicks the recover button, the post request goes to the rest api therefore changing the page that is being displayed.
I tried to add target="_blank" in the form, but it didn't work. My front end is written in html and thymeleaf only.
There might be a simple solution out there that I'm just missing.
resetPassword.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<title>Reset Password</title>
<link href="css/main.css" rel="stylesheet"/>
</head>
<body>
<div>
<div>
<h2>Recover your password</h2>
<p>To recover your password follow the instructions below to reset your password.</p>
</div>
<form th:action="#{/api/v1/accountmanagement/user/password_reset}" method="post"
id="resetPasswordForm" th:object="${account}" target="_blank">
<div id="field_email">
<label for="email">Enter your email address :</label>
<p>Enter the email address with your account.</p>
<div><input type="text" id="email" name="email" th:field="*{email}"/></div>
</div>
<div id="successRecover" style="display: none;">
An email has been sent to your email address. The email contains instructions to reset your password.
</div>
<div th:if="${param.error}" class="login-panel_error error">Error.</div>
<div>
<button type="submit" class="btn-primary">
<i class="fa fa-spin fa-spinner hidden"></i>
<span>Recover</span>
</button>
</div>
</form>
</div>
</body>
</html>
PasswordManagementController.java
#Controller
#RequestMapping("/api/v1/accountmanagement")
public class PasswordManagementController {
#Autowired
private PasswordResetService passwordResetService;
private Logger LOG = LoggerFactory.getLogger(this.getClass());
#RequestMapping(value = "/user/password_reset", method = RequestMethod.POST)
public ResponseEntity processResetPassword(#ModelAttribute(value = "account") Account account,
BindingResult result, HttpServletRequest request) {
LOG.info("account email " + account.getEmail());
// build the hash here for hashUrl
if (account != null) {
if (!StringUtil.isBlank(account.getEmail())) {
try {
passwordResetService.processResetPassword(account, hashUrl);
} catch (AccountConfigException ace) {
// deal with exception here.
// return
} catch (Exception e) {
// deal with exception here.
// return
}
return new ResponseEntity(HttpStatus.OK);
} else {
// deal with an exception here.
// return
}
} else {
// deal with an exception here.
// return
}
}
}
If you're returning a ResponseEntity in the case of a successful request you will indeed be redirected.
I don't know how you handle errors but what you might want to do is changing the return type of your controller method to String. This way you can redirect to the same page in case of a successful response while passing a boolean value to the model that will decide to render your successRecover div, without needing any Javascript.
The new handler:
#RequestMapping(value = "/user/password_reset", method = RequestMethod.POST)
public String processResetPassword(#ModelAttribute(value = "account") Account account, Model model) {
// build the hash here for hashUrl
try {
passwordResetService.processResetPassword(account, hashUrl);
} catch (AccountConfigException ace) {
// deal with exception here.
// return
} catch (Exception e) {
// deal with exception here.
// return
}
model.addAttribute("isOK", true);
return "index";
}
And then in the view:
<div id="successRecover" th:if="${isOK}">
An email has been sent to your email address. The email contains instructions to reset your password.
</div>

Laravel 5.4: Submit a HTML form and receive a JSON response

Question: how can I communicate JSON back from a controller to my html page, and embed the response in my page, instead of destroying the page?
The long story is like this:
Embedded in a quite large html page (created by a view when I open my base URL, say, http://.../home) I have a html form. It has some data fields, and the usual "Submit" button.
<form class="form-horizontal" method="POST" action="{{ route('form.user') }}">
{{ csrf_field() }}
... lots of input fields ...
<div class="form-group">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</form>
The receiving route ...
Route::post('form/user','ItemController#save')->name('form.user');
And the controller ...
public function save(Request $request) {
...
return response()->json(['status' => 'Saved successfully']);
}
The whole thing works like intended, if I fill the form and hit the "Submit" button, the controller receives all input fields via the $request properties.
The problem arises after the return from the controller, the html is cleared from the browser, and the JSON is displayed.
What I need is receive the JSON and display it in a div of my original html, not replace it.
Question: what do I need to do, how can I hook into the communication to intercept and handle the JSON response, so I can display the response text in my original web page (using JQuery), and not destroy the html?
Thx, Armin.
Capture the FORM submit event, and prevent the default.
Construct an AJAX request
Dictate the response type.
Convert the form data to a serialized object to be sent to the server
Capture the returned response and apply it to a DIV.
That would look something like this:
$('form').on('submit', function(e){
e.preventDefault(); //1
var $this = $(this); //alias form reference
$.ajax({ //2
url: $this.prop('action'),
method: $this.prop('method'),
dataType: 'json', //3
data: $this.serialize() //4
}).done( function (response) {
if (response.hasOwnProperty('status')) {
$('#target-div').html(response.status); //5
}
});
});

Getting a file from html input field with vaadin

I have to use a HTML snippet to get an image from Android/iOS devices with
<input type="file" accept="image/*" capture="camera" />
which is displayed in a Label:
Label label = new Label("<input type=\"file\" accept=\"image/*\" capture=\"camera\" />");
label.setContentMode(Label.CONTENT_XHTML);
Because I'm using Vaadin on Liferay I'm not sure how to obtain the Image since there is no POST submit
How am I able to get this image?
You need to write custom Vaadin component which extends FormPanel. Thats not hard as it may sounds, just let Vaadin Widget creator generate classes for you and then replace auto-generated GWT component with the following code
public class CameraCaptureWidget extends FormPanel {
public CameraCaptureWidget() {
setEncoding(FormPanel.ENCODING_MULTIPART);
setMethod(FormPanel.METHOD_POST);
FileUpload f = new FileUpload();
this.add(f);
f.getElement().setAttribute("accept", "image/*");
f.getElement().setAttribute("capture", "camera");
f.addChangeHandler(new ChangeHandler(){
#Override
public void onChange(ChangeEvent event)
{
submit();
}
});
}
}
You can also add button instead of adding ChangeHandler on FileUpload itself.
After you are done with that you need to handle submit() event in the Connector. Example:
public CameraCaptureConnector() {
getWidget().addSubmitHandler(new SubmitHandler()
{
#Override
public void onSubmit(SubmitEvent event)
{
Window.alert("Hello world");
}
});
}
You may also need to remove some unnecessary auto-generated methods.
This solution generates this HTML code in DOM:
<input capture="camera" accept="image/*" class="gwt-FileUpload" type="file">
Should you encounter trouble, please make sure you have read https://vaadin.com/wiki/-/wiki/Main/Creating+a+simple+component

Forwarding the partial view's details to HttpPost method of a controller when button in partial view is clicked

Whenever following HttpGet method in controller is called it generates a partial view.
Controller HttpGet Method
[HttpGet]
public ActionResult AddCredit(Guid creditBalanceId)
{
var newCredit = new AddCredits()
{
CreditBalanceId = creditBalanceId
};
return PartialView(newCredit);
}
View
#model AdminPortal.Areas.Customer.Models.ViewModels.AddCredits
#Html.HiddenFor(m=>m.CreditBalanceId)
<div class="input-small" id="credit">#Html.EditorFor(m=>m.CreditToAdd) </div>
#Html.ActionLink("Add","AddCredit", new {#class="btn"})
Whenever Add button is clicked in the partial view, I want it to be forwarded to HttpPost method of my controller with HiddenFor(CreditBalanceId) and CreditToAdd value
[HttpPost]
public ActionResult AddCredit(AddCredits credits)
{
_businessUnitRepository.AddCredits(credits);
Information("Credits Successfully added!");
return RedirectToAction("LicenseDetails");
}
Question
What changes do I need to make to my view so that when the button is clicked, i get forwarded to httppost method in controller with all the values?
Have you tried this?
#using(Html.BeginForm("Add", "AddCredit"))
{
#Html.HiddenFor(m=>m.CreditBalanceId)
<div class="input-small" id="credit">#Html.EditorFor(m=>m.CreditToAdd) </div>
<button type="submit" class="btn">Add Credit</button>
}
You could do it quite easily using something like Html.BeginForm and an type of submit. This link is a pretty good example MVC4 forms that save to entity framework models