this is my jsp page.where im displaying a form and sending the values to another servlet page to insert the data into mysql database.im using post method to send all values.servlet name is updateVehicle2
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Modify Vehicle</title>
</head>
<center><h1> Modify Vehicle</h1></center>
<center>
<form action="updateVehicle2" method="Post">
<label >Enter Vehicle name:</label>
<input type="text" name="vname" required><br><br>
<label >Enter Vehicle model:</label>
<input type="text" name="vmodel" required ><br><br>
<label >Enter Vehicle ID:</label>
<input type="text" name="vid" required ><br><br>
<label >Select Vehicle type:</label>
<select name="vtype" required>
<option disabled selected>select type</option>
<option value="Ac">Ac</option>
<option value="NonAc">Non Ac</option>
</select><br><br>
<label >Rate per hour:</label>
<input type="text" name="vrph" required ><br><br>
<label >Rate per km:</label>
<input type="text" name="vrpk" required ><br><br>
<input type="submit" value="Add Vehicles">
</form></center>
this is my servlet page.here im trying to retrieve values by using request.getParameter() ,but im getting null values here.every values is null.i have used name attribute for retrieving values .but,still it returning null values.please help me struggling with this problem morethan 5 hours.thanks in advance
String vn=request.getParameter("vname");
String vmodel=request.getParameter("vmodel");
String vid=request.getParameter("vid");
String vtype=request.getParameter("vtype");
String vrph=request.getParameter("vrph");
String vrpk=request.getParameter("vrpk");
response.setContentType("text/html");
final String JDBC_DRIVER="com.mysql.jdbc.Driver";
final String DB_URL="jdbc:mysql://localhost:3306/startrek";
final String user="root";
final String pass="kingmaker";
Connection conn=null;
PreparedStatement stmt;
stmt = null;
int numRows=0;
PrintWriter out = response.getWriter();
out.println(vn);
out.println(vmodel);
try
{
Class.forName(JDBC_DRIVER);
conn=DriverManager.getConnection(DB_URL,user,pass);
stmt = conn.prepareStatement("update vehicles set vname=?,vmodel=?,vtype=?,vrph=?,vrpk=? where vid=?;");
stmt.setString(1,vn);
stmt.setString(2,vmodel);
stmt.setString(3,vtype);
stmt.setString(4,vrph);
stmt.setString(5,vrpk);
stmt.setString(6,vid);
numRows=stmt.executeUpdate();
if(numRows>0)
{
out.println("updated successfully");
}
else
{
out.println("not succesfully");
}
}
catch(Exception e)
{
out.println(e);
}
}
}
To overcome from this problem write '#MultipartConfig' before your Servlet class.
like-->
#MultipartConfig
public class EditUserServlet extends HttpServlet {}
Related
I have an endpoint:
#GetMapping("book/param")
public String bookByParam(
#RequestParam(required = false,name = "name") String name,
#RequestParam(required = false,name = "author") String author,
#RequestParam(required = false,name = "genre") String genre,
#RequestParam(required = false,name = "genre") int price, Model m
){
List<Books> books = bookService.showSpecificBooks(name, author, genre,price);
m.addAttribute("books", books);
return "book";
}
For the params I wrote querys so they can be null that means if i dont input anything I will get all books.
Now I have my books.html template with following implemenation:
<form th:action="#{book/param}" th:object="${books}" method="get">
<label for="name">name:</label><br>
<input type="text" id=name th:field="name" placeholder="name">
<label for="author">author:</label><br>
<input type="text" id=author th:name="author" placeholder="author">
<label for="genre">genre:</label><br>
<input type="text" id=genre th:name="genre" placeholder="genre">
<label for="price">price:</label><br>
<input type="number" id=price th:name="price" placeholder="price">
</form>
I would expect that I would get a List of books within the range of the submitted values and when I have no input I would get (because of my Query) all books but all I get is a TemplateInputException: An error happened during template parsing. I also tried to wrap the object names like this:
<input type="text" id=name th:field="*{name}" placeholder="name">
or like this :
<input type="text" id=name th:field="${name}" placeholder="name">
but unfortunately it did not work. Can anyone see what I am doing from.
Thanks in advance
Use a model object and bind that to the form instead of separate query parameters. \
public class SearchParameters {
private String name, genre, author;
private int price;
// getters / setters
}
#ModelAttribute("params")
public SearchParams params() {
return new SearchParamters ();
}
#GetMapping("book/param")
public String bookByParam(#ModelAttribute("params") SearchParamters params, Model m
){
List<Books> books = bookService.showSpecificBooks(params.getName(), params().getAuthor(), params.getGenre(), params.getPrice());
m.addAttribute("books", books);
return "book";
}
TIP: You could also pass the SearchParameters to your BookService and just get the things in there. Saves you from modifying the method when you add an additional parameter, you just need to change the SearchParameters and the BookService implementation.
Now let your form use params as a object and refer to the fields.
<form th:action="#{book/param}" th:object="${params}" method="get">
<label for="name">name:</label><br>
<input type="text" id=name th:field="name" placeholder="name">
<label for="author">author:</label><br>
<input type="text" id=author th:field="author" placeholder="author">
<label for="genre">genre:</label><br>
<input type="text" id=genre th:field="genre" placeholder="genre">
<label for="price">price:</label><br>
<input type="number" id=price th:field="price" placeholder="price">
</form>
This should bind your form object to the thymeleaf form and you will see earlier entered data.
To show your results you need to iterate over the books list and show them in a table (or something else).
<table>
<tr><th>Name</th><th>author</th><th>Genre</th><th>Price</th></tr>
<tr th:each="book : ${books}">
<td th:text="${book.name}">Name</td>
<td th:text="${book.author}">Author</td>
<td th:text="${book.genre}">Genre</td>
<td th:text="${book.price}">Price</td>
<tr>
</table>
Something like the above should do.
th:field works for entities. From what I see name is a request parameter. Try using th:name, as you do for author, genre, price.
<input type="text" id=name th:name="name" placeholder="name">
In order to iterate through the list of books you can try doing this:
<tr th:each="book : ${books}">
<td><span th:text="${book.name}"> Title </span></td>
<td><span th:text="${book.author}"> Author </span></td>
<td><span th:text="${book.genre}"> Genre</span></td>
<td><span th:text="${book.price}"> Price</span></td>
</tr>
In this case, there's no need for #RequestParam since the fields can be found inside Book entity.
I want get a values from web client and save it in database, but I don't know how call my controller methods from cshtml
#{
#ViewBag.Title;
#model Homi.Controllers.HomeController
Homi.Controllers.HomeController obj = (Homi.Controllers.HomeController)ViewData["h"];
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
#Styles.Render("~/Content/style.css")
#Styles.Render("~/Content/rest.css")
#Styles.Render("~/Content/font.css")
#Styles.Render("~/Content/font2.css")
</head>
<body>
Register
<div>
<input type="username" id="Username required="required" />
</div>
<div>
<input type="password" id="Password" required="required" />
<label for="Password">Password</label>
</div>
<div>
<input type="password" id="Repeat Password" required="required"/>
<label for="Repeat Password">Repeat Password</label>
</div>
<div>
<button><span>Next</span></button>
</div>
#Scripts.Render("~/Content/index.js")
#Scripts.Render("~/Content/jquery.js")
</body>
</html>
for example I have this code on my mind but you know it's doesn't work:
<div onclick=#obj.setp(username.text, password.text)>
<button><span>Next</span></button>
</div>
I want when I click on "Next" button my method calling.
and this is part of my controller, the method that I want to call:
namespace Homi.Controllers{
public class HomeController : Controller
{
public ActionResult setp(string usename, string password)
{
WebAdmin wa = new WebAdmin();
wa.InsertToDb(username, password);
return View("userAccess");
}}}
it's very important to me that I don't change my html code style
thank you for your help
Keep your input fields inside a form tag and submit the form
#using(Html.BeginForm("setp","home"))
{
<input type="text" name="Username" required="required" />
<input type="text" name="Password" required="required" />
<input type="submit" value="Next"/>
}
When razor executes the page, it will generate a form tag in the place of #using(Html.BeginForm line where the action is set to "home/setp"(Check the view source in browser). As long as your form element name's matches with your HttpPost action method parameter name's, values of the textboxes will be available in those when the form is submitted.
[HttpPost]
public ActionResult setp(string Username, string password)
{
//do something
}
I have a form with all fields, less one of it, filled from user. This is the class passed through the form
public class CarForm {
private String id;
private Integer initialKm;
private String carChassis;
private String note;
private String carType;
private Integer fleet;
The only one field, fleet, I would like to set before pass the form, or better, set it from HTML. For example:
<div class="form-group">
<label>Fleet application</label> <input type="text"
class="form-control" th:field="*{fleet}"
th:placeholder="${fleetApplication}" readonly="readonly">
</div>
So I would like to show ${fleetApplication.application} and set into fleet this value, or, if it is possible, set another value${fleetApplication.idFleet}.
Is it possible one of these solutions?Thanks
Update: as suggested by #Faraj Farook I resolved so:
<div class="form-group">
<label>Fleet application</label>
<!-- Show fleet application -->
<input class="form-control" type="text" th:value="${fleetApplication.application}" readonly="readonly" />
<!-- Save into fleet the value of idFleet -->
<input type="hidden" name="fleet" th:value="${fleetApplication.idFleet}" />
</div>
Setting it in the server side
controller
String action(Model model){
CarForm carForm = new CarForm();
carForm.setFleet(<some value>);
model.addAttribute("obj", carForm);
return view.html;
}
view.html
<div class="form-group">
<label>Fleet application</label>
<input type="text" th:field="*{fleet}" readonly/>
</div>
setting it in the client side
view.html
<div class="form-group">
<label>Fleet application</label>
<input type="text" readonly th:value="${someValueVariable}"/>
<input type="hidden" name="fleet" th:value="${someValueVariable}"/>
</div>
I have this HTML5 code:
<form id="LogInArea" action = "/Home/ValidateUser" >
<fieldset>
<legend>Login Page</legend>
<p>
<label>
User name<br>
<input type="text" id="userName" required></label></p>
<p><label>
Password<br>
<input type="password" id="password" required></label></p>
<p>#*<button id="LoginButton">
Log in</button>*#
<button>submit</button>
</p>
Register if you don't have an account.
</fieldset>
</form>
When I press the submit button the ValidateUser() action in Home controller is fired.
My question is how can I get the submitted form in ValidateUser() action and how I get the values of form element?
P.S. I don't want to use model!
I'm not sure why you don't want to use a model as the other answers recommend, however you can get the form values by using the Request object.
[HttpPost]
public void ValidateUser()
{
string name = Request.Form["userName"];
string password = Request.Form["password"];
}
However you will need ensure that you set your form method to Post and add name values to all your submitted form fields.
<form id="LogInArea" action = "/Home/ValidateUser" method="post">
...
<input type="text" id="userName" name="userName" required></label>
...
<input type="password" id="password" name="password" required></label>
...
</form>
You should also define a value for the 'name' attribute, so instead of:
<input type="text" id="userName" required>
it should be
<input type="text" id="userName" name="username" required>
then in your controller:
public ActionResult ValidateUser(string username)
{
...
}
You have to catch model you passed into your view i.e.
If you have passed Login model into your view, then you have to catch same into your controller's action method like below:
public ActionResult Login(Login model)
{
// Login is your model which you passed into view. Validate it here.
}
To get values you have to use name attribute in your input tag.
Let me know if you have any confusion.
I don't know how to insert gender(radio button), favorite subjects(checkbox) into database using servlet. Here is my coding...
FORM:
<form name="myform" action="NewServlet" method="GET">
Name: <input type="text" name="name" value="" />
Age: <input type="text" name="age" value="" />
Gender: <input type="radio" name="Gender" value="" />Male
<input type="radio" name="Gender" value="" />Female
Your favorite: <input type="checkbox" name="fav" value="" />C
<input type="checkbox" name="fav" value="" />C++
<input type="checkbox" name="fav" value="" />JAVA
<input type="submit" value="submit"/>
</form>
NewServlet:
public class NewServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Connection conn;
Statement stmt;
String name=req.getParameter("name");
int age=Integer.parseInt(req.getParameter("age"));
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:mydb");
stmt=conn.createStatement();
int i=stmt.executeUpdate("insert into student values(' "+name+" ',' "+age+" ') ");
if(i>0)
out.print("Inserted Successfully");
else
out.print("Fail to Insert");
}
catch(Exception e){out.print(e);}
}}
The way radio buttons work is you set the value in your HTML code and give them the same name. When the form is submitted, the browser only sends the value of the one that is selected. So your issue is you left the values blank.
Gender: <input type="radio" name="Gender" value="Male" />Male
<input type="radio" name="Gender" value="Female" />Female
Once you have the values in there, you just use req.getParameter("Gender") like you did with the other parameter.
But 2 tips: (1) Your code is open to SQL injection. (2) You should include a column list in your insert. If you don't, adding fields to the table schema later will break your insert in the future. I.e. insert into table (col1, col2) values('val1', 'val2');