I am working with Spring MVC architecture and Hibernate using H2 Database.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add New Product</title>
</head>
<body>
<p>Add New Product !!</p>
<form:form action="addProducttoDB" commandName="product" method="POST" enctype="multipart/form-data">
Product id :<br>
<label>Product Name : </label><form:input path="product_name" value="Product Name"/> <br>
Product Desc : <form:input path="product_desc" value="Product Desc"/><br>
Select Image :<form:input type="file" path=""/><br>
Submit : <input type="submit" value="Add">
</form:form>
</body>
</html>
As in above code - its storing the information about prodouct and adding to Database using action request -> "addProducttoDB" , Model object -> product
And path is the column name, now I would like to save an image along with the details. How can I do that?
You need to do following change
give name to <form:input type="file" path="productImg" name="productImg/>
Declare MultipartFile object in method signature where datastore logic is there
call the save saveMultipartFile method inside the save method
method
private void saveMultipartFile( MultipartFile files)
{
if(!files.isEmpty()){
try {
String fileName = files.getOriginalFilename();
String dirLocation ="Path where you want to save image";
if(!new File(dirLocation).exists()){
File file = new File(dirLocation);
file.mkdirs();
}
byte[] bytes = files.getBytes();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(dirLocation+new File(fileName)));
bufferedOutputStream.write(bytes);
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Related
I have a problem with checkbox. I have such jsp page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>All Photos</title>
</head>
<body>
<form action="/photos/deletePhotos">
<c:forEach var="photo" items="${photoList}">
<p><input type="checkbox" name="id" value="${photo.key}">${photo.key}</p>
<img src="/photos/photo/${photo.key}" width="300" height="200">
<br/><br/>
</c:forEach>
<input type="submit" value="Delete" />
</form>
</body>
</html>
and such controller:
#RequestMapping("/deletePhotos")
public ModelAndView deleteSomePhotos(#PathVariable(name = "id", required = false) long[] id) {
System.out.println(id);
return new ModelAndView("all", "photoList", photos);
}
problem is id==null, no matter checked checkbox or not. Where is my mistake?
#PathVariable is for path variable, like #RuquestMapping("/deletePhotos/{id}").
Use #RequestParam instead of #PathVariable.
Refer here : #RequestParam vs #PathVariable
I'm getting the following error. I am going to insert the excel sheet data into MYSQL database. When I upload the Excel sheet and press submit button ,the following exception occured.
java.io.FileNotFoundException: studentsdetails1.xls (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
Here is my code. In this I am going to insert the excel file data into database.
index.jsp-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action ="Excel.jsp" method="post" >
<input type="file" name= "excelfile" size="20" id="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Excel.jsp-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" `"http://www.w3.org/TR/html4/loose.dtd"> `
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%# page import ="java.util.Date" %>
<%# page import ="java.sql.*" %>
<%# page import ="java.io.*" %>
<%# page import ="java.io.FileNotFoundException" %>
<%# page import ="java.io.IOException" %>
<%# page import ="java.util.Iterator" %>
<%# page import ="java.util.ArrayList" %>
<%# page import ="javax.servlet.http.HttpServletRequest"%>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
<%# page import ="akshay.Exceltest" %>
<%# page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
<%!
Connection con;
PreparedStatement ps=null;
Statement stmt= null;
public static ArrayList readExcelFile(String fileName)
{
/** --Define a ArrayList
--Holds ArrayList Of Cells
*/
System.out.println(fileName);
ArrayList cellArrayLisstHolder = new ArrayList();
try{
/** Creating Input Stream**/
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreArrayList=new ArrayList();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreArrayList.add(myCell);
}
cellArrayLisstHolder.add(cellStoreArrayList);
}
}catch (Exception e){e.printStackTrace(); }
return cellArrayLisstHolder;
}%>
<%
String file = request.getParameter("excelfile");
String fileName=""+file+""; //testExcel.xls Excel File name
//Read an Excel File and Store in a ArrayList
ArrayList dataHolder=readExcelFile(fileName);
//Print the data read
//printCellDataToConsole(dataHolder);
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/<dtatabse>", "name", "password");
stmt =con.createStatement();
String query="insert into students12(id,name,age) values(?,?,?)";
ps=con.prepareStatement(query);
int count=0;
ArrayList cellStoreArrayList=null;
//For inserting into database
for(int i=1;i<dataHolder.size();i++) {
cellStoreArrayList=(ArrayList)dataHolder.get(i);
ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
count= ps.executeUpdate();
//out.print(((HSSFCell)cellStoreArrayList.get(2)).toString() + "\t");
}
//For checking data is inserted or not?
if(count>0)
{
%>
Following deatils from Excel file have been inserted in student table of database
<table>
<tr>
<th>Student's Name</th>
<th>Class</th>
<th>Age</th>
</tr>
<%
for (int j=1;j < dataHolder.size(); j++) {
cellStoreArrayList=(ArrayList)dataHolder.get(j);%>
<tr>
<td><%=((HSSFCell)cellStoreArrayList.get(0)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(1)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(2)).toString() %></td>
</tr>
<%}
}
else
{%>
<center> Details have not been inserted!!!!!!!!!</center>
<% }
}catch(Exception e)
{}%>
</table>
</body>
</html>
Add enctype="multipart/form-data" in form like.
<form action ="Excel.jsp" method="post" enctype="multipart/form-data" >
Rest looks fine.
i want to make a webpage where people can register, build their own AI on the Ultimatum-Game as a Java Class and compete each other. The can edit their Class in a textarea, which get stored in a database.
My problem is now getting an object from a class that is just a String yet.
I hope someone can help me.
best regards
test.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>random</title>
</head>
<body>
<form action="test2.jsp" method="post">
<div>
<label for="text">Klasse</label>
<textarea id="text" name="text" cols="100" rows="50">
public class test {
String teststring;
public test() {
this.teststring ="Hallo";
}
}
</textarea>
<input type="submit" value="Senden" />
</div>
</form>
</body>
</html>
test2.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>random</title>
</head>
<body>
<form action="test2.jsp" method="post">
<div>
<label for="text">Klasse</label>
<textarea id="text" name="text" cols="100" rows="50">
public class test {
String teststring;
public test() {
this.teststring ="Hallo";
}
}
</textarea>
<input type="submit" value="Senden" />
</div>
</form>
</body>
</html>
Hello I am trying to save data from a form to database however I have no idea how to continue now. I have this following code.
I tried using the request.getParameter("id") in the controller which gave me an compiler error.
So how do I get the data from the jsp form to the controller and then save them to the MySQL database ?
jsp file
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ProductController" method="post">
<p>Enter product name :</p> <input id="productName" type="text" name="username"> <BR>
<p>Enter product serial number :</p> <input id="serialNumber" type="password" name="password"> <BR>
<input type="submit" placeholder="Submit" />
</form>
</body>
</html>
The controller
#Controller
#RequestMapping("/product")
public class ProductController {
#Autowired
private ProductService productService;
#RequestMapping("/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("product/list");
System.out.println("Count:" + productService.getProducts().size());
modelAndView.addObject("test", "mytest");
modelAndView.addObject("count", productService.getProducts().size());
modelAndView.addObject("products", productService.getProducts());
return modelAndView;
}
}
and product DAO
#Override
public void saveProduct(Product product) {
//persist(product);
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(product);
tx.commit();
session.close();
}
you have to use name attribute of html element to get value, like request.getParameter("username");
how to compare two txt or pdf files in html or jsp using md5 algorithm? please post the code
<%# page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form method=post action="nextpage.jsp">
<h3>Select File 1:</h3><input type="file" name="fileName1" id="file1">
<h3>Select File 2:</h3><input type="file" name="fileName2" id="file2">
<br>
<br>
<input type="button" name="Compare" value="Compare">
</form>
</body>
</html>
this is my index.jsp file
<%# page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<%= request.getParameter("fileName1") %>
<%= request.getParameter("fileName2") %>
</body>
</html>
this is nextpage.jsp
i want to compare these two input files using message digest..
i have a java code of md5
public String msgDigest(String fname)throws Exception
{
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream(fname);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1)
{
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++)
{
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
String result= sb.toString();
return result;
}
how can i compare two files?
I made a project that check the md5 of two files and show you the result. here are the codes.
the code for servlet :
#WebServlet("/upload")
#MultipartConfig
public class Md5ServletProcessor extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String md5ForFirstFile = getMd5String(request, "file1");
String md5ForSecondFile = getMd5String(request, "file2");
response.sendRedirect("result.jsp?file1Md5="+md5ForFirstFile+"&file2Md5="+md5ForSecondFile+"&filesEqual="+md5ForFirstFile.equals(md5ForSecondFile));
}
private String getMd5String(HttpServletRequest request, String parameter) throws ServletException, IOException{
Part filePart = request.getPart(parameter);
InputStream is = filePart.getInputStream();
return DigestUtils.md5Hex(is);
}
}
jsp main page :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Java MD5CheckSum</title>
</head>
<body>
<div>
<h3> Choose Two Files for MD5CheckSum : </h3>
<form action="upload" method="post" enctype="multipart/form-data">
<table>
<tr>
<th>File 1:</th>
<td><input type="file" name="file1" /></td>
</tr>
<tr>
<th>File 2:</th>
<td> <input type="file" name="file2" /></td>
</tr>
</table>
<input type="submit" value="upload" />
</form>
</div>
</body>
</html>
and finally the jsp result page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Md5Checksum Result</title>
</head>
<body>
<table>
<tr>
<th colspan="2">THE RESULT OF COMPARING TWO FILE IS:</th>
</tr>
<tr><th colspan="2"></th></tr>
<tr>
<th>File1 Md5:</th>
<td>${param.file1Md5}</td>
</tr>
<tr>
<th>File2 Md5:</th>
<td>${param.file2Md5}</td>
</tr>
<tr>
<th>result</th>
<td><c:if test="${param.filesEqual}">
<span style="color: green">These two files are equal</span>
</c:if> <c:if test="${!param.filesEqual}">
<span style="color: red">These two files are not equal</span>
</c:if></td>
</tr>
<tr>
<th colspan="2"><a href="." >go back</a></th>
</tr>
</table>
</body>
</html>
for downloading the whole eclipse project you can use this link -> link
Good Luck !
I recommend you to use Commons FileUpload in servlet that processes form input. Here is sample tutorial: http://commons.apache.org/proper/commons-fileupload/using.html. Once you are done just dispatch to another jsp.
Is it sufficient for you to go further or do you need code sample?