getParameter in Servlet from form in JSP - forms

I have a jsp with a form
<form action="Login" method="post">
<h1>Login</h1>
<div>
<input type="text" placeholder="Email" required="" id="email" />
</div>
<div>
<input type="password" placeholder="Password" required="" id="password" />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form><!-- form -->
In the login Servlet I do the next:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String pass = request.getParameter("password");
String email = request.getParameter("email");
The problem is the pass and email is always null, I don't know why.

Because you get parameters by name. Try to put this:
<input type="text" placeholder="Email" required="" id="email" name="email" />
And you'll get the parameter.

<form action="Login" method="post">
<h1>Login</h1>
<div>
<input type="text" placeholder="Email" required="" name="email" />
</div>
<div>
<input type="password" placeholder="Password" required="" name="password" />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form>
String pass = request.getParameter("password");
String email = request.getParameter("email");

jsp code
<html>
<body>
<form name="loginForm" method="post" >
<input type="text" name="username" required>
<input type="password" name="password" required="">
<input type="submit" name="login" value="Login" required>
</form>
</body>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
//System.out.print(username);
String password = request.getParameter("password");
//System.out.print(password);
if (//handle ur logic) {//call validate function in UserValidate.java
//System.out.println("validate true");
HttpSession session = request.getSession();
session.setAttribute("username",username);
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
} else {
//System.out.println("validate false");
out.print("<p style=\"color:blue\">Invalid Username Password</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
out.close();
}
in here you have to create a session and setAttribute("username",username).
i think u get some idea.

Related

How to add a form in my .jsp file to send the values in the URL as pathvariabls not params . like this :- http://localhost:9091/getFeedback/138

I want to extract in my Controller.java this way (#PathVariable Integer id):-
// Get /http://localhost:9091/getFeedback/138
#GetMapping("/getFeedback/{id}")
public Feedback getFeedback(#PathVariable Integer id) {
return service.getFeedback(id);
}
Not this way:-
#GetMapping("/getFeedback")
public Feedback getFeedback(#RequestParam Integer id) {
return service.getFeedback(id);
}
I tried :
<form method="Get" action="getFeedback/">
ID: <input type="text" name="name" id="name" /><br />
<input type="submit" value="Submit" />
</form>
You can use onsubmit:
<form
method="Get"
action="getFeedback/"
onsubmit="this.action = this.action + this.name.value; this.submit();"
>
ID: <input type="text" name="name" id="name" /><br />
<input type="submit" value="Submit" />
</form>

Laravel - Form back with Input

I'm doing a login form with laravel. What I want is to validate the POST values, and if it's OK, then redirect to dashborad. If not, redirect back with Input. This is my login form :
<form method="post" autocomplete="off">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="email">Adresse courriel:</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Mot de passe:</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-aqua">Se connecter</button>
</form>
And this is my AuthController function :
public function postLogin(Request $request){
Log::info('Showing user profile for user: '.$request);
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
return redirect()->route('/admin/dashboard');
}
return redirect()->back()->withInput(Input::all());
}
When it's redirecting back, my input are note filled.
Laravel implements a old() function which brings back input data if the form submitted has errors:
<form method="post" autocomplete="off">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="email">Adresse courriel:</label>
<input type="email" class="form-control" id="email" name="email" required value="{{ old('email') }}">
</div>
<div class="form-group">
<label for="password">Mot de passe:</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-aqua">Se connecter</button>
</form>
I strongly recommend to not bring back the password. I know this is annoying, but safer imo.
More info : https://laravel.com/docs/5.4/requests#old-input

retrieve url parameter and populate a hidden form field

I have a simple form and I want to pull a url parameter and populate one of the hidden fields with that value.
for example the url is www.myurltest.html?placement=xyz
here is my form code with js. when I load the page, the value xyz is not being filled into the hidden field. The way I am checking is after page refresh, I check the source to see if the value is in the html. Please let me know what is wrong, I'm also not a developer by trade so this is extra challenging.
<script>
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
<form method="post" action="http://xyz.com" >
<ul><li ><label>First Name:</label><input name="firstName" id="firstName" type='text' value="" maxlength='255' tabIndex='1' ></li>
<li ><label>Last Name:</label><input name="lastName" id="lastName" type='text' value="" maxlength='255' tabIndex='2' /></li>
<li ><label>Email:</label><input name="email" id="email" type='text' value="" maxlength='255' tabIndex='3' /></li>
<li ><label>Company Name:</label><input name="name" id="name" type='text' value="" maxlength='255' tabIndex='4' /></li>
<li>
<input type='submit' foo=en_US value='testtest' name='submit' />
</li>
</ul>
<input type="hidden" name="placement" id="placement" value="" />
<script type="text/javascript">
document.getElementById("placement").value = getParameterByName("placement");
</script>
</form>
The value won't appear in the source. If you use Chrome F12 dev tools, you can inspect the value instead. It seems to be working for me.
<html>
<head>
<script type="text/javascript">
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
</head>
<body>
<form method="post" action="http://xyz.com" >
<ul>
<li><label>First Name:</label><input name="firstName" id="firstName" type='text' value="" maxlength='255' tabIndex='1' ></li>
<li><label>Last Name:</label><input name="lastName" id="lastName" type='text' value="" maxlength='255' tabIndex='2' /></li>
<li><label>Email:</label><input name="email" id="email" type='text' value="" maxlength='255' tabIndex='3' /></li>
<li><label>Company Name:</label><input name="name" id="name" type='text' value="" maxlength='255' tabIndex='4' /></li>
<li><input type='submit' foo=en_US value='testtest' name='submit' /></li>
</ul>
<input type="hidden" name="placement" id="placement" value="" />
<script type="text/javascript">
document.getElementById("placement").value = getParameterByName("placement");
</script>
</form>
</body>
</html>

In Thymeleaf with multiple actions and multiple forms are possible?

Hi i am new in thymeleaf + spring and i start learn it.
and wanted to integrate these 2 form in one page .
that means now 2 forms are in 2 different pages and the th:action are different ..
here i want these 2 forms work in one page
i tried that with a page with 2 forms and 2 actions but that caught error..
Create Standard Code
<form action="#" th:action="#{/saveStandard.html}" th:object="${standard}">
<table>
<h1>Create Standard</h1>
<tr>
<td>Standard Name:</td>
<td><input type="text" placeholder="Enter Standard Name" required="required"
th:field="*{standardName}"/></td>
</tr>
<tr>
<td><input type="submit" value="Create" name="save" /></td>
</tr>
</table>
</form>
Create Division Code
<form action="#" th:action="#{/saveDivision.html}"
th:object="${division}">
<table>
<td>Division Name:</td>
<tr>
<td><input type="text" placeholder="Enter Division Name" required="required"
th:field="*{divisionName}" />
</td>
</tr>
<td><input type="submit" class="btn btn-primary" value="Create"
name="save" /></td>
</table>
</form>
these are controllers..
#RequestMapping(value = Array("/saveStandard.html"), params = Array({ "save" }))
def saveStandard(standard: Standard): String = {
standard.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
standardService.addStandard(standard)
"redirect:/school/CreateStandard.html"
}
#RequestMapping(value = Array("/saveDivision.html"), params = Array({ "save" }))
def saveDivision(division: Division): String = {
division.setCreatedDate(new java.sql.Date(new java.util.Date().getTime))
divisionService.addDivision(division)
"redirect:/school/CreateDivision.html"
}
if you knew about this question please share your answer here..
and Thanks...
Hi It is posible here a example
HTML Example
<section id="registration" class="section">
<div class="container tagline">
<em>Register User</em><br />
<form method="post" th:action="#{/user/register}" th:object="${newUser}">
<div>
<label for="givenName">Id</label>
<input id="id" placeholder="Enter Id" type="text" th:field="*{id}" />
<p th:if="${#fields.hasErrors('id')}" th:text="${#strings.listJoin(#fields.errors('id'), ', ')}">
</p>
</div>
<div>
<label for="givenName">Name</label>
<input id="name" placeholder="Enter Name" type="text" th:field="*{name}" />
<p th:if="${#fields.hasErrors('name')}"
th:text="${#strings.listJoin(#fields.errors('name'), ', ')}"></p>
</div>
<div>
<label for="email">Email</label>
<input id="email" placeholder="Enter the Email" type="text" th:field="*{email}" />
<p th:if="${#fields.hasErrors('email')}"
th:text="${#strings.listJoin(#fields.errors('email'), ', ')}"></p>
</div>
<button type="submit">Create user</button>
</form>
</div>
</section>
<div>
<form method="get" th:action="#{/user/searchById}" th:object="${searchUser}">
<input id="id" placeholder="Search by id" type="text" th:field="*{id}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByName}" th:object="${searchUser}">
<input id="id" placeholder="Search by Name" type="text" th:field="*{name}" size="10" >
<button type="submit" >search</button>
</form>
<form method="get" th:action="#{/user/searchByEmail}" th:object="${searchUser}">
<input id="id" placeholder="Search by Email" type="text" th:field="*{email}" size="10" >
<button type="submit" >search</button>
</form>
</div>
Spring
#Controller
#RequestMapping("/user")
public class User {
BookingFacadeUserImp userService = new BookingFacadeUserImp();
#GetMapping()
public ModelAndView init() {
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#PostMapping("/register")
public ModelAndView saveUser(#Valid #ModelAttribute("newUser") UserDTO user, BindingResult result)
throws NumberFormatException, ParseException {
System.out.println("Register: " + user);
userService.createUser(user);
return getModelView().addObject("users", getUsersByName("", 100, 0));
}
#GetMapping("/delete/{id}")
public ModelAndView delete(#PathVariable long id) {
userService.deleteUser(id);
return init();
}
#PostMapping("/update")
public ModelAndView updateUser(#ModelAttribute("updateUser") UserDTO user) {
userService.updateUser(user);
return init();
}
#GetMapping("/searchById")
public ModelAndView searchById(#ModelAttribute("searchUser") UserDTO user) {
if (user.getId() > 0)
return getModelView().addObject("users", getUsersById(user.getId()));
else
return init();
}
#GetMapping("/searchByName")
public ModelAndView searchByName(#ModelAttribute("searchUser") UserDTO user) {
if (!user.getName().equals(""))
return getModelView().addObject("users", getUsersByName(user.getName(),100,0));
else
return init();
}
public ModelAndView getModelView() {
ModelAndView model = new ModelAndView("user");
model.addObject("newUser", new UserDTO());
model.addObject("searchUser", new UserDTO());
return model;
}
public List<UserDTO> getUsersById(long id) {
List<UserDTO> list = new ArrayList<UserDTO>();
list.add((UserDTO) userService.getUserById(id));
return list;
}
public List<com.example.demo.task1.model.User> getUsersByName(String name, int pageSiza, int pageNum) {
return userService.getUsersByName(name, pageSiza, pageNum);
}
public List<com.example.demo.task1.model.User> getUsersByEmail(String email) {
return (List<com.example.demo.task1.model.User>) userService.getUserByEmail(email);
}
}

Can you require two form fields to match with HTML5?

Is there a way to require the entries in two form fields to match using HTML? Or does this still have to be done with JavaScript? For example, if you have two password fields and want to make sure that a user has entered the same data in each field, are there some attributes, or other coding that can be done, to achieve this?
Not exactly with HTML validation but a little JavaScript can resolve the issue, follow the example below:
function check() {
var input = document.getElementById('password_confirm');
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
<p>
<label for="password">Password:</label>
<input name="password" required="required" type="password" id="password" oninput="check()"/>
</p>
<p>
<label for="password_confirm">Confirm Password:</label>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check()"/>
</p>
<input type="submit" />
You can with regular expressions Input Patterns (check browser compatibility)
<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>
<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>
A simple solution with minimal javascript is to use the html attribute pattern (supported by most modern browsers). This works by setting the pattern of the second field to the value of the first field.
Unfortunately, you also need to escape the regex, for which no standard function exists.
<form>
<input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
<input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
</script>
JavaScript will be required, but the amount of code can be kept to a minimum by using an intermediary <output> element and an oninput form handler to perform the comparison (patterns and validation could augment this solution, but aren't shown here for sake of simplicity):
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
Not only HTML but a bit of JavaScript
HTML
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
JavaScript
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
confirm_password.setCustomValidity( password.value !=
confirm_password.value ? "Passwords Don't Match" : '');
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
CodePen Demo
As has been mentioned in other answers, there is no pure HTML way to do this.
If you are already using JQuery, then this should do what you need:
$(document).ready(function() {
$('#ourForm').submit(function(e){
var form = this;
e.preventDefault();
// Check Passwords are the same
if( $('#pass1').val()==$('#pass2').val() ) {
// Submit Form
alert('Passwords Match, submitting form');
form.submit();
} else {
// Complain bitterly
alert('Password Mismatch');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ourForm">
<input type="password" name="password" id="pass1" placeholder="Password" required>
<input type="password" name="password" id="pass2" placeholder="Repeat Password" required>
<input type="submit" value="Go">
</form>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
value={password}
onChange={(e) => { setPassword(e.target.value) }}
type="password" id='password' name="password" required minLength={3} maxLength={255} />
</div>
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
title='Passwords should be match'
pattern={`${password}`}
value={confirmPassword}
onChange={(e) => { setConfirmPassword(e.target.value) }}
type="password" id='confirmPassword' name="confirmPassword" required minLength={3} maxLength={255} />
</div>