Store and Display Image in Spring Boot - spring

I am trying to save a logo(in the project not in DB) and fetch it and display it on the JSP page For that I am saving the URL of the image in the DB but when I fetch it I am not getting the Image here is my code and screenshot of the project structure please help me here and please Let me know if this is the correct folder or I should save images somewhere else Thanks.
File Save Method
public static String storeLogoPath(MultipartFile file) {
logger.info("File AAYA HAI " + file);
String path = "";
try {
//String paths = "G:/MainWorkSpace/Picture_testing/WebContent/resources/images/"+file.getOriginalFilename();
path = "G:/MainWorkSpace/TestProjects/ecomProject/src/main/resources/static/img/storeLogo/"+file.getOriginalFilename();
File newFile = new File(path);
newFile.createNewFile();
FileOutputStream myfile = new FileOutputStream(newFile);
myfile.write(file.getBytes());
myfile.close();
logger.info("File should be saved now :: ");
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
Controller Method
#RequestMapping(value = "/storeFormshow" ,method = RequestMethod.GET)
public String addStoreForm(Model theModel) {
Stores storeObj = new Stores();
theModel.addAttribute("storeForm",storeObj);
return "Store/storeForm";
}
JSP PAGE FOR LIST
<%#include file="/WEB-INF/views/Store/StoreTemplet/Header.jsp"%>
<div class="content-wrapper">
<table class="table" id="table_id">
<thead>
<tr>
<th>Logo</th>
<th>ID</th>
<th>Store Name</th>
<th>Country</th>
<th class="text-center">Store Status</th>
</tr>
</thead>
<tbody>
<c:forEach var="store" items="${storeList}">
<tr>
<td> <img src="${store.logoURL}" width="10" height="10"> </td>
<td>${store.id}</td>
<td><a>${store.storeName}</a></td>
<td>${store.country}</td>
<td>${store.storeStatus}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<%#include file="/WEB-INF/views/Store/StoreTemplet/Footer.jsp"%>
Project Structure
The URL returned for the Images
G:/MainWorkSpace/TestProjects/ecomProject/src/main/resources/static/img/storeLogo/Screenshot_2018-07-11-21-46-48.jpg"
Application Properties
spring.mvc.view.prefix: /WEB-INF/views/
spring.mvc.view.suffix: .jsp
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

add your images to resources/static folder and then access them like below in the img tags
<img src="/images/solr.png" height="50" width="50">

public static String storeLogoPath(MultipartFile file) {
logger.info("File AAYA HAI " + file);
String path = "";
try {
path = "G:/MainWorkSpace/TestProjects/ecomProject/src/main/resources/static/img/storeLogo/"+file.getOriginalFilename();
File newFile = new File(path);
newFile.createNewFile();
FileOutputStream myfile = new FileOutputStream(newFile);
myfile.write(file.getBytes());
path ="/img/storeLogo/"+file.getOriginalFilename();
myfile.close();
logger.info("File should be saved now :: ");
} catch (Exception e) {
e.printStackTrace();
}
logger.info("Path Returned is ::: " + path);
return path;
}
I have trimmed the path from the static folder and saved it in the DB
This is not the correct way of doing it but It worked for me

<img src={`http://localhost:8080/api/employees/${employee.id}/image`} style={{'height':'50px','width':'50px'}}></img>
Use above code snippets to get image from server,
You can change url as per your machine

Related

how can i store the value of path variable and use it in my controller method?

When i launch the below url
http://localhost:8090/QuickStartConsulting/quickstart/email?key=6226f7cbe59e99a90b5cef6f94f966fd
The following controller method is invoked
#RequestMapping(value = "/quickstart/email")
public String viewQuickStartEmailForm(#ModelAttribute(value = "quickbean")
QuickStartBean quickbean,BindingResult result,Model model) {
try {
//System.out.println(quickbean.getKey());
email=quickbean.getEmail();
model.addAttribute("email", email);
model.addAttribute("quickstartdatabean",new QuickStartBean() );
} catch (Exception e) {
e.printStackTrace();
}
return "quickstart/emaillogin";
}
Here is my emaillogin jsp page
<form:form id="requestForm" method="GET" modelAttribute="quickbean" ACTION="${pageContext.request.contextPath}/quickstart/email" >
<form:hidden path="key" />
<table>
<tr>
<td><span><img src="<c:url value="/views/images/youremailid.png"/>"> </img></span></td>
<td>
<form:input type="text" style="width: 300px;" id="name" path="email" title="xyz#email.com"/>
</td></tr>
<tr>
<td>
<input type="image" id="invite_btn" src="<c:url value="/views/images/submit.png"/>" title="create invite" width="170" height="32"/>
</td>
</tr>
</table>
</form:form>
How can i store the value of path variable 'key' and use it in my controller method? the emaillogin page is the first page and is not redirected from any other jsp page.
Use the #RequestParam annotation
public String viewQuickStartEmailForm(#RequestParam("key") String key, ....) {...}
Btw: #See #RequestParam vs #PathVariable for details and difference between request params and path variables
First define pathVariables as follows:
public String viewQuickStartEmailForm(#PathVariable Map pathVariables,..)
You can get the values by using below code snippet:
if (pathVariables != null) {
if (pathVariables.containsKey("fieldName") &&
!"undefined".equals(
(String)pathVariables.get("fieldName")) &&
!"null".equals(
(String)pathVariables.get("fieldName"))) {
params.setFieldName((String)pathVariables.get("fieldName"));
}
}
There is a difference between #PathVariable and #RequestParam. For example :
#RequestParam used for accessing the values of the query parameters.
URL : http://localhost:8081/Test/card?cardId=1012111
#RequestMapping("/card")
public String getCard(#RequestParam(value="cardId", required=true) String cardId){
System.out.println("print the value of the cardId : "+cardId)
.......
}
where as #PathVariable used for accessing the values from the URI template.
URL : http://localhost:8081/Test/card/1012111
#RequestMapping("/card/{cardId}")
public String updateCard(#PathVariable(value="cardId") String cardId){
System.out.println("print the value of the cardId : "+cardId)
.......
}
So you can correct your code and use any one of the above mentioned approach rather then mixing both of them.

Retrieve image from oracle database and show image in jsp

I want to retrieve image from table named Image and column named image with type blob, but while running the code its giving the blob code like this-
"oracle.sql.BLOB#193242d"
Please see my code for fetching and show the image on jsp page/browser:-
ResultSet resultset =
statement.executeQuery("select * from image where id = '" + id + "'") ;
Browser page:-
<TABLE border="1">
<TR>
<TH>ID</TH>
<TH>picture</TH>
</TR>
<TR>
<TD> <%= resultset.getString(1) %> </TD>
<TD> <%= resultset.getBlob(2) %> </TD>
</TR>
</TABLE>
<BR>
First:
oracle.sql.BLOB#193242d is the response of toString() method, not the image.
Second:
ResultSet resultset =
statement.executeQuery("select * from image where id = '" + id + "'") ;
For sake of SQL Injection, please!
Finally
You cannot response image with text data in heart! Image must be retrieved via a separated cgi/servlet where the content type is set to image, so for your case.
<TD> <%= resultset.getString(1) %> </TD>
<TD> <img src="/get_img?id="<%=id%>/> </TD>
And later you need a servlet/cgi to respond the image as get_img
#WebServlet(name = "img", urlPatterns = {"/get_img"})
public class get_img extends HttpServlet{
doGet(HttpServletRequest req, HttpServletResponse resp){
...
resp.setContentType("image/jpg");//or image/whatever
try(ResultSet rs=ps.executeQuery()){//where ps is a PreparedStatement
//set the content length, and respond image data
//example: http://stackoverflow.com/a/4332975/5266804
}
...
}
}
You can either create a servlet to serve the images from DB, see How to retrieve images from database and place on JSP?
Or you can embed the image data directly into the src attribute of an image tag: I want to retrieve image from mysql database using servlet and show that image along with that user details in table - although this is recommendable only for small images (icons etc.).

Image in jsp through servlet

I m not able to display image on jsp page plzz help
dis is my jsp page where d image is to be inserted...`
<h4>Welcome<%=rst.getString(1)%></h4>
<table>
<tr><td>Designation:<%=rst.getString(4)%></td><td></td></tr>
<tr><td>Date of Birth:<%=rst.getString(8)%>/<%=rst.getString(7)%>/<%=rst.getString(6)%></td></tr>
<tr><td>Qualification:<%=rst.getString(9)%></td></tr>
<tr><td>Full Address:<%=rst.getString(10)%><%=rst.getString(11)%></td></tr>
<tr><td>Contact No:<%=rst.getString(12)%></td></tr
<tr><td><img src="Image1?imgid=<%=rst.getString(14)%>" width="60" height="60"></img></td></tr>
</table>
and this is my servlet
try
{
String id1=request.getParameter("imgid");
Blob image=null;
byte[]imgData=null;
Class.forName("com.mysql.jdbc.Driver");
Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/regf","root","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select image from teac where UserId='"+id1+"'");
}
if(rs.next()){
image = rs.getBlob(18);
int ln=(int) image.length();
imgData = image.getBytes(1,ln);
response.setContentType("image/jpeg");
OutputStream o = response.getOutputStream();
InputStream readImg = rs.getBinaryStream(18);
int index=readImg.read(imgData, 0,ln);
response.getOutputStream().write(imgData,0,ln);
response.getOutputStream().flush();
}
}
make sure the path "Image1?imgid=<%=rst.getString(14)%>" is correct and follow this format:
<td><img src="" alt="" border=3 height=100 width=100></img></th>.
Print this path on the console or on the page and check image exists there.

Invalid working of #springFormSingleSelect in velocity template

I am making spring mvc application and using velocity templates for views.There is form for filling it by the data and in this form i am using #springFormSingleSelect.Form works fine when data is valid, but when form is filled by invalid data as mentioned there are messages with errors, but #springFormSingleSelect is empty.That's my view:
<form action="saveEmployee" method="POST">
#springBind("newEmployee")
#springMessage("label.back")
<p>
<table>
<tr>
<td>#springMessage("label.firstName")</td>
<td>#springFormInput("newEmployee.firstName" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.lastName")</td>
<td>#springFormInput("newEmployee.lastName" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.salary")</td>
<td>#springFormInput("newEmployee.salary" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.birthdate")</td>
<td>#springFormInput("newEmployee.birthday" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.departament")</td>
<td>#springFormSingleSelect("newEmployee.departamentId" $departamentsMap "")</td>
</tr>
</table>
<input type="submit" value="#springMessage("label.submit")">
</form>
That's part of controller to the view:
#RequestMapping(value="/saveEmployee", method= RequestMethod.GET)
public ModelAndView newuserForm(){
ModelAndView model = new ModelAndView("newEmployee");
Employee empl = new Employee();
Map departamentsMap = new TreeMap();
List<Departament> departamentsList = service.listDepartaments();
//for singleselect of departaments
for(int i=0; i<departamentsList.size(); i++){
Departament dep = departamentsList.get(i);
departamentsMap.put(dep.getDepartamentId(),dep.getTitle() );
}
model.addObject("departamentsMap",departamentsMap);
model.getModelMap().put("newEmployee", empl);
return model;
}
#RequestMapping(value="/saveEmployee", method=RequestMethod.POST)
public String create(#ModelAttribute("newEmployee")Employee empl, BindingResult result){
employeeValidator.validate(empl, result);
if(result.hasErrors()){
return "newEmployee";
}
service.saveEmployee(empl);
return "redirect:/listEmployees";
}
Maybe someone knows the reason of that behavior?
departamentsMap is null at the time of Error...So please add model.addObject("departamentsMap",departamentsMap);
in your post detail ,So when eeror Occured it must not be null.
//Modified this line of code..
if(result.hasErrors()){
Map departamentsMap = new TreeMap();
List<Departament> departamentsList = service.listDepartaments();
//for singleselect of departaments
for(int i=0; i<departamentsList.size(); i++){
Departament dep = departamentsList.get(i);
departamentsMap.put(dep.getDepartamentId(),dep.getTitle() );
}
model.addObject("departamentsMap",departamentsMap);
return "newEmployee";
}

Paging with page numbers in JSP file not url

I am using spring paging framework for my form. I am testing the paging framework from here:
http://www.developer.com/java/web/article.php/10935_3830886_3/A-Pagination-Technique-Using-Spring.htm. The url for my form displays the page numbers like this:
1st page: http://...stuff../mySite/paging/paging/0
2nd page: http://...stuff../paging.do?action=list&p=1
3rd page: http://...stuff../paging.do?action=list&p=2
etc
The paging is not consistent and causes a problem in my code (note the difference btwn first pg and 2nd pg urls) and to keep my url clean, I prefer to store the page numbers as a hidden jsp parameter. Is it possible? Do you have any advice? Thanks.
My controller:
#Controller
#RequestMapping(value="/paging")
#ApplicationComponent(component="Paging")
public class PaginationController
{
private final Log logger = LogFactory.getLog(getClass());
#Autowired
private ItemDao itemDao;
#RequestMapping(value="/paging/{p}")
public ModelAndView list(#PathVariable("p") int page) throws Exception
{
ModelAndView mav = new ModelAndView("paging/paging");
System.out.println("In the paging controller");
// get data in a list from jsp
List searchResults = itemDao.getAllItems();
// initialize PagedListHolder with the list,
PagedListHolder pagedListHolder = new PagedListHolder(searchResults);
pagedListHolder.setPage(page);
int pageSize = 5;
pagedListHolder.setPageSize(pageSize);
mav.addObject("pagedListHolder", pagedListHolder);
return mav;
}
}
Here is the JSP:
<jsp:useBean id="pagedListHolder" scope="request" type="org.springframework.beans.support.PagedListHolder"/>
<%-- // create link for pages, "~" will be replaced with the proper page number --%>
<c:url value="/paging.do" var="pagedLink">
<c:param name="action" value="list"/>
<c:param name="p" value="~"/>
</c:url>
<tg:paging pagedListHolder="${pagedListHolder}" pagedLink="${pagedLink}"/>
<%-- // show only current page data --%>
<table width="200px" border="1">
<tr>
<th width="20px">No.</th>
<th>Print Items from pagedListHolder list</th>
</tr>
<c:forEach items="${pagedListHolder.pageList}" var="item">
<tr>
<td>${item.key}</td>
<td style="color:blue;font-weight:bold;text-align:right">${item.data}</td>
</tr>
</c:forEach>

Resources