How to get an HTML data form to my web service? - java

I'm working on a project and I'm trying to get an HTML form data into my REST web service, so I can insert it into my database, I don't know where to get the HTML form data from.
This is my web service:
package hananepkg;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* #author mon pc
*/
#Path("generic")
public class GenericResource {
DBConnector db = new DBConnector();
#Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of pkg.GenericResource
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.TEXT_HTML)
public String insert(#QueryParam ("name")String name,#QueryParam ("email")String email,#QueryParam ("password")String password,#QueryParam ("confirmpassword")String confirmpassword) {
//TODO return proper representation object
return "<html><body><h1>"+db.insertData(name,email,password,confirmpassord)+"</body></h1></html>";
}
/**
* PUT method for updating or creating an instance of GenericResource
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.TEXT_HTML)
public void putHtml(String content) {
}
}
This is my html page:
<section id="contact" class="contact3">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Sign In</h2>
</div>
<div class="col-lg-6 mt-5 mt-lg-0" data-aos="fade-left" data-aos-delay="100">
<form action="forms/contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Username" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="subject" id="password" placeholder="Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="subject" id="confirmpassword" placeholder="Confirm Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="text-center"><button id="submit" type="submit">Sign In</button></div>
</form>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:8080/HananeTest/",
data: formToJSON(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
alert('Success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Error: ' + textStatus);
}
});
});
});
function formToJSON()
{
return JSON.stringify
({
"username": $('#name').val(),
"email": $('#email').val(),
"password": $('#password').val()
"password": $('#confirmpassword').val() });
};
</script>
Any suggestions how to get the input data into my web service so I can insert it to my database?

In your resource you have generic and in JS you have HananeTest as path. Make sure your are using the correct paths on both sides.
Your formToJSON function does not fill the parameter confirmpassword but has a duplicate entry for password. Make sure that all the parameters are set properly.
In JS you are currently using a JSON string and in your service you are referring to individual query parameters. To get JSON data to your method, you can annotate it with #Consumes({MediaType.APPLICATION_JSON}) and then use a simple POJO with the corresponding fields as attributes.
Example:
#Path("api/user")
public class YourResource {
#GET
#Consumes({MediaType.APPLICATION_JSON})
#Produces(MediaType.TEXT_HTML) // depending on what you want to return
public String insert(UserDTO user) {
// validation logic
// insert user into database
// return something
}
}
public class UserDTO {
private String username;
private String email;
private String password;
private String confirmpassword; // can possibly be removed if you check in JS whether the passwords match
// getters and setters
}

Related

Registration page and post request

I want to create my own registration page with spring boot, instead of sending a JSON POST request from Postman.
I currently have an HTML page with a form which submits the registration data, a registration controller, and registration service. However, it is not working properly.
My code:
RegistrationRequest
#Getter
#AllArgsConstructor
#EqualsAndHashCode
#ToString
public class RegistrationRequest {
private final String firstName;
private final String lastName;
private final String email;
private final String password;
}
Registration Controller
#RestController
#RequestMapping(path = "api/v1/registration")
#AllArgsConstructor
public class RegistrationController {
private final RegistrationService registrationService;
#PostMapping
public String register(#RequestBody RegistrationRequest request) {
return registrationService.register(request);
}
#GetMapping(path = "confirm")
public String confirm(#RequestParam("token") String token) {
return registrationService.confirmToken(token);
}
HTML form
<form class="form-signin" method="post" action="api/v1/registration">
<h2 class="form-signin-heading">Please Log in to tour agency account</h2>
<p>
<label for="firstName" class="sr-only">First name</label>
<input type="text" id="firstName" name="firstName" class="form-control" placeholder="First name" required="" autofocus="">
</p>
<p>
<label for="lastName" class="sr-only">Last name</label>
<input type="text" id="lastName" name="lastName" class="form-control" placeholder="Last name" required="" autofocus="">
</p>
<p>
<label for="email" class="sr-only">Email</label>
<input type="text" id="email" name="email" class="form-control" placeholder="Email" required="" autofocus="">
</p>
<p>
<label for="password" class="sr-only">Password</label>
<input type="password" id="password" name="password" class="form-control" placeholder="Password" required="">
</p>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
Template controller
#Controller
#RequestMapping("/")
public class TemplateController {#PostMapping("register") // I know that "register is not linked with path = api/v1/registeration
public String postRegister() {
return "register";
}
}
You need either need a template engine, or you could use Javascript and submit an AJAX request for that. If you want to use a template engine, I recommend using Thymeleaf, however there are many template engines that are available for use.
Using Thymeleaf, you'd have to modify your template to include th:action, which describes your endpoint, and th:object, which is your model. Then we name it as register.html:
<form action="#" th:action="#{/api/v1/registration}" th:object="${registrationRequest}" method="post">
<!-- Form inputs... -->
<button type="submit">Register</button>
</form>
Then in the controller, we need to tell Spring about our HTML page and the model:
#GetMapping("/register")
public String registerationForm(Model model) {
model.addAttribute("registrationRequest", new RegistrationRequest());
return "register";
}
So now when we open /register, our HTML page is loaded.
Finally, modify your POST endpoint to get our form's submitted model:
#PostMapping
public String register(#ModelAttribute RegistrationRequest registrationRequest) {
return registrationService.register(request);
}
This returns the result from registration service, you could also return a string which represents a page name, e.g. return "result", here result is an HTML page result.html.

Cannot read strings from form

I am writing form that lets user to change his password. Instead of passing User object to form, I am passing 3 empty Strings. Everything is okay, but when I am passing Submit, Strings returns as empty. Is there any way to get String from forms in Spring without packaging them into objects like changePasswordForm with 3 String fields?
My code:
Change password view:
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="/fragments/head"></head>
<body>
<div class="container">
<div th:replace="/fragments/header"> </div>
<div class="jumbotron">
<h1 class="display-4">Changing password</h1>
<form action="#" th:action="#{/user/changePassword/} + ${user.id}" method="post">
<div class="form-group">
<label>Current password</label>
<input type="password" th:field="${currentPassword}" class="form-control" placeholder="Your current password"/>
</div>
<div class="form-group">
<label>New password</label>
<input type="password" th:field="${newPassword}" class="form-control" placeholder="Your new password"/>
</div>
<div class="form-group">
<label>New password confirmation</label>
<input type="password" th:field="${newPasswordConfirmation}" class="form-control" placeholder="Confirm your new password"/>
</div>
<button class="btn btn-primary">Submit</button>
<button class="btn btn-secondary">Reset</button>
</form>
</div>
<div th:replace="/fragments/footer"> </div>
</div>
</body>
</html>
User controller:
package io.gromo13.personalBlog.controller;
import io.gromo13.personalBlog.service.RoleService;
import io.gromo13.personalBlog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import io.gromo13.personalBlog.model.User;
import javax.validation.Valid;
#Controller
#RequestMapping("/user")
#SessionAttributes("user")
public class UserController {
#Autowired
UserService userService;
#Autowired
RoleService roleService;
public void setUserService(UserService userService) {
this.userService = userService;
}
public void setRoleService(RoleService roleService) {
this.roleService = roleService;
}
#GetMapping("/{id}")
public String profile(#PathVariable Long id, Model model) {
User user = userService.get(id);
model.addAttribute("user", user);
return "/user/profile";
}
#GetMapping("/register")
public String register(Model model) {
model.addAttribute("roles", roleService.getAll());
model.addAttribute("user", new User());
return "/user/register";
}
#PostMapping("/register")
public String registerSubmit(#Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "/user/register";
userService.add(user);
return "redirect:/admin/users";
}
#GetMapping("/edit/{id}")
public String edit(#PathVariable Long id, Model model) {
User user = userService.get(id);
model.addAttribute("user", user);
model.addAttribute("password", "");
return "/user/edit";
}
#PostMapping("/edit/{id}")
public String editSubmit(#ModelAttribute("user") #Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "/user/edit";
userService.edit(user);
return "redirect:/admin/users";
}
#GetMapping("/changePassword/{id}")
public String changePasword(Model model) {
model.addAttribute("currentPassword", "");
model.addAttribute("newPassword", "");
model.addAttribute("newPasswordConfirmation", "");
return "/user/changePassword";
}
#PostMapping("/changePassword/{id}")
public String changePasswordSubmit(#PathVariable Long id,
#ModelAttribute("currentPassword") String currentPassword,
#ModelAttribute("newPassword") String newPassword,
#ModelAttribute("newPasswordConfirmation") String newPasswordConfirmation,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "/user/changePassword";
User user = userService.get(id);
if (newPassword.equals(newPasswordConfirmation) && user.getPassword().equals(currentPassword)) {
user.setPassword(newPassword);
userService.edit(user);
}
return "redirect:/admin/users";
}
#GetMapping("/delete/{id}")
public String delete(#PathVariable Long id) {
userService.delete(id);
return "redirect:/admin/users";
}
}
Actually my whole page is working fine, I just cannot read single Strings passed to forms without wrapping to objects.
Every tutorial about forms in Spring I found is passing object like xForm or User to view and read them. It works for me too, but I do not see sense in creating special object just for single form.
change th:field to name tag
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="/fragments/head"></head>
<body>
<div class="container">
<div th:replace="/fragments/header"> </div>
<div class="jumbotron">
<h1 class="display-4">Changing password</h1>
<form action="#" th:action="#{/user/changePassword/} + ${user.id}" method="post">
<div class="form-group">
<label>Current password</label>
<input type="password" name="currentPassword" class="form-control" placeholder="Your current password"/>
</div>
<div class="form-group">
<label>New password</label>
<input type="password" name="newPassword" class="form-control" placeholder="Your new password"/>
</div>
<div class="form-group">
<label>New password confirmation</label>
<input type="password" name="newPasswordConfirmation" class="form-control" placeholder="Confirm your new password"/>
</div>
<button class="btn btn-primary">Submit</button>
<button class="btn btn-secondary">Reset</button>
</form>
</div>
<div th:replace="/fragments/footer"> </div>
</div>
</body>
</html>
remove this from controller
#GetMapping("/changePassword/{id}")
public String changePasword(Model model) {
model.addAttribute("currentPassword", ""); //remove
model.addAttribute("newPassword", ""); //remove
model.addAttribute("newPasswordConfirmation", ""); //remove
return "/user/changePassword";
}
and here change ModelAttribute to RequestParam Annotation
#PostMapping("/changePassword/{id}")
public String changePasswordSubmit(#PathVariable Long id,
#RequestParam("currentPassword") String currentPassword,
#RequestParam("newPassword") String newPassword,
#RequestParam("newPasswordConfirmation") String newPasswordConfirmation) {
this sentence bindingResult not work because this validate a POJO using validations annotations
//if (bindingResult.hasErrors())
// return "/user/changePassword";
for this case the best way is create a new POJO with those fields and then validate them.
if you want to use the validation you need to create a POJO and add the constraints.
1)
public class ChangePass {
#Size(min = 8,max = 13, message = "error current password between {min} to {max}")
private String currentPassword;
#Size(min = 8,max = 13,message = "error new password between {min} to {max}")
private String newPassword;
//validate later
private String newPasswordConfirmation;
}
2)
then you need to add a instance of this POJO in the view.
#GetMapping("/changePassword/{id}")
public String changePasword(Model model) {
model.addAttribute("userPass", new ChangePass()); // adding model
return "/user/changePassword";
}
3)
in your form you need to fix 2 things add
th:object="${userPass}" and add th:field="*{currentPassword}" not th:field="${currenctPassword}" the difference is " * "
<form th:action="#{/user/changePassword/} + ${user.id}" method="post" th:object="${userPass}">
<div class="form-group">
<label>Current password</label>
<input type="password" th:field="*{currentPassword}" class="form-control" placeholder="Your current password"/>
</div>
<div class="form-group">
<label>New password</label>
<input type="password" th:field="*{newPassword}" class="form-control" placeholder="Your new password"/>
</div>
<div class="form-group">
<label>New password confirmation</label>
<input type="password" th:field="*{newPasswordConfirmation}" class="form-control" placeholder="Confirm your new password"/>
</div>
<button class="btn btn-primary">Submit</button>
<button class="btn btn-secondary">Reset</button>
</form>
4)
and the Post Method should be...
#PostMapping("/changePassword/{id}")
public String changePassword(#PathVariable Long id,
#ModelAttribute("userPass"),
#Valid ChangePass change,
BindingResult errors){
if(errors.hasErrors()){
return "/user/changePassword";
}
//your next code

Form using Thymeleaf doesn't work with POJO

I rewrite code from Mastering Spring book's and it does not work because all time I got the exception:
Caused by: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'profileForm' available as request attribute
My form:
<form th:action="#{/profile}" th:object="${profileForm}" method="post" class="col m8 s12 offset-m2">
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.twitterHandle}" id="twitterHandle" type="text"/>
<label for="twitterHandle" th:text="#{twitter.handle}">Identyfikator Twitter</label>
</div>
<div class="input-field col s6">
<input th:field="${profileForm.email}" id="email" type="email"/>
<label for="email">Adres e-mail</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input th:field="${profileForm.birthDate}" id="birthDate" type="text"/>
<label for="birthDate" th:text="#{birthdate}">Data urodzenia</label>
</div>
</div>
<div class="row s12 center">
<button class="btn indigo waves-effect waves-light" type="submit" name="save">Wyƛlij
<i class="mdi-content-send right"></i>
</button>
</div>
</form>
My POJO:
package masterspringmvc.profile;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class ProfileForm {
private String twitterHandle;
private String email;
private LocalDate birthDate;
private List<String> tastes = new ArrayList<>();
// getters setters
}
My Controller:
#Controller
public class ProfileController {
#RequestMapping(value = "/profile", method = RequestMethod.GET)
public String displayProfile() {
return "profile/profilePage";
}
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public String saveProfile(ProfileForm profileForm) {
System.out.println("Profil: " + profileForm);
return "redirect:/profile";
}
}
Tomcat prints shows:
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' (profile/profilePage:16)
According to book everything should be ok, but I still getting errors, why?
I think you need to:
Add "profileForm" to the model.
Add "#ModelAttribute("profileForm")" to the post controller.
In addition, you can simplify your #RequestMappings
#Controller
public class ProfileController {
#GetMapping("/profile")
public String displayProfile(Map<String, Object> model) {
model.put("profileForm", new ProfileForm());
return "profile/profilePage";
}
#PostMapping("/profile")
public String saveProfile(#ModelAttribute("profileForm") ProfileForm profileForm) {
System.out.println("Profil: " + profileForm);
return "redirect:/profile";
}
}

Ajax call not hitting controller

hi I am trying to Use Ajax with Spring Mvc Porltet In liferay.I Have a Jsp File and Controller Class.I want to insert a data in the form but my controller class is Not Called.So please Help Me to Solve this Problem.When I Click on submit My COntroller class is not called.
my .jsp code as follws:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects/>
<portlet:renderURL var="renderOneMethodURL">
<portlet:param name="action" value="renderOne"></portlet:param>
</portlet:renderURL>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
Call RenderOne method
<%-- <form action="${actionOneMethodURL}" method="post">
User Name: <input type="text" name="userName">
<input type="submit">
</form> --%>
<div id="request">
<div id="bigForm">
<h2> REQUEST</h2>
<h3> Enter Request Details :</h3>
<p>Name: <input name="name">
Code: <input name="code" size="6">
Request: <input name="request">
Type: <input name="type" size="6"></p>
<hr></hr>
<div class="block2">
<h2> Attribute Value Pair(Avp)</h2>
<p class="remark"> Recursive structure of avp. You can nest one AVP inside another..</p>
<div data-holder-for="branch"></div>
</div>
<div class="clear"></div>
<p> </p>
<p class="remark" align="right" padding-right:"1cm";>Click here to generate JSON representation of the form</p>
<p align="right">
<input type="submit" id="saveBigForm"></p>
</div>
<style type="text/css">a {text-decoration: none}</style>
<!-- Subforms library -->
<div style="display:none">
<div data-name="branch">
<table>
<td>Name:</td> <td><input name="name"></td>
<td>Code:</td> <td><input name="code"></td>
<td>Vendor:</td> <td><input name="vendor"></td>
<td>Multiplicity:</td><td><input name="multiplicity"></td>
<td>Index:</td><td><input name="index"></td>
<td>CDR-Index:</td><td><input name="cdrIndex"></td>
<tr>
<td >Type:</td><td><input name="type"></td>
<td>Value:</td><td><input name="value"></td>
</tr>
</table>
<div style="margin:10px; border-left:3px solid black" data-holder-for="branch"></div>
</div>
</div>
<div id="popup"></div>
</div>
and my javascript
$('#saveBigForm').click(function(){
var json = $('#bigForm').jqDynaForm('get');
showFormJson(json);
// var myInfoUrl = "<c:out value="${actionOneMethodURL}" />";
$.ajax({
type: "POST",
//url: "http://localhost:9090/first-spring-mvc-portlet//WEB-INF/servlet/view",
//url : myInfoUrl,
url : "${actionOneMethodURL}",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
});
and controller class as follows
package com.myowncompany.test.springmvc.controller;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
#Controller(value = "MyFirstSpringMVCTestController")
#RequestMapping("VIEW")
public class MyFirstSpringMVCTestController {
private static Log log = LogFactoryUtil.getLog(MyFirstSpringMVCTestController.class);
/*
* maps the incoming portlet request to this method
* Since no request parameters are specified, therefore the default
* render method will always be this method
*/
#RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
return "defaultRender";
}
#RenderMapping(params = "action=renderOne")
public String openSaveSearchPopup(RenderRequest request, RenderResponse response, Model model){
return "render1";
}
#RenderMapping(params = "action=renderTwo")
public String openDeeplinkForInfoI(RenderRequest request, RenderResponse response){
return "render2";
}
#RenderMapping(params = "action=renderAfterAction")
public String testRenderMethod(RenderRequest request, RenderResponse response){
log.info("In renderAfterAction method");
return "renderAfterAction";
}
#ActionMapping(params = "action=actionOne")
public void actionOne(ActionRequest request, ActionResponse response) throws IOException {
String userName=ParamUtil.get(request, "userName", "");
log.info("server input stream is :::"+ request.getPortletInputStream().toString());
System.out.println("we ri nnnnnnnnn");
log.info("userName is==>"+userName);
response.setRenderParameter("action", "renderAfterAction");
}
#ActionMapping(params = "action=actionTwo")
public String addMyChannelAction(ActionRequest actionRequest, ActionResponse actionResponse) {
return "action2";
}
}
iam getting the log as follows:
09:36:56,291 INFO [DispatcherPortlet:119] Portlet 'firstspringmvc' configured successfully
09:36:56,300 INFO [localhost-startStop-19][PortletHotDeployListener:454] 1 portlet for first-spring-mvc-portlet is available for use
10:09:49,460 WARN [http-bio-9090-exec-138][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
10:09:54,325 WARN [http-bio-9090-exec-139][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
Try with jsp core tag,
url : "<c:url value='/VIEW/actionOne' />"
OR
url : "<c:out value='${actionOneMethodURL}' />"
Include JSTL core in JSP i.e.:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and Change your ajax URL
url : "${actionOneMethodURL}"
to
url : "<c:url value='/VIEW/actionOne' />",
From what you have told us so far I can identify those causes:
your javascript has a problem and is not running at all (open with google chrome or firefox and press F12. Go to the Console tab and tell us if you have any errors there.
since you have a different javascript file, as the warning said, ${actionOneMethodURL}is not defined there. So you can do it like this:
In your HTML (the .jsp file you postet at top):
<script type="text/javascript">
ajaxLink = "${actionOneMethodURL}";
</script>
In your javascript file:
url : window.ajaxLink;
Experiment with this, I have no way to test it may need some tweaks like where you add the script (near the beginning of the document, near the end), and if the " surrounding the ${actionOneMethodURL} are needed.
in .jsp page add
var actionurl =${actionOneMethodURL};
in example.js on ajax call
$.ajax({
type: "POST",
url : actionurl,
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});

JSP - Process a form with a Bean Method with more than one parameter

I have this form and want to process it:
<form id="myForm" class="form-horizontal" action="/user" method="post">
<fieldset>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Email:</label>
<div class="controls">
<input name="email" placeholder="email" class="input-xlarge" type="text"
value="<%=?????????">
</div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Password:</label>
<div class="controls">
<input name="password" placeholder="password" class="input-xlarge" type="text"
value="<%=request.getParameter("password")%>">
</div>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
Close
<input class="btn btn-primary" type='button' value='Save Changes'
onclick='document.forms["myForm"].submit();'>
</div>
</div>
However, I have a bean method with two parameters and I tried to handle this by using:
public void insert(String email, String password) {
User entry = new User(email, password);
PersistenceManager pm = PMF.get().getPersistenceManager();
pm.makePersistent(entry);
}
My question is, how to connect the Bean properly with the form, which uses two parameters?
Have you created the bean java file to connect those two? A functional bean file consists of the following three parts:
A constructor working as initialization
Getters
Setters
In the following lines, you will find a plain example concerning a form based on the one you posted above. Remember the old trick of System.out.println's to check everything you are writing is right.
Bean file , let's call it userData.java
package blabla;
import java.io.Serializable;
public class UserData implements Serializable {
private String email;
private String password;
//1.Constructor
public UserData()
{
email="";
password="";
}
//2.Getters
public String getEmail(){
return email;
}
public String getPassword(){
return password;
}
//3.Setters - Caution: we use different variables here
public void setEmail(String eml)
{
this.email=eml;
}
public void setPassword(String pswd)
{
this.password=pswd;
} }
On the other hand, the .jsp file should resemble like this
index.jsp
<%--Blablabla headers and stuff, I will only write the things needing to be added--%>
<jsp:useBean id="entry" class="packagePath.UserData" scope="application"/>
<%--For analytic info about the parameters of the jsp call above, check: http://www.javatpoint.com/jsp-useBean-action--%>
<jsp:setProperty name="entry" property="*"/>
<%--Code to invoke all the setters of the bean--%>
<p><jsp:getProperty name="entry" property="email"/></p>
<p><jsp:getProperty name="entry" property="password"/></p>
<%--The two lines are not obligatory to use; you will need them only if you wan tto print the results on the page--%>
<%-- rest of the code%-->

Categories

Resources