The implementation function is that users can browse an image locally (for the sake of simplicity, they must make a local test). This is because hibernate inserts an image into the database and displays the image on another page.
Index. jsp
<Body>
<Form name = "frm" Action = "imgservlet" method = "Post">
<Input type = "file" name = "path"/>
<Input type = "Submit" value = "Submit">
</Form>
</Body>
A simple form is used to browse images.
IMG. Java
Public class IMG implements java. Io. serializable {
// Fields
Private integer ID;
Private byte [] IMG;
......
}
IMG. HBM. xml
<Hibernate-mapping>
<Class name = "HIB. IMG" table = "IMG" schema = "DBO">
<ID name = "ID" type = "Java. Lang. Integer">
<Column name = "ID"/>
<Generator class = "Identity"/>
</ID>
<Property name = "IMG" type = "binary">
<Column name = "IMG" not-null = "true"/>
</Property>
</Class>
</Hibernate-mapping>
Servlet processing method (<URL-pattern>/Imgservlet</Url-pattern> Configure the servlet)
Public void dopostt (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype ("text/html ");
// Printwriter out2 = response. getwriter ();
// The out object in the servlet can be used only once.
// If binary data is to be used and output, the outputstream object must be used.
Outputstream out = response. getoutputstream ();
Request. setcharacterencoding ("UTF-8 ");
String Path = request. getparameter ("path ");
Java. Io. File file = new file (PATH );
Inputstream = new fileinputstream (File );
Byte [] buff = new byte [(INT) file. Length ()];
Inputstream. Read (buff, 0, (INT) file. Length ());
IMG = new IMG ();
IMG. setimg (buff );
Session session = hibernatesessionfactory. getsession ();
Session. Save (IMG );
Session. begintransaction (). Commit ();
String realpath = request. getsession (). getservletcontext (). getrealpath ("/");
System. Out. println ("realpath" + realpath );
System. Out. println ("Path:" + path );
System. Out. println ("inserted successfully !!! ");
Try {
// Write the image to the output stream
Out. Write (IMG. getimg ());
} Catch (exception e ){
E. printstacktrace ();
}
// Request. getrequestdispatcher ("show. jsp"). Forward (request, response );
Response. sendredirect ("show. jsp ");
Out. Flush ();
Out. Close ();
}
Show. jsp
<Body>
</Body>
After submitting the image, you can view the image submitted by the user in show. jsp and save it to the database.