I am using a form where i am adding an state into the database but now i want to use a server side validation for this form (like checking whether it is empty or not.) So please help me in this.
By the way i am new in jsp and want to learn server side validation in jsp page so plese let me know how to go about it.
String sql="insert into tblstate(fkCountry_Id,fldstate) "
+ "values('"+cou+"','"+sta+"')";
try{
conn.createStatement().executeUpdate(sql);
conn.setAutoCommit(true);
// New location to be redirected
String site = new String("add_state.htm");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
}catch(Exception e){
e.printStackTrace();
}
%>
" method="POST">
<div class="control-group">
<label class="control-label" for="selectError">Country</label>
<select class="form-control" name="cou">
<option value="none">Select</option>
<%
String sql_cou = "select * from tblcountry";
PreparedStatement coun=conn.prepareStatement(sql_cou);
ResultSet rs_cou = coun.executeQuery(sql_cou);
while(rs_cou.next()){
out.println("<option value=" + rs_cou.getString("pkCountry_Id")+ "> " + rs_cou.getString("fldCountry")+"</option>");
}
%>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">State</label>
<input name="sta" type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Dzongkhag">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
Related
I am trying to allow currently logged in user of my spring application update their current details but it is not persisting to the database, I am getting no errors and have tried to debug but have gotten no success.. please take a look.
Service class:
#Transactional
public User updateAccount(User userInForm){
System.out.println("Fetching user with id: " + userInForm.getId());
Optional<User> optionalUser = repo.findById(userInForm.getId());
if(!optionalUser.isPresent()){
System.out.println("User not found.");
return null;
}
User userInDB = optionalUser.get();
System.out.println("User fetched: " + userInDB);
userInDB.setFirstName(userInForm.getFirstName());
userInDB.setLastName(userInForm.getLastName());
System.out.println("Saving updated user: " + userInDB);
User savedUser = repo.save(userInDB);
System.out.println("User saved: " + savedUser);
return savedUser;
}
Controller class:
#PostMapping("/myAccount/update")
public String updateAccount(User user, RedirectAttributes redirectAttributes, Principal principal){
System.out.println("Updating user details...");
user = repo.findByEmail(principal.getName());
User updatedUser = service.updateAccount(user);
if (updatedUser == null) {
System.out.println("Error updating user details.");
} else {
redirectAttributes.addFlashAttribute("message", "Details Updated!");
return "redirect:/myAccount";
}
return "redirect:/myAccount";
}
Front end:
<h1 style="color:green">Welcome <b>[[${#request.userPrincipal.principal.fullName}]]</b></h1>
<h2 style="color:green">My Details</h2>
<div th:if="${message}" class ="alert alert-success text-center">
[[${message}]]
</div>
<form th:action="#{/myAccount/update}" th:object="${user}"
method="post" style="max-width: 600px; margin: 0 auto;">
<div class="m-3">
<div class="form-group row">
<label class="col-4 col-form-label">E-mail: </label>
<div class="col-8">
<input type="email" th:field="*{email}" class="form-control" readonly="readonly" />
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Password: </label>
<div class="col-8">
<input type="password" th:field="*{password}" placeholder="Leave blank if you don't want to change!" class="form-control"
minlength="6" maxlength="10"/>
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">First Name: </label>
<div class="col-8">
<input type="text" th:field="*{firstName}" class="form-control"
required minlength="2" maxlength="20"/>
</div>
</div>
<div class="form-group row">
<label class="col-4 col-form-label">Last Name: </label>
<div class="col-8">
<input type="text" th:field="*{lastName}" class="form-control"
required minlength="2" maxlength="20" />
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">Update Details</button>
</div>
</div>
</form>
Printed statements in console:
Updating user details...
Fetching user with id: 1
User fetched: com.example.Model.User#330603d0
Saving updated user: com.example.Model.User#330603d0
User saved: com.example.Model.User#330603d0
You are reassigning the user object received from the request to some other value. Check the below lines from the controller method
user = repo.findByEmail(principal.getName()); // this line reassigning the user object from the request to that of the one in database.
User updatedUser = service.updateAccount(user);
Because of this, user details are getting updated but with the existing data.
I'm trying to upload a file to cloudinary. I'm stucked at how to only get parts of image from the form. It keeps on throwing exception: Invalid image file. If I remove all text inputs in the form, the uploading is successful. I guess that happens because the form also has text inside. Please help me solve this. I'm really grateful for your support.
Here is my code:
Form.jsp:
<form role="form" action="<c:url value="/admin/product/update"/>" method="post" enctype="multipart/form-data">
<input name="id" value="${product.id}" hidden="">
<div class="form-group">
<label>Name:</label> <input class="form-control" value="${product.name}" name="name" />
</div>
<div class="form-group">
<label>Price:</label> <input class="form-control" value="${product.price}" type="number" name="price" />
</div>
<div class="form-group">
<label>Quantity:</label> <input class="form-control" value="${product.quantity}" type="number" name="quantity" />
</div>
<div class="form-group">
<label>Image:</label> <input class="form-control" value="${product.image}" name="image" />
</div>
<div class="form-group">
<label>Description </label> <br>
<textarea rows="4" cols="50" name="description" value="${product.description}" ></textarea>
</div>
<div class="form-group">
<label>Category</label>
<div class="checkbox">
<select name="catid">
<c:forEach items="${categorylist}" var="c">
<option value="${c.id}">${c.name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label>image</label> <input type="file" name="image" value="${product.image }" />
</div>
Servlet.java
BeanUtils.populate(product, request.getParameterMap());
//if (catid != product.getCategory().getId()) {
// Category category = new Category();
category = dao2.getCategoryByID(catid);
product.setCategory(category);
Map result = null;
Collection<Part> fileParts = request.getParts();
for (Part part : fileParts) {
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
String url = String.valueOf(result.get("url"));
product.setImage(url);
if (result == null) {
throw new RuntimeException("Loi upload");
}
}
dao.update(product);
The Cloudinary upload method supports uploading media files from the sources like a local path, a remote URL, a private storage URL (S3 or Google Cloud storage), a base64 data URI, or an FTP URL.
Based on your code, it seems that you are only supplying the filename of the image.
String fileName = part.getSubmittedFileName();
result = UploadImage.uploadImage(fileName, part);
You would need to update the code to input the local path of the image.
I encountered a problem in the connection between an HTML page and a servlet in Java. I already had this problem a few days ago but it was my mistakes in project management.
Now, it seems to me that I have done everything properly but I cannot deal with it.
In particular I'm creating an HTML page that contains a form with the action that call a servlet. My HTML page is on the "Web content" directory automatically created by Eclipse when I create a new Dynamic web project.
my WebServlet annotation is "#WebServlet(/UploadBook)" and the action on the form tag is "action=UploadBook".
When I click on the submit button the page this is the message that I receive:
Not Found
The requested URL /coltraneShop/Administrator/adminColtraneShop/WebContent/UploadBook was not found on this server.
I'm using Firefox on MacOS and apache webServer is started. I added, moreover, the Dynamic web project on server tomcat 9 from Eclipse and started it without problem.
This is my servlet Java code:
package insertion;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/UploadBook")
public class UploadBook extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out= response.getWriter();
Long productCode= (long) 0;
//Fetch data from HTML form method POST
String title= request.getParameter("Title");
String quantity= request.getParameter("Quantity");
String yearOfPublication= request.getParameter("yearOfPublication");
String genre= request.getParameter("Genre");
String numPages= request.getParameter("numPages");
String ISBN= request.getParameter("ISBN");
String publisher= request.getParameter("publisher");
String writerName1= request.getParameter("writerName1");
String writerSurname1= request.getParameter("writerSurname1");
String writerDateOfBirth1= request.getParameter("writerDateOfBirth1");
String writerGender1= request.getParameter("writerGender1");
Connection connection= null;
//Connect to DB
try {
connection= connectDB();
}
catch (ClassNotFoundException | SQLException ConnectionException) {
System.out.println("Error in connection!");
out.print("Connection to DB is not avaiable. " + ConnectionException.getMessage());
}
//Send query to DB
try {
//Preparing statement and query to DB
PreparedStatement statementProduct = connection.prepareStatement("INSERT INTO coltraneShop.Product (Category, `Title`, Quantity, `Year of publication`)"
+ "VALUES ('Book', ?, ?, ?);", Statement.RETURN_GENERATED_KEYS);
//Passing parameters
statementProduct.setString(1, title);
statementProduct.setInt(2, Integer.parseInt(quantity));
statementProduct.setInt(3, Integer.parseInt(yearOfPublication));
int affectedRows= statementProduct.executeUpdate();
if(affectedRows == 0)
throw new SQLException("Creating product failed, no rows affected.");
//Return ID of product insert in DB
ResultSet resultSet = statementProduct.getGeneratedKeys();
if(resultSet.next())
productCode= resultSet.getLong(1);
statementProduct.close();
out.print("<p>Added a product</p><br>");
PreparedStatement statementBook = connection.prepareStatement("INSERT INTO coltraneShop.Book VALUES (?, ?, ?, ?, ?);");
statementBook.setString(1, genre);
statementBook.setInt(2, Integer.parseInt(numPages));
statementBook.setLong(3, Long.parseLong(ISBN));
statementBook.setString(4, publisher);
statementBook.setLong(5, productCode);
int affectedRowsBook= statementBook.executeUpdate();
if(affectedRowsBook == 0)
throw new SQLException("Creating book failed, no rows affected.");
statementBook.close();
out.print("<p>Added a book</p><br>");
PreparedStatement statementWriter1 = connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
statementWriter1.setString(1, writerName1);
statementWriter1.setString(2, writerSurname1);
statementWriter1.setString(3, writerDateOfBirth1);
statementWriter1.setString(4, writerGender1);
int affectedRowswriter1= statementWriter1.executeUpdate();
if(affectedRowswriter1 == 0)
throw new SQLException("Creating writer failed, no rows affected.");
statementWriter1.close();
out.print("<p>Added a writer</p><br>");
int elementInRequest= request.getContentLength();
if(elementInRequest > 10) {
int numAdditionalWriter= (elementInRequest - 10) / 4;
for(int i=0; i<(numAdditionalWriter); i++) {
PreparedStatement statementAdditionalWriter= connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
statementAdditionalWriter.setString(1, ("writerName" + (i+2)));
statementAdditionalWriter.setString(2, ("writerSurname" + (i+2)));
statementAdditionalWriter.setString(3, "writerDateOfBirth" + (i+2));
statementAdditionalWriter.setString(4, "writerGender" + (i+2));
int affectedRowsAdditionalWriter= statementAdditionalWriter.executeUpdate();
if(affectedRowsAdditionalWriter == 0)
throw new SQLException("Creating addtional writer failed, no rows affected.");
statementAdditionalWriter.close();
out.print("<p>Added a writer</p><br>");
}
}
}
catch (SQLException exceptionInQuery) {
System.out.println("Error in the query");
out.print("Error in statement or process of sending queries to the database. " + exceptionInQuery.getMessage());
}
try {
connection.close();
}
catch (SQLException closeConnectionException) {
System.out.println("Problem in closing connection");
out.print("Problem in closing connection. " + closeConnectionException.getMessage());
}
out.close();
}
private Connection connectDB() throws ClassNotFoundException, SQLException {
Connection connection= null;
Class.forName("com.mysql.cj.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/coltraneShop?useTimezone=true&serverTimezone=UTC", "root", "");
return connection;
}
}
And This is my HTML form code:
<head>
<title>Insert book in the database</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<!--Bootstrap CSS-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="administrator.js"></script>
</head>
<body>
<form action="UploadBook" method="POST">
<div class="container">
<div class="form-group">
<label> <strong>Title:</strong> </label>
<input type="text" name="Title" class="form-control" placeholder="Title of book" maxlength="50" required>
</div>
<div class="form-group">
<label> <strong>Quantity:</strong> </label>
<input type="text" class="form-control" name="Quantity" placeholder="Max quantity in stock can be 999" maxlength="3" pattern="[0-9]{1,3}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Year of publication:</strong> </label>
<input type="text" class="form-control" name="yearOfPublication" placeholder="Year of publication" maxlength="4" pattern="[0-9]{1,4}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Genre:</strong> </label>
<select class="form-control" name= "Genre" required>
<option value="History" >History</option>
<option value="Fantasy">Fantasy</option>
<option value="Child">Child</option>
<option value="Art">Art</option>
<option value="Music">Music</option>
<option value="Thriller">Thriller</option>
<option value="Travel">Travel</option>
<option value="Biography">Biography</option>
<option value="Poetry">Poetry</option>
<option value="Romance">Romance</option>
<option value="Science">Science</option>
</select>
</div>
<div class="form-group">
<label> <strong>Number of pages:</strong> </label>
<input type="text" class="form-control" name="numPages" placeholder="Max length: 99.999 pages" maxlength="5" pattern="[0-9]{1,5}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>ISBN:</strong> </label>
<input type="text" class="form-control" name="ISBN" placeholder="13-digit code" maxlength="13" pattern="[0-9]{1,13}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Publisher:</strong> </label>
<input type="text" class="form-control" name="publisher" placeholder="The name of the publishing house" maxlength="30" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's name:</strong> </label>
<input type="text" class="form-control" name="writerName1" placeholder="The name of the Writer" maxlength="20" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's surname:</strong> </label>
<input type="text" class="form-control" name="writerSurname1" placeholder="The surname of the Writer" maxlength="20" pattern="[A-z]{1,20}" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's date of birth:</strong> </label>
<input type="date" class="form-control" name="writerDateOfBirth1"></input>
</div>
<div class="form-group">
<label> <strong>Writer's gender:</strong> </label>
<input type="text" class="form-control" name="writerGender1" placeholder="Gender of writer: can be 'M' or 'F' or 'N(on defined)'" maxlength="1" pattern="^(M|F|N)" ></input>
</div>
<div class="form-group" id="containerWriters">
<button type="button" class="btn btn-outline-success" id="addWriterButton" onclick="addWriter()"> Add Writer </button>
<button type="button" class="btn btn-outline-danger" id="removeWriterButton" onclick="removeWriter()"> Remove Writer </button>
</div>
<!--Submit all data -->
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Insert" id="submit"></input>
</div> <!--Container div-->
</form>
<!-- Bootstrap jQuery, Ajax and JavaScript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
Thank a lot for helping me.
It looks like you loaded file directly from file system and the tried to call this servlet. This is not correct. Load this HTML via your Tomcat, i.e. via URL like
http://localhost:8080/.../xxx.html.
If because of some reason you still want to use static HTML without Tomcat, then change servlet URL in your HTML to a full URL like following:
<form action="http://localhost:8080/.../UploadBook" method="POST">
If none of this is your case, then provide more info, how exactly are you loading HTML in you browser.
Here is my code.When I check checkbox and click the edit button the value is fetched correctly.But edited value is not updated in mysql database as well as table.I'm using jdbc template for this example."location" field is select option value.
controller get the checkbox value and fetch data from database.after that the updated value is not shown in the table.
HomeController.java
#RequestMapping("/edit")
public String update(Model model,#RequestParam Map<String,String> req){
updateValue = new Integer(req.get("checkId"));
List<Users> users = userdao.getUpdateRecord(updateValue);
model.addAttribute("result",users);
return "formedit";
}
#RequestMapping("/saveUpdate")
public String saveUpdate(Model model,#RequestParam Map<String,String> req){
String name,storage,location,address;
name = req.get("name");
storage=req.get("storage");
location=req.get("location");
address = req.get("address");
int row = userdao.updateRecord(updateValue,name,storage,location,address);
String message = row+ "updated";
model.addAttribute("message", message);
result(model);
return "home";
}
UsersDAO doesn't get the update value from formedit page.
UsersDAO.java
public List<Users> getUpdateRecord(int updateValue){
System.out.println("update value"+updateValue);
String sql="select id,name,storage,location,address from customer where id="+updateValue;
return jdbc.query(sql,new UsersMapper());
}
public int updateRecord(int id,String name,String storage,String location,String address){
return jdbc.update("update customer set name = ?,storage = ?,location = ?,address=? where id = ?",id,name,storage,location,address);
formedit.jsp
<form role="form" action="saveUpdate" method="post" class="form-horizontal">
<c:forEach var="row" items="${result}">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-xs-4 text">Customer Name</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="name" value=${row.name }>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4 text">Storage Location*</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="storage" value=${row.storage }>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-xs-4 text">Location</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="location" value=${row.location }>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4 text">Customer Address</label>
<div class="col-xs-8">
<textarea class="form-control" name="address">${row.address }</textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-success btn-md col-md-offset-6" value="Update">
</div>
</c:forEach>
</form>
}
Because this is wrong:
return jdbc.update("update customer set name = ?,storage = ?,location = ?,address=? where id = ?",id,name,storage,location,address);
The parameters order is incorrect, it doesnt find id with value address.
I am using html5 validation for my form in jsp page. I have given novalidate in form. When i click on submit button of that form it should validate the form now and display all validation in one label which was hidden before.How can i get these in jsp?
This is my form code.
<form action="#join1_form" method="POST">
<div>
<input type="text" name="firstname" id="firstname" value="" required placeholder="First Name" pattern="\w+" />
<input type="text" name="lastname" id="lastname" value="" required placeholder="Last Name" pattern="\w+" />
</div>
<div>
<input type="email" name="email" placeholder="Your Email" id="email" value="" required />
</div>
<div>
<input name="password" id="password" type="password" required placeholder="New Password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" name="password" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Password must contain at least 6 characters, including UPPER/lowercase and numbers' : '');
if(this.checkValidity()) form.cpassword.pattern = this.value;">
</div>
<div>
<input name="cpassword" id="cpassword" type="password" placeholder="Re-enter Password" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}" name="cpassword" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');">
</div>
<div>
<input type="label" hidden value="">
</div>
<input type="submit" value="Next">
</form>
I want to display all the validation notes after submitting the submit button.These validations should displaye in textfield which is given hidden here.how can i do that?
this is my code for not repeating the emailID. where should i put this in above form?How to display its validation in the textfield which is given hidden above?
<%
Connection conn = null;
PreparedStatement ps=null;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "");
String email1=request.getParameter("lemail");
try{
String q="SELECT * FROM userdetails where email=?";
ps=conn.prepareStatement(q);
ps.setString(1,email1);
rs=ps.executeQuery();
if(rs.next())
{
//what to do here?
}
else
{
//what to do here?
}
}
catch(Exception e)
{
e.printStackTrace();
}
try{
if(ps!=null){
ps.close();
}
if(rs!=null){
rs.close();
}
if(conn!=null){
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<html:form action="storenotes" onsubmit="return demo()">
call demo() function in your JavaScript
and submit form by
return true
or
return false