How to get and store value selected from dropdown to the database? - spring

addMission.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Create a mission</title>
</head>
<body>
<h1>Create a Mission</h1>
<form action="/createMission" method="post">
<p>Mission title: <input type="text" required id="title" name="title" value=""></p>
<p>
<select name="agent" id="agent">
<option value="natasha">Natasha Romanova</option>
<option value="austin">Austin Powers</option>
<option value="johnny">Johnny English</option>
</select>
</p>
<h2>Enter the gadgets</h2>
<p>Gadget 1:<input type="text" required id="gadget1" name="gadget1" value=""></p>
<p>Gadget 2:<input type="text" required id="gadget2" name="gadget2" value=""></p>
<p><input type="submit" value="Create Mission!"></p>
</form>
<p> Back to home </p>
</body>
</html>
Controller Code
#PostMapping("/createMission")
public String createMission(#ModelAttribute Mission mission) {
int returnValue = database.createMission(mission);
System.out.println(returnValue);
return "view_missions";
}
createMission() method
public int createMission(Mission mission) {
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
String query = "INSERT INTO missions(agent, title, gadget1, gadget2) VALUES (:agent, :title, :gadget1, :gadget2)";
namedParameters
.addValue("agent", mission.getAgent())
.addValue("title", mission.getTitle())
.addValue("gadget1", mission.getGadget1())
.addValue("gadget2", mission.getGadget2());
int returnValue = jdbc.update(query, namedParameters);
return returnValue;
}
In the code snippets shared above, Im creating a mission using thymleaf.
When I enter the details in the textboxes and hit "Create" button I get an error 'Property or field 'empty' cannot be found on null'. Im sure this null property is coming from the dropdown list.
Is there any way I can get the value of the dropdown too along with the other values and send them to the createMission() ?

I don't see in your controller how you get back the values.
You need to add an object to your model in your "get controller" and link it to the form.
Then you can retrieve it and save it in the database.
Please have a look to this post you will get more details on how to make it

Related

Retrieving Information from Userinput SpringMVC dropdown box

