I am trying to display the user profile details when user click on the profile link. I am using eclipse. Also using mvc architecture. No errors occuring but data is not displaying in the jsp file.
CustomerProfileController servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
CustomerViewQuery cvq = new CustomerViewQuery(name);
try {
List<Customer> customers = cvq.list();
request.setAttribute("customers", customers); // Will be available as ${products} in JSP
request.getRequestDispatcher("CustomerProfile.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain vehicles from DB", e);
}
}
CustomerViewQuery file
package dbhelpers;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import models.Customer;
public class CustomerViewQuery {
DBConnection databaseCon = new DBConnection();
String uName;
public CustomerViewQuery(String name) {
this.uName = name;
}
public List<Customer> list() throws SQLException {
List<Customer> customers = new ArrayList<Customer>();
try (
Connection con = databaseCon.dbconnect();
PreparedStatement pst = con.prepareStatement("SELECT * FROM customers WHERE username='\"+uName+\"'");
ResultSet resultSet = pst.executeQuery();
) {
while (resultSet.next()) {
Customer customer = new Customer();
customer.setId(resultSet.getInt("id"));
customer.setName(resultSet.getString("name"));
customer.setEmail(resultSet.getString("email"));
customer.setAddress(resultSet.getString("address"));
customer.setSex(resultSet.getString("sex"));
customer.setBday(resultSet.getString("bday"));
customer.setTelephone(resultSet.getString("telephone"));
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
customers.add(customer);
}
}catch(SQLException e) {
e.printStackTrace();
}
return customers;
}
}
Getters and Setters are in the Customer.java file
I get no errors but also nothing is displaying in the CustomerProfile.jsp file. Here is the code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${customers}" var="customer">
</c:forEach>
<div class="container mt-5"><br>
<form role="form" action="CustomerController" data-toggle="validator" method="post" id="registerForm">
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" value="${customer.name}" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" value="${customer.email}" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" name="address" value="${customer.address}" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="sex" class="col-sm-2 col-form-label">Sex</label>
<div class="col-sm-10">
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline2" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Female</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate</label>
<div class="col-sm-10">
<input type="date" name="bday" value="${customer.bday}" placeholder="Birthdate" required>
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone</label>
<div class="col-sm-10">
<input type="text" name="tele" value="${customer.telephone}" placeholder="Telephone">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="${customer.username}" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="passowrd" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" value="${customer.password}" id="inputPassword" placeholder="Password" data-minlength="6">
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block btn-large">Sign me up.</button>
</form><br>
</div>
Here i changed some things with your code. It should work now. Let me know.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
CustomerViewQuery cvq = new CustomerViewQuery();
try {
List<Customer> customers = cvq.list(name);
request.setAttribute("customers", customers);
request.getRequestDispatcher("CustomerProfile.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain vehicles from DB", e);
}
}
Some changes here too:
public class CustomerViewQuery {
public List<Customer> list(String name) throws SQLException {
List<Customer> customers = new ArrayList<Customer>();
//get connection like this
try(Connection con = DBConnection.dbconnect()) {
PreparedStatement pst = con.prepareStatement("SELECT * FROM customers WHERE username=?;");
pst.setString(1, name); //set name like this (The '1' means first occurance of a question mark '?')
ResultSet resultSet = pst.executeQuery();
while (resultSet.next()) {
Customer customer = new Customer();
customer.setId(resultSet.getInt("id"));
customer.setName(resultSet.getString("name"));
customer.setEmail(resultSet.getString("email"));
customer.setAddress(resultSet.getString("address"));
customer.setSex(resultSet.getString("sex"));
customer.setBday(resultSet.getString("bday"));
customer.setTelephone(resultSet.getString("telephone"));
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
customers.add(customer);
}
}catch(SQLException e) {
e.printStackTrace();
}
return customers;
}
}
your forEach JSTL tag was not iterating over anything...
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach items="${customers}" var="customer">
<div class="container mt-5"><br>
<form role="form" action="CustomerController" data-toggle="validator" method="post" id="registerForm">
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" value="${customer.name}" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" value="${customer.email}" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" name="address" value="${customer.address}" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="sex" class="col-sm-2 col-form-label">Sex</label>
<div class="col-sm-10">
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline2" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Female</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate</label>
<div class="col-sm-10">
<input type="date" name="bday" value="${customer.bday}" placeholder="Birthdate" required>
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone</label>
<div class="col-sm-10">
<input type="text" name="tele" value="${customer.telephone}" placeholder="Telephone">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="${customer.username}" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="passowrd" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" value="${customer.password}" id="inputPassword" placeholder="Password" data-minlength="6">
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block btn-large">Sign me up.</button>
</form><br>
</div>
</c:forEach>
EDIT: Here's how you can do it without a loop:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
CustomerViewQuery cvq = new CustomerViewQuery();
try {
//not list required this time, created a new method called 'getCustomer'
Customer customer = cvq.getCustomer(name);
request.setAttribute("customer", customer);
request.getRequestDispatcher("CustomerProfile.jsp").forward(request, response);
} catch (SQLException e) {
throw new ServletException("Cannot obtain vehicles from DB", e);
}
}
new method in your CustomerViewQuery Class called 'getCustomer'
public class CustomerViewQuery {
public Customer getCustomer(String name) throws SQLException {
Customer customer = new Customer();
try(Connection con = DBConnection.dbconnect()) {
PreparedStatement pst = con.prepareStatement("SELECT * FROM customers WHERE username=?;");
pst.setString(1, name); //set name like this (The '1' means first occurance of a question mark '?')
ResultSet resultSet = pst.executeQuery();
while (resultSet.next()) {
customer.setId(resultSet.getInt("id"));
customer.setName(resultSet.getString("name"));
customer.setEmail(resultSet.getString("email"));
customer.setAddress(resultSet.getString("address"));
customer.setSex(resultSet.getString("sex"));
customer.setBday(resultSet.getString("bday"));
customer.setTelephone(resultSet.getString("telephone"));
customer.setUsername(resultSet.getString("username"));
customer.setPassword(resultSet.getString("password"));
}
}catch(SQLException e) {
e.printStackTrace();
}
return customer;
}
}
no changes here except removed the JSTL forEach tag as it is not needed anymore.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<div class="container mt-5"><br>
<form role="form" action="CustomerController" data-toggle="validator" method="post" id="registerForm">
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" value="${customer.name}" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="email" value="${customer.email}" placeholder="Email">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<input type="text" name="address" value="${customer.address}" placeholder="Address">
</div>
</div>
<div class="form-group row">
<label for="sex" class="col-sm-2 col-form-label">Sex</label>
<div class="col-sm-10">
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline1" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline1">Male</label>
</div>
<div class="custom-control custom-radio custom-control-inline">
<input name="sex" type="radio" value="${customer.sex}" id="customRadioInline2" class="custom-control-input">
<label class="custom-control-label" for="customRadioInline2">Female</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate</label>
<div class="col-sm-10">
<input type="date" name="bday" value="${customer.bday}" placeholder="Birthdate" required>
</div>
</div>
<div class="form-group row">
<label for="telephone" class="col-sm-2 col-form-label">Telephone</label>
<div class="col-sm-10">
<input type="text" name="tele" value="${customer.telephone}" placeholder="Telephone">
</div>
</div>
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" name="username" value="${customer.username}" placeholder="Username">
</div>
</div>
<div class="form-group row">
<label for="passowrd" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" name="password" value="${customer.password}" id="inputPassword" placeholder="Password" data-minlength="6">
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block btn-large">Sign me up.</button>
</form><br>
</div>
Related
I'm trying to set boxes' elements copied from medicineBox's values like below. Can anyone help me in this. I need to post medicineOrder model to the controller
<tr th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
<input type="text" th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" th:value="${medicineBox.box.number}" />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
I'm using two object here -
medicine and medicineOrder
------------------> Controller method to get the page
#GetMapping("/{medicineId}")
public String loadMedicineDetailPage(#PathVariable("medicineId") long medicineId, Model model) {
model.addAttribute("medicine", service.getMedicineById(medicineId));
model.addAttribute("medicineOrder", new MedicineOrder());
return WebPages.MEDICINE_DETAIL.toString();
}
------------------> thymeleaf html page
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Spring Boot Application</title>
</head>
<body>
<div class="container">
<br/>
<a class="btn btn-primary" th:href="#{/mvc/medicine/list}">Back</a>
<br/>
<br/>
<h3 class="text-center alert alert-success">Medicine Details</h3>
<form class="row g-3" action="#" th:action="#{/mvc/medicine/sell}" method="post" th:object="${medicineOrder}">
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="name" class="form-label">Name</label>
<input type="text" style="background-color:#95edea" disabled class="form-control" id="name" th:field="${medicine.name}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="company" class="form-label">Company</label>
<input type="text" disabled class="form-control" id="company" th:field="${medicine.companyStringName}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="price" class="form-label">Price</label>
<input type="text" disabled class="form-control" id="price" th:field="${medicine.price}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="count" class="form-label">Count</label>
<input type="text" class="form-control" id="count" th:field="${medicine.count}"/>
</div>-->
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="volume" class="form-label">ML</label>
<input type="text" disabled class="form-control" id="volume" th:field="${medicine.volume}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="purchaseDate" class="form-label">Date Purchased</label>
<input type="text" disabled class="form-control" id="purchaseDate" th:field="${medicine.purchaseDate}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="boxNo" class="form-label">Box Number</label>
<input type="text" class="form-control" id="boxNo" th:field="${medicine.boxNumber}"/>
</div>-->
**<input type="hidden" th:field="*{medicineId}" th:value="${medicine.medicineId}"/>**
<table class="table table-bordered">
<tr class="table-primary">
<td>Box Number</td>
<td>Medicine Count</td>
<td>Sell Count</td>
</tr>
<tr th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
**<input type="text" th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" th:value="${medicineBox.box.number}"** />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
</table>
<button class="btn btn-primary" type="submit">Sell</button>
</form>
</div>
</body>
</html>
---------------> Controller method to handle the post request
#PostMapping("/sell")
public String sellMedicine(#ModelAttribute MedicineOrder medicineOrder, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
// error handling
}
service.sellMedicine(medicineOrder);
return "redirect:/mvc/medicine/list";
}
----------------> Class MedicineOrder
package com.example.demo.dto;
import com.example.demo.model.Box;
import java.util.ArrayList;
import java.util.List;
public class MedicineOrder {
private long medicineId;
private List<OrderedBox> boxes = new ArrayList<>();
public long getMedicineId() {
return medicineId;
}
public void setMedicineId(long medicineId) {
this.medicineId = medicineId;
}
public List<OrderedBox> getBoxes() {
return boxes;
}
public void setBoxes(List<OrderedBox> boxes) {
this.boxes = boxes;
}
#Override
public String toString() {
return "MedicineOrder{" +
"medicineId=" + medicineId +
", boxes=" + boxes +
'}';
}
}
package com.example.demo.dto;
public class OrderedBox {
private String boxNumber;
private int medicineCount;
public String getBoxNumber() {
return boxNumber;
}
public void setBoxNumber(String boxNumber) {
this.boxNumber = boxNumber;
}
public int getMedicineCount() {
return medicineCount;
}
public void setMedicineCount(int medicineCount) {
this.medicineCount = medicineCount;
}
#Override
public String toString() {
return "OrderedBox{" +
"boxNumber='" + boxNumber + '\'' +
", medicineCount=" + medicineCount +
'}';
}
}
Not able to get the MedicineOrder.medicineId and medicineBorder.boxes[*].boxNumber from template to model object.
After lot of searching I didn't find any answer which is solving the issue only using thymeleaf.
To solve this issue I had to add two hidden input field for medicineId and boxNumber on medicineOrder object and populate those input field using javascript as below. Anyway if anyone find the solution by only using thymeleaf, please let me know.
Populated those fields using javascript
<script>
function function__02__number__assignment(_element){
var __element = _element.children[0];
var __tElement1 = __element.children[0];
var __tElement2 = __element.children[1];
// Copy value from 2 to 1
__tElement1.value = __tElement2.value;
}
function function__01__box_traverse(){
var rootElement = document.getElementsByClassName('box-stock-details');
for(var __i=0 ; __i < rootElement.length ; __i++) {
function__02__number__assignment(rootElement[__i]);
}
function_01_01_medicineId();
return true;
}
function function_01_01_medicineId(){
var _00_1_id_src = document.getElementById('00-1-id-src');
var _00_1_id_dest = document.getElementById('00-1-id-dest');
_00_1_id_dest.value = _00_1_id_src.value;
}
</script>
updated template file
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Spring Boot Application</title>
</head>
<body>
<div class="container">
<br/>
<a class="btn btn-primary" th:href="#{/mvc/medicine/list}">Back</a>
<br/>
<br/>
<h3 class="text-center alert alert-success">Medicine Details</h3>
<form class="row g-3" action="#" th:action="#{/mvc/medicine/sell}" method="post" th:object="${medicineOrder}">
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="name" class="form-label">Name</label>
<input type="text" style="background-color:#95edea" disabled class="form-control" id="name" th:field="${medicine.name}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="company" class="form-label">Company</label>
<input type="text" disabled class="form-control" id="company" th:field="${medicine.companyStringName}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="price" class="form-label">Price</label>
<input type="text" disabled class="form-control" id="price" th:field="${medicine.price}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="count" class="form-label">Count</label>
<input type="text" class="form-control" id="count" th:field="${medicine.count}"/>
</div>-->
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="volume" class="form-label">ML</label>
<input type="text" disabled class="form-control" id="volume" th:field="${medicine.volume}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="purchaseDate" class="form-label">Date Purchased</label>
<input type="text" disabled class="form-control" id="purchaseDate" th:field="${medicine.purchaseDate}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="boxNo" class="form-label">Box Number</label>
<input type="text" class="form-control" id="boxNo" th:field="${medicine.boxNumber}"/>
</div>-->
<!-- Hidden input to get the value of medicineId from Medicine object -->
<input id="00-1-id-src" type="hidden" th:value="${medicine.medicineId}"/>
<!-- Hidden input to set the medicineId on MedicineOrder object -->
<input id="00-1-id-dest" type="hidden" th:field="*{medicineId}" />
<table class="table table-bordered">
<tr class="table-primary">
<td>Box Number</td>
<td>Medicine Count</td>
<td>Sell Count</td>
</tr>
<tr class="box-stock-details" th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
<input hidden th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" />
<input disabled class="form-control" type="text" th:value="${medicineBox.box.number}" />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
</table>
<button class="btn btn-primary" type="submit" onclick="return function__01__box_traverse()">Sell</button>
</form>
</div>
</body>
<script>
function function__02__number__assignment(_element){
var __element = _element.children[0];
var __tElement1 = __element.children[0];
var __tElement2 = __element.children[1];
// Copy value from 2 to 1
__tElement1.value = __tElement2.value;
}
function function__01__box_traverse(){
var rootElement = document.getElementsByClassName('box-stock-details');
for(var __i=0 ; __i < rootElement.length ; __i++) {
function__02__number__assignment(rootElement[__i]);
}
function_01_01_medicineId();
return true;
}
function function_01_01_medicineId(){
var _00_1_id_src = document.getElementById('00-1-id-src');
var _00_1_id_dest = document.getElementById('00-1-id-dest');
_00_1_id_dest.value = _00_1_id_src.value;
}
</script>
</html>
I encountered this issue on uploading image file. It say's that there is something part is missing and I have no idea. I have searched so many things already but still I couldn't find a solution. I'm trying to insert it in database and store the file in my project directory. It's seems I have missed something.
here is my html:
<form autocomplete="off" th:action="#{/AddCriminal}"
enctype="multipart/form-data" method="post" class="m-t" role="form"
th:object="${criminalRec}" data-toggle="validator">
<h1 class="text-white">Add Criminal</h1>
<div th:if="${info}" class="alert alert-success" role="alert"
th:text=${info}></div>
<div th:if="${infoError}" class="alert alert-danger" role="alert"
th:text="${infoError}"></div>
<div class="row text-center">
<div class="col-md-5">
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}"
class="validation-message alert alert-danger" role="alert"></div>
<div th:if="${#fields.hasErrors('seq_number')}"
th:errors="*{seq_number}"
class="validation-message alert alert-danger" role="alert"></div>
<div th:if="${#fields.hasErrors('comments')}"
th:errors="*{comments}"
class="validation-message alert alert-danger" role="alert"></div>
<div class="form-group">
<label class="text-white">Full Name: </label> <input type="text"
th:field="*{name}" placeholder="Wanted Full name"
class="form-control" required /> <small id="firstnameHelp"
class="form-text text-muted text-white">Full name of the
person</small>
</div>
<div class="form-group">
<label class="text-white">Sequence Number: </label> <input
type="text" th:field="*{seq_number}"
placeholder="Sequence Number" class="form-control" required /> <small
id="firstnameHelp" class="form-text text-muted text-white">Sequence
of the records the Ascending order</small>
</div>
<div class="form-group">
<label class="text-white">Photo: </label> <!-- <input type="file"
th:field="*{photo}" placeholder="Add Photo" class="form-control"
accept="image/*" required /> -->
<input type="file" name="photo" accept="image/*" class="form-control" />
<small id="firstnameHelp" class="form-text text-muted text-white">Upload
Photo</small>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" th:field="*{comments}"
placeholder="Facts" rows="3" required></textarea>
<small id="firstnameHelp" class="form-text text-muted text-white">Facts
about this criminal</small>
</div>
</div>
<div class="col-md-5">
<button type="submit" class="btn btn-primary block full-width m-b">Add
Criminal</button>
</div>
</div>
</form>
my controller:
#RequestMapping(value = "/AddCriminal", method = RequestMethod.POST, consumes = "multipart/form-data")
public ModelAndView processCriminal(ModelAndView modelAndView,
#Valid #ModelAttribute("criminalRec") Criminals criminalRec, #RequestParam("photo") MultipartFile file,
BindingResult bindingResult, HttpServletRequest request)
throws SerialException, SQLException, IOException {
if (bindingResult.hasErrors()) {
modelAndView.setViewName("/admin/addwantedperson");
} else {
storageService.store(file);
System.out.println("FILENAME: " + storageService.getFName());
byte [] byteArr=file.getBytes();
Blob blob = new SerialBlob(byteArr);
criminalRec.setPhoto(blob);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.now();
criminalRec.setDate_added(formatter.format(localDate));
criminalService.saveCriminal(criminalRec);
modelAndView.addObject("info", "Criminal Record Successfully Added!");
modelAndView.addObject("criminalRec", new Criminals());
modelAndView.setViewName("/admin/addwantedperson");
}
return modelAndView;
}
In your Application Properties add spring.http.multipart.enabled=true
I have implemented a registration process where you can send user data to the controller via post request.
The post request works fine, however now I want to pass another value (role, Long) from the form to the controller that is not an attribute of the user model.
That part is not working.
Does anyone know why?
HTML:
<form action="add_user" method="post" class="form-horizontal" th:object="${user}">
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{username}" class="form-control" placeholder="Person ID" type="text" name="id" id="id"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{firstName}" class="form-control" placeholder="First Name" type="text" name="firstname" id="firstname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{lastName}" class="form-control" placeholder="Last Name" type="text" name="lastname" id="lastname"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<input th:field="*{password}" class="form-control" placeholder="Password" type="password" name="password" id="password"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<select th:field="${role}" class="form-control" id="role">
<option value="1">Admin</option>
<option value="2" >User</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-1 col-sm-10">
<button type="submit" class="btn btn-success" value="Submit">Save</button>
</div>
</div>
</form>
Controller:
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String showUsers(Model model)
model.addAttribute("user", new User());
model.addAttribute("role", new Long(2));
return "users";
}
And:
#RequestMapping(value = "/add_user", method = RequestMethod.POST)
public String handleNewUser(#ModelAttribute("user") User user, BindingResult bindingResult, Model model, long role) {
if (user != null) {
System.out.println(role);
userService.save(user);
}
return "redirect:/users";
}
th:field="${role}" means name of field in the model object, not its value. You probably want to write th:value="${role}" instead of this.
I am using Spring MVC, Jquery,Hibernate and tomcat while I am trying to call the save method on controller through ajax and Jquery. while click the save button I am getting this syntactically incorrect error on tomcat here is the code
<script type="text/javascript">
function invokeCancel() {
var a = confirm("are you sure to cancel the page");
if (a == true) {
var urlString = "display.do";
$.ajax({
type : "GET",
url : urlString,
success : function(response) {
$("#addEditViewcontractDetailsDiv").html("");
$("#addEditViewcontractDetailsDiv").hide();
},
error : function() {
alert("Error occured during cancel process");
}
});
} else
return false;
}
$("#piId").focusout(function() {
valaidateElement('piId', 'c1');
});
$("#piName").focusout(function() {
validateElement('piName', 'c2');
});
$("#studyId").focusout(function() {
validateElement('studyId', 'c3');
});
$("#studyName").focusout(function() {
validateElement('studyName', 'c4');
});
$("#contractType").focusout(function() {
validateElement('contractType', 'c5');
});
$("#contractStartDate").focusout(function() {
validateElement('contractStartDate', 'c6');
});
$("#contractEndDate").focusout(function() {
validateElement('contractEndDate', 'c7');
});
$("#paymentTerms").focusout(function() {
validateElement('paymentTerms', 'c8');
});
$("#modeOfPayment").focusout(function() {
validateElement('modeOfPayment', 'c9');
});
$("#panNumber").focusout(function() {
validateElement('panNumber', 'c10');
});
function validateAllElements() {
return valaidateElement('piId', 'c1')
&& validateElement('piName', 'c2')
&& validateElement('studyId', 'c3')
&& validateElement('studyName', 'c4')
&& validateElement('contractType', 'c5')
&& validateElement('contractStartDate', 'c6')
&& validateElement('contractEndDate', 'c7')
&& validateElement('paymentTerms', 'c8')
&& validateElement('modeOfPayment', 'c9')
&& validateElement('panNumber', 'c10');
}
$(document).ready(function() {
for ( var i=1; i<11; i++) {
$("#c" + i).hide();
};
$("#saveBtn").click(function() {
if (validateAllElements()) {
$("#contacrtDetailsPage").submit();
}
});
});
$("#updateBtn").click(function() {
if (validateAllElements()) {
$("#contacrtDetailsPage").attr("action", "updateContract.do");
$("#contacrtDetailsPage").submit();
}
});
$(document)
.ready(
function() {
$("#removeVariable").hide();
var counter = 2;
$("#addVariable")
.click(
function() {
$("#removeVariable").show();
if (counter > 10) {
alert("Only 10 milestones allow");
return false;
}
var newTextBoxDiv = $(
document
.createElement('div'))
.attr(
"id",
'milestoneDiv'
+ counter);
newTextBoxDiv
.after()
.html(
'<div class="row">'
+ '<div class="col-md-12">'
+ '<p class="bx-form"><label> MileStone '
+ counter
+ ' </label>'
+ ' '
+ '<input type="text" size="32" id="mileStone" placeholder="Please Enter Milestone" name="mileStone' + counter +
'" path="mileStone' + counter + '" value="" ></p></div></div>');
newTextBoxDiv
.appendTo("#mileStoneGroup");
counter++;
});
$("#removeVariable").click(function() {
counter--;
$("#milestoneDiv" + counter).remove();
if (counter == 2) {
$("#removeVariable").hide();
alert("No more milestones to remove");
return false;
}
});
});
</script>
</head>
<body>
<sf:form id="contacrtDetailsPage" page="contacrtDetailsPage"
modelAttribute="contractDetails" method="post"
action="saveContract.do">
<div class="mx-main">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Contract Details >>
<c:choose>
<c:when test='${ACTION_TYPE == "EDIT"}'>
Update
</c:when>
<c:otherwise>
Create
</c:otherwise>
</c:choose>
</h3>
</div>
<div class="panel-body">
<sf:hidden path="contractDetailsId" />
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="piId">Pi Id <font
color="red">*</font></label>
<sf:input path="piId"
placeholder="Please enter Pi Id" type="text"
id="piId" cols="34" rows="4" maxlength="60"/>
<span id="c1" class="label label-warning">This information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="piName">PI Name <font color="red">*</font></label>
<sf:input path="piName" placeholder="Please Enter PI Name"
type="text" id="piName" size="60" maxlength="60" />
<span id="c2" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="studyId">Study Id <font color="red">*</font></label>
<sf:input path="studyId" placeholder="Please Enter Study Id"
type="text" id="studyId" size="60" maxlength="60" />
<span id="c3" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="studyName">Study Name <font color="red">*</font></label>
<sf:input path="studyName" placeholder="Please Enter Study Name"
type="text" id="studyName" size="60" maxlength="100" />
<span id="c4" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="contractType">Contract Type <font
color="red">*</font></label>
<sf:select path="contractType" id="contractType">
<sf:option value="">-- Select Contract Type --</sf:option>
<sf:option value="Actual">Actual</sf:option>
<sf:option value="Additional">Additional</sf:option>
<sf:option value="Lab">Lab</sf:option>
<sf:option value="Extension">Extension</sf:option>
</sf:select>
<span id="c5" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row" id="otherType">
<div class="col-md-12">
<p class="bx-form">
<label for="contractStartDate">Contract Start Date
<font color="red">*</font>
</label>
<sf:input type="date" path="contractStartDate"
placeholder="Please Enter Contract Start Date"
id="contractStartDate" size="60" />
<span id="c6" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row" id="otherType">
<div class="col-md-12">
<p class="bx-form">
<label for="contractEndDate">Contract End Date <font
color="red">*</font></label>
<sf:input path="contractEndDate"
placeholder="Please Enter Contract End Date" type="date"
id="contractEndDate" size="60" />
<span id="c7" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="paymentTerms">Payment Terms <font
color="red">*</font></label>
<sf:select path="paymentTerms" id="paymentTerms">
<sf:option value="">-- Select Payment Terms --</sf:option>
<sf:option value="One Term">One Term</sf:option>
<sf:option value="MileStone">MileStone</sf:option>
</sf:select>
<span id="c8" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row" id="mileStoneGroup">
<div class="col-md-12" id="milestoneDiv">
<p class="bx-form">
<label for="mileStone1">MileStone </label>
<sf:input path="mileStone" placeholder="Please Enter MileStone1"
type='textbox' id="mileStone1" size="60" maxlength="11" />
<button type="button" id="addVariable" name="addVariable">
<img src="../images/save2.jpg" />
</button>
<button type="button" id="removeVariable" name="removeVariable">
<img src="../images/minus.png" />
</button>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="contractOthers">Others</label>
<sf:input path="contractOthers"
placeholder="Please Enter Others" type="text"
id="contractOthers" size="60" maxlength="60" />
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="irbPayment">IRB Payment</label>
<sf:input path="irbPayment" id="irbPayment"
placeholder="Please Enter IRB Payment" type="text" size="60"
maxlength="60" />
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="iecPayment">IEC Payment</label>
<sf:input path="iecPayment" id="iecPayment"
placeholder="Please Enter IEC Payment" type="text" size="60"
maxlength="60" />
</p>
</div>
</div>
<div class="row" id="otherType">
<div class="col-md-12">
<p class="bx-form">
<label for="modeOfPayment">Mode of Payment <font
color="red">*</font></label>
<sf:select path="modeOfPayment" id="modeOfPayment">
<sf:option value="">-- Select Mode of Payment--</sf:option>
<sf:option value="Cheque">Cheque</sf:option>
<sf:option value="Draft">Draft</sf:option>
<sf:option value="Cash">Cash</sf:option>
</sf:select>
<span id="c9" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="inFavorOf">In Favor Of</label>
<sf:input path="inFavorOf"
placeholder="Please Enter In Favor Of" type="text"
id="inFavorOf" size="60" maxlength="60" />
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="paybleAt">Payable At</label>
<sf:input path="paybleAt" id="paybleAt"
placeHolder="Please Enter The Payable At" size="60"
maxlength="60" />
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<label for="panNumber">PAN Number <font color="red">*</font></label>
<sf:input path="panNumber" id="panNumber"
placeHolder="Please Enter The PAN Number" size="60"
maxlength="30" />
<span id="c10" class="label label-warning">This
information is required.</span>
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p class="bx-form">
<c:choose>
<c:when test='${ACTION_TYPE == "EDIT"}'>
<button type="button" id="updateBtn" class="btn btn-success">Update</button>
</c:when>
<c:otherwise>
<button type="button" id="saveBtn" name="cmd"
class="btn btn-success">Save</button>
</c:otherwise>
</c:choose>
<button type="button" id="cancelBtn" class="btn btn-warning"
onclick="javascript:invokeCancel();">Cancel</button>
</p>
</div>
</div>
</div>
</div>
</div>
</sf:form>
</body>
</html>
Controller:Code
/************************************* Save ContractDetails *****************************/
#RequestMapping(value = "/saveContract", method=RequestMethod.POST)
public ModelAndView saveContractDetails(ContractDetails contractDetails,
BindingResult result) {
contractDetailsService.createContractDetails(contractDetails);
ModelAndView model = new ModelAndView(PagesI.CONTRACT_DETAILS_DISPLAY);
model.addObject("contractDetailsList",
contractDetailsService.getContractDetailsList());
model.addObject("DISPLAY_VIEW_PAGE", "Y");
return model;
}
It seems like your are missing something in your saveContractDetails method inside your controller.
When you submit your form, you are sending a request on "/saveContract" and passing the model attribute contractDetails to it.
In order for Spring to be able to process your request, I think you have to specify inside the declaration of the saveContractDetails method that you are sending a model attribute.
I would try something like that:
#RequestMapping(value = "/saveContract", method=RequestMethod.POST)
public ModelAndView saveContractDetails(#ModelAttribute ContractDetails contractDetails,
BindingResult result) { ... }
My code was working perfectly fine a while ago until my classmate sent a modified HTML file and every single parameter is now null. I don't really know what happened. I'm transferring the information from the form to the servlet and from the servlet, I'm transferring it to the database. Here's the code for the form:
<form method="post" action="informationTransfer">
<div class='row'>
<div class='col-md-6'>
<label for="username">User Name</label>
<input type="text" class="form-control" id="username" placeholder="User Name" name='username' required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for="lastName">Last Name</label>
<input type="text" class="form-control" id="lastName" placeholder="Last Name" name='LastName' required>
</div>
<div class='col-md-6'>
<label for="firstName">Name</label>
<input type="text" class="form-control" id="firstName" placeholder="First Name" name='FirstName' required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for="lastName">E-Mail</label>
<input type="email" class="form-control" id="email_1" placeholder="E-Mail Address" name='Email' required>
</div>
<div class='col-md-6'>
<label for="firstName">Confirm E-Mail</label>
<input type="email" class="form-control" id="email_2" placeholder="Confirm E-Mail Address" required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for="lastName">Password</label>
<input type="password" class="form-control" id="password_1" placeholder="Password" name='Password' required>
</div>
<div class='col-md-6'>
<label for="firstName">Confirm Password</label>
<input type="password" class="form-control" id="password_2" placeholder="Confirm Password" required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-6'>
<label for='birthDate'>Birthday</label>
<div class="bfh-datepicker" data-max="today" data-close="false" data-date="today" data-format="y-m-d">
<input id="birthDate" type="text" data-name="birthDate" name='Birthdate' style='background-color:white;'>
</div>
</div>
<div class='col-md-6'>
<label for='gender'>Gender</label>
<select class='form-control' name='gender'>
<option>Male</option>
<option>Female</option>
</select>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-4'>
<label for="countries_selectors">Country</label>
<select id="countries_selectors" class="form-control bfh-countries" data-country="PH" name='country' required></select>
</div>
<div class='col-md-4'>
<label for="State">State</label>
<select class="form-control bfh-states" data-country="countries_selectors" id='State' name='State' required></select>
</div>
<div class='col-md-4'>
<label for="zip">Zip Code</label>
<input type="zip" class="form-control" id="zip" placeholder="Zip Code" name='zipcode' required>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-12'>
<label for="address">Home Address</label>
<input type="text" class="form-control" id="address" placeholder="Last Name" name='Address' required>
</select>
</div>
</div>
<br />
<div class='row'>
<div class='col-md-10'>
<label for="phone">Contact Number</label>
<input type="text" class="form-control bfh-phone" data-country="countries_selectors" id="phone" name='PhoneNumber'>
</div>
<div class='col-md-2'>
<label for="signup_b"><br /></label>
<button type="submit" class="btn btn-default center-block" name='signup_b'>Sign Up!</button>
</div>
</div>
</form>
Here's the code for the servlet:
#WebServlet(description = "transfers contents of bean to database", urlPatterns = { "/informationTransfer" })
public class transferInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
toDatabase(request, response);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
toDatabase(request, response);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void toDatabase(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, ClassNotFoundException
{
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/FoundationSystem","root","!Qaz2wsx");
con.setAutoCommit(false);
try
{
PreparedStatement stmt1, stmt2, stmt3;
stmt1 = con.prepareStatement("INSERT INTO AddressInformation (AddressID, Country, ZipCode, State, Address) VALUES (null,?,?,?,?)");
stmt1.setString(1, request.getParameter("country"));
stmt1.setString(2, request.getParameter("zipCode"));
stmt1.setString(3, request.getParameter("state"));
stmt1.setString(4, request.getParameter("address"));
stmt1.executeUpdate();
stmt2 = con.prepareStatement("INSERT INTO AccountDetails VALUES (?,?,?,?,?)");
stmt2.setString(1, request.getParameter("username"));
stmt2.setString(2, request.getParameter("password"));
stmt2.setString(3, null);
stmt2.setString(4, null);
stmt2.setInt(5, 3);
stmt2.executeUpdate();
stmt3 = con.prepareStatement("INSERT INTO PersonalInformation VALUES (?,?,?,?,?,?,?,?)");
Statement address = con.createStatement();
ResultSet result = address.executeQuery("SELECT max(AddressID) FROM AddressInformation");
result.next();
stmt3.setString(1, request.getParameter("userName"));
stmt3.setString(2, request.getParameter("lastName"));
stmt3.setString(3, request.getParameter("firstName"));
stmt3.setString(4, request.getParameter("gender"));
stmt3.setString(5, request.getParameter("birthdate"));
stmt3.setInt(6, result.getInt(1));
stmt3.setString(7, request.getParameter("email"));
stmt3.setString(8, request.getParameter("phoneNumber"));
stmt3.executeUpdate();
con.commit();
//response.sendRedirect();
}
catch (Exception e)
{
con.rollback();
System.out.println(e);
}
}
}
Take care of case here. For eg.
<input type="zip" class="form-control" id="zip" placeholder="Zip Code" name='zipcode' required>
you get this data by
stmt1.setString(2, request.getParameter("zipcode"));
and not
stmt1.setString(2, request.getParameter("zipCode")); // C is capital
name of the input tag in your form should match the parameter name you use in getParameter() method.
Seems name case problem. Match parameter name of your input fields in html file and request.getParameter("fieldName") in your servlet