Hi I'm having some trouble retrieving information from the user using a spring controller.
the controller looks like this:
#Slf4j
#Controller("indexController")
public class IndexController {
List<String> userInput = new ArrayList<>(Arrays.asList(new String[]{"Apple", "Blackberry", "Strawberry"}));
public List<String> getUserInput() {
return userInput;
}
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(
Model model
){
log.info("home path was hit");
model.addAttribute("options", getUserInput());
model.addAttribute("option", new Object());
return "index";
}
#RequestMapping(value = "createOrder", method = RequestMethod.POST)
public String placeUserOrder(
Model model,
#ModelAttribute("option")String usersInput
){
log.info("createOrder path was hit");
log.info(usersInput);
return "redirect:/home";
}
the index.thml within re main/resource/templates folder looks like this:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>home page</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h2>your orders are:</h2>
<form method="post" action="/createOrder" th:object="${order}">
<th:text alignment-baseline="text-before-edge" aria-atomic="true" > select a copybook</th:text>
<select class="from-control" id="dropDownList">
<option value="0">select copybook</option>
<option th:each="option : ${options}" th:value="${option}" th:text="${option}" >
<input type="hidden" name="${_csrf.usersChoiceFromThymeleaf}" value="${_csrf.token}" />
</option>
<input type="submit" name="createOrder" value="place">
</select>
</p>
</p>
</form>
<th:block th:each="order : ${orders}">
<tr>
<td th:text="${order.value}"></td>
</tr>
</th:block>
</body>
</html>
every time after i set a breakpoint within the post function the option value is empty.
what am i doing wrong?
shouldnt i expect a string from selected dropdown menu?
i tried to fetch an int and it remains empty as well
the model contains also only 2 key value pairs "option"->""
and org.springframework.validation.BindingResult.option -> {BeanPropertyBindingResult#7472} "org.springframework.validation.BeanPropertyBindingResult: 0 errors"

Is it possible to use Spring model in Javascript functions inside Thymeleaf template?

I've the following domain:
#Document(collection = "backupareas")
public class BackupArea {
#Id
private String id;
private String area;
private List<Tape> tapes;
In my template I would that when I change area a js function fill the tape select with related area tapes.
<div class="form-group col-md-3">
<label for="backup"><i>*</i> Backup</label>
<select id="backup" class="form-control" name="backup" required onchange="loadTapes();">
<option value="" selected="selected">--- Select Area ---</option>
<option th:each="area: ${areas}" th:value="${area.getArea()}" th:text="${area.getArea()}"></option>
</select>
</div>
<div class="form-group col-md-3">
<label for="tape"><i>*</i> Tape</label>
<select id="tape" class="form-control" name="tape" required >
</select>
I start with this js function, but I don't know how to use (or if it is possible) model variables.
function loadTapes() {
var area = $("#backup").val();
console.log($("#backup").index(area));
if($("#backup").index(area) == 1) {
$("#tape").empty();
return false;
}
$("#tape").empty();
var select = $('#tape');
select.append($("<option />").val("").text("--- Select one ---"));
// Here should use model variable to loop over tapes related to the selected area
select.append($("<option/>").val(TAPE).text(TAPE));
}
I solved. I created a fragment as:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<th:block th:fragment="tapes">
<th:block th:if="${tapes != null}">
<option th:each="tape: ${tapes}" th:value="${tape}" th:text="${tape}"></option>
</th:block>
</th:block>
</body>
</html>
In the main template I call an ajax method:
function loadTapes() {
$("#tape").empty();
$.post("/area/loadTapes", {area: area}, function (data) {
$('#tape').append(data);
});
}
The loadTapes method is:
PostMapping("/area/loadTapes")
public String loadTape(#RequestParam("area") String area, Model model) {
BackupArea backupArea = backupAreaService.findByArea(area);
List<Integer> tapes = new ArrayList<>();
for(Tape tape: backupArea.getTapes()) {
tapes.add(tape.getTape());
}
model.addAttribute("list", tapes);
return "/backup/tapes :: list";
}

How pass extra param from html to controller

Spring Boot 2.5, Thymeleaf
I need when click submit to pass object Product and additional extra param (quantity)
html template:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Category template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container">
<h3 th:text="*{title}"/>
<form method="post" action="#" th:object="${product}" th:action="#{/product}">
<input type="hidden" id="id" th:field="*{id}"/>
<input type="text" placeholder="Name" id="name" th:field="*{name}" th:disabled="${isView}"/>
<input type="hidden" id="created" th:field="*{created}"/>
<textarea placeholder="Description" rows="5" id="description"
th:field="*{description}" th:disabled="${isView}"></textarea>
<input type="number" placeholder="Price" id="price" th:field="*{price}" th:disabled="${isView}"/>
<input type="text" placeholder="Currency" id="currency" th:field="*{currency}" th:disabled="${isView}"/>
<input type="text" placeholder="Images URL(separate by comma)" id="images" th:field="*{images}" th:disabled="${isView}"/>
<input th:type="${isView} ? hidden : submit" value="Submit"/>
</form>
</div>
</body>
</html>
and here my controller:
#RequestMapping("cart/add")
public String addProduct(Model model) {
logger.info("addProduct");
model.addAttribute("isAdd", true);
model.addAttribute("product", new Product());
model.addAttribute("title", "Add Product");
model.addAttribute("viewMode", ViewMode.ADD);
return "product";
}
#PostMapping(value = "/product")
public String submitProduct(Product product, Model model) {
logger.info("submitProduct = " + product);
if (product.getId() == 0) { // add category
product.setCreated(new Date());
} else { // update category
product.setUpdated(new Date());
}
return "redirect:/cart";
}
So when click button Submit call submitProduct with fill object Product. But I need to pass extra param (as second param in method submitProduct) - quantity.
How I can pass this extra int param from html to controller?
One option is to access the value directly from the request parameters.
Assuming the quantity value is available in the form as an input field, with a name of quantity (looks like it is not there at the moment), then you can alter your controller to use this:
import org.springframework.web.bind.annotation.RequestParam;
And then change the relevant method signature to something like this:
public String submitProduct(Product product, Model model,
#RequestParam(name = "quantity") String quantity) {...}
(Field validation of some kind would also be needed, I assume.)

How do I modify a .html file to give hardcoded inputs to input fields every time?

I want to access my Powerschool (powerschool.avon.k12.ct.us), and I find the need to type in my password and username every time rather tedious. To try and fix this I downloaded the page's source in Chrome, below:
<!DOCTYPE html>
<!-- saved from url=(0052)http://powerschool.avon.k12.ct.us/guardian/home.html -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Parent Sign In</title>
<meta http-equiv="X-UA-Compatible" content="IE=8">
<meta name="robots" content="noindex">
<link href="./Powerschool_files/screen.css" rel="stylesheet" type="text/css" media="screen">
<meta name="viewport" content="width=device-width">
<script src="./Powerschool_files/jquery-1.4.2.min.js"></script><style type="text/css"></style>
<script language="JavaScript" src="./Powerschool_files/md5.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript"><!--
var pskey = "4EDE156E2FAD0F1A427D2AD066530F496ADC3EEA78CE43E70F28053576FD4EA1";
//-->
</script>
<script language="JavaScript" type="text/javascript">
function deleteCookie(cookieName){
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime()-1);
document.cookie = cookieName + "=; expires='" + cookieDate.toGMTString()+"'; path=/";
}
deleteCookie("InformAuthToken");
function getURLParameter(name) {
return unescape(
(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
);
}
var $j = jQuery.noConflict();
$j(document).ready(function() {
// Hide or show the translator login input field
// if the URL parameter "translator" is present
var translator = getURLParameter("translator");
if (translator == "null") {
$j('#translatorInput').hide();
} else {
if (translator == "true") {
$j('#translatorInput').show();
} else {
$j('#translatorInput').hide();
}
}
$j('a.popWin').click(function(){
var winURL = $j(this).attr('href');
window.open(winURL);
return false;
});
});
</script>
</head>
<body class="pslogin" id="palogin">
<div id="container">
<div id="branding-powerschool"><img src="./Powerschool_files/ps7-logo-lrg.png" alt="PowerSchool" width="280" height="41"></div>
<div id="content" class="group">
<form action="./Powerschool_files/Powerschool.htm" method="post" name="LoginForm" target="_top" id="LoginForm" onsubmit="doPCASLogin(this);">
<input type="hidden" name="pstoken" value="2465670387a1nxrEimrKqPMN0c7QbxxKLNZe16PRC">
<input type="hidden" name="contextData" value="4EDE156E2FAD0F1A427D2AD066530F496ADC3EEA78CE43E70F28053576FD4EA1">
<input type="hidden" name="dbpw" value="">
<input type="hidden" name="translator_username" value="">
<input type="hidden" name="translator_password" value="">
<input type="hidden" name="translator_ldappassword" value="">
<input type="hidden" name="returnUrl" value="">
<input type="hidden" name="serviceName" value="PS Parent Portal">
<input type="hidden" name="serviceTicket" value="">
<input type="hidden" name="pcasServerUrl" value="/">
<input type="hidden" name="credentialType" value="User Id and Password Credential">
<h2>Parent Sign In</h2>
<!--box content-->
<div id="noscript" class="feedback-alert" style="display: none;"> To sign in to PowerSchool, you must use a browser that supports and has JavaScript enabled. </div>
<fieldset id="login-inputs" class="group">
<div>
<label>Username</label>
<input type="text" id="fieldAccount" name="account" value="" size="39">
</div>
<div>
<label>Password</label>
<input type="password" name="pw" value="" size="39"><div id="login-help">Having trouble signing in?</div>
</div>
<div id="translatorInput" style="display: none;">
<label>Translator Sign In</label>
<input type="password" name="translatorpw" value="" size="39">
</div>
<div class="button-row">
<button type="submit" id="btn-enter" title="Sign In To PowerSchool Parent Access" value="Enter" border="0">Sign In</button>
</div>
</fieldset>
<!-- box content-->
</form>
</div>
<div id="footer" class="group">
<p>Copyright© 2005 - 2013 Pearson Education, Inc., or its affiliate(s). All rights reserved.</p>
<p id="pearsoncorplink">Join us on Facebook</p>
</div>
</div>
<div id="branding-pearson">
<div id="logo-pearson"></div>
<div id="tagline-pearson"></div>
</div>
<script type="text/javascript">
/**
* Set the page's locale via a request_locale URL parameter. If there is already a URL parameter by
* this name, then substitute it with the passed-in locale. NOTE: This function will actually cause the page
* to be re-submitted with the new locale, so it really should not be used with pages submitted via POST
* requests (if there are any, which I hope there are not).
* #param locale the locale to set (e.g. en_US)
*/
function setPageLocale (locale) {
var c=String (window.location);
var rlpos = c.indexOf("request_locale=");
var afterPart = "";
if (rlpos > 0) {
var afterBegin = c.indexOf("&", rlpos);
if (afterBegin > 0) {
afterPart = c.substring(afterBegin);
}
c = c.substring(0, rlpos-1);
}
var s=(c.indexOf('?') > 0 ? '&' : '?');
var np = c + s + 'request_locale=' + locale + afterPart;
window.location = np;
}
function jsCheck() {
document.getElementById("login-inputs").className = 'group';
}
jsCheck();
</script>
<script>
$j('#noscript').hide();
function jsEnabled() {
if(typeof $j != 'function'){
alert('Developer: This page is missing key components required for functionality!\n\nPossible causes include:\n - Commonscripts might be missing.\n - Page customization might enabled, and incomplete.');
//document.write('<script...');
} else {
$j('#login-inputs').removeClass('hide');
$j("#fieldAccount").focus();
}
}
$j(document).ready(function(){
jsEnabled();
});
</script>
</body></html>
I was wondering if it was possible to directly modify the downloaded source to automatically fill the input boxes (the below block is where I think it would be done) to always fill in the username and pass fields with "myUsername" and "myPassword," or something like that. I tried setting the value of the Input and Username fields, but that (chrome) gave me an, shown here:
No webpage was found for the web address: file:///C:/Users/Me/Desktop/Powerschool_files/Powerschool.htm
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.
Do you guys know how this could be done?
Instead of copying the entire page, it's probably simpler to make a bookmarklet that fills in the form. Just edit a normal bookmark and change the link to be this:
javascript:(function() { document.forms[0].elements[0].value="hi" })()
That will set the value of the first field in the first form. (It may take some experimenting to see which form number and which field number.)
You can probably use Chrome to remember your passwords for you automatically, but what you have should actually work. You just need to change any paths to urls for it to work perfectly. One that you definitely need to change is the form action:
- ./Powerschool_files/Powerschool.htm
+ https://example.com/Powerschool_files/Powerschool.htm
This should allow you to submit directly to that site unless they have a CSRF token in the form that I don't see.

MVC3 - Understanding POST with a button

How does one obtain the form data after submitting it?
<form target="_self" runat="server">
<p>
<select id="BLAHBLAH2">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
</select>
<input type="submit" runat="server" value="Change Year" />
</p>
</form>
This hits the controller's Index method. But, there's nothing in Request.Form. Why?
Second, can I use
<input type="button" instead of type=submit? That is, without introducing ajax via onclick.
Finally, how do I submit to a different method in the controller, e.g. Create?
Try removing those runat server tags. They should not be used in ASP.NET MVC. Also your select doesn't have a name. If an input element doesn't have a name it won't submit anything. Also your option tags must have value attributes which indicates what value will be sent to the server if this options is selected:
<form action="/Home/Create" method="post">
<p>
<select id="BLAHBLAH2" name="BLAHBLAH2">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
<input type="submit" value="Change Year" />
</p>
</form>
But the correct way to generate forms in ASP.NET MVC is to use HTML helpers. Depending on the view engine you are using the syntax might be different. Here's an example with the Razor view engine:
#model MyViewModel
#using (Html.BeginForm("Create", "Home"))
{
<p>
#Html.DropDownListFor(x => x.SelectedYear, Model.Years)
<input type="submit" value="Change Year" />
</p>
}
Here you have a strongly typed view to some given view model:
public class MyViewModel
{
public string SelectedYear { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable
.Range(2010, 4)
.Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
which is populated by some controller action that will render this view:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
... model.SelectedYear will contain the selected year
}
}
None of your <option> tags have a value:
...
<option value="2010">2010</option>
...
As noted by David, runat="server" is most definitely a WebForms thing, so you can 86 that.
If you want to submit to a different method on your controller you just need to specify the URL for that method.
Easy way using Html.BeginForm:
#using (Html.BeginForm("AnotherAction", "ControllerName")) {
<!-- Your magic form here -->
}
Using Url.Action
<form action="#Url.Action("AnotherAction")" method="POST">
<!-- Your magic form here -->
</form>
You can also use
In Controller
int Value = Convert.ToInt32(Request["BLAHBLAH2"]); //To retrieve this int value
In .cshtml file use
<select id="IDxxx" name="BLAHBLAH2">
//Request[""] will retrieve the VALUE for the html object ,whose "name" you request.

Resources