Add cid image in thymeleaf template - spring-boot

I have the following code :
Context context = getContext(transaction.getQuoteId(),transaction);
body = templateEngine.process("....html", context);
MimeMessage mail = javaMailSender.createMimeMessage();
FileSystemResource logo = new FileSystemResource(new File("/images/logo.png"));
MimeMessageHelper helper = new MimeMessageHelper(mail, true);
helper.addInline("logo", logo);
helper.setFrom(fromEmail);
helper.setTo("...);
helper.setSubject("....");
helper.setText(body, true);
javaMailSender.send(mail);
In html code I have:
<td align="center" style="line-height: 0px; text-align:start;">
<img style="display:block; line-height:0px;margin-left: 30px;" src="cid:${logo}" width="200" alt="logo">
</td>
I also tried using th:src="'cid:logo'" but it didn't work. When I receive an email the image in not rendered.
The image resides inside :
src/main/resources/images/logo.png
I also allowed access to "/images/.., /resources/.." in HttpSecurity ant matchers.

Related

Store and Display Image in Spring Boot

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

Session or Cookies in login page = master page = child page

I' creating a multilanguage website and I have some files :
login page.
master page.
child page using master page.
In login page, I used link control for choose language by user :
<table class="borderlang" style="position: absolute; top: 5px; left: 5px; width: auto; height: auto;">
<tr>
<td style="vertical-align: middle;">
<asp:Label ID="Label1" runat="server" Text="Language :" meta:resourcekey="Label1Resource1"></asp:Label>
</td>
<td>
<a href="?lang=vi" runat="server" id="linkVietnameseLang">
<img src="Content/Images/VNlogo.jpg" style="height: 20px; width: auto; padding-left: 10px;" /></a>
</td>
<td>
<a href="?lang=en" runat="server" id="linkEnglishLang">
<img src="Content/Images/USALogo.png" style="height: 20px; width: auto; padding-left: 10px;" /></a>
</td>
</tr>
</table>
I use BasePage.cs with code :
public class BasePage : System.Web.UI.Page
{
protected override void InitializeCulture()
{
if (!string.IsNullOrEmpty(Request["lang"]))
{
Session["lang"] = Request["lang"];
}
string lang = Convert.ToString(Session["lang"]);
string culture = string.Empty;
if (lang.ToLower().CompareTo("en") == 0)
{
culture = "en-US";
}
if (lang.ToLower().CompareTo("vi") == 0 || string.IsNullOrEmpty(culture))
{
culture = "vi-VN";
}
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
base.InitializeCulture();
}
}
So in login page I use :
public partial class Login : BasePage
To use BasePage.
In this form have some items that I can't use local resource, so I used 2 resources : global resource and local resource. But I don't care because when I choose language in link -> language change and global and local resource are changed, too.
Now, when I login, website will redirect to a page using master page. In master page I put a dropdown for user in case they wanna change language again :
<asp:DropDownList ID="ddlLanguage" runat="server"
OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged"
AutoPostBack="True" meta:resourcekey="ddlLanguageResource1">
<asp:ListItem Text="Tiếng ViệT" Value="vi-VN" meta:resourcekey="ListItemResource1" />
<asp:ListItem Text="EnglisH" Value="en-US" meta:resourcekey="ListItemResource2" />
</asp:DropDownList>
And in master page I add :
if (!Page.IsPostBack)
{
ddlLanguage.SelectedValue = Thread.CurrentThread.CurrentCulture.Name;
}
and :
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlLanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload the page for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture =
new CultureInfo(ddlLanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture =
new CultureInfo(ddlLanguage.SelectedValue);
Server.Transfer(Request.Path);
}
In global.asax is :
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cookie.Value);
Thread.CurrentThread.CurrentCulture = new CultureInfo(cookie.Value);
}
else
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("vi-VN");
Thread.CurrentThread.CurrentCulture = new CultureInfo("vi-VN");
}
}
Question 1 : How can I use session or cookies of link value (in login page) to master page : ddlanguage value = session or cookies of lang ??
Now, in child page using master page. I must use local resource because if use global resource I must use <%$ Resources:nameresource, keysource%> -> too slow.
And I have a problem : in child page with local resoure, culture and uiculture value is not depending on ddlanguage value in master page.
Question 2 : How can I set culture and uiculture value in child page = ddlanguage value in master page.
And result is : lang value in login page = ddlanguage dropdown value in master page = culture and uiculture in child page using that masterpage. But can change ddlanguage value in masterpage and cultureanduiculture in child page will change, too.
.
I'm an amateur in coding, so I hope have solution in my case.
Thank very very much (and sorry for my English).
In program.cs
user name can set Globals variable
namespace GlobalVariables
{
public static class Globals
{
static Globals()
{
userName="";
}
public static void setusername(int[] newInt)
{
setusername = newInt;
}
public static string userName { get; private set; }
}
you can set or get every child or parent form
inherit namespace like in another child or parent form
using GlobalVariables;
to set Globals session or cookiee
Globals.setusername(userName.ToString()));
you can check and restrict page
username=Globals.userName;
Response.Cookies("userInfo")("userName") = "rangarajakrishnan"
Response.Cookies("userInfo")("lastVisit") = DateTime.Now.ToString
Response.Cookies("userInfo").Expires = DateTime.Now.AddDays(1)
Dim aCookie As New HttpCookie("userInfo")
aCookie.Values("userName") = "mike"
aCookie.Values("lastVisit") = DateTime.Now.ToString
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)

Accessing images from remote or external resource in jsp

I am trying to implement a web page where images location is outside my web application.
I will iterate through the images folder and then load the images in jsp.
But when i do it everything works fine but images are not displaying.
I found the reason too, its prepends application context to image location.
For example if my image location is "d:/images", when the img src is resolves, the path becomes http: // hostname //portnumber/exampled/d:/images/image1.gif
Following is my code.
Service class:
public List<String> getSiteKeyImages(){
List<String> imageList = new ArrayList<String>();
File directory = new File(PropertyFileReader.getNycbMessage().getProperty("imageURL"));
if(directory.isDirectory()){
String[] images = directory.list();
for(String image:images){
imageList.add(image);
}
}
return imageList;
}
servlet class:
private List<String> images = new ArrayList<String>();
images = userService.getSiteKeyImages();
session.setAttribute("images",images);
Then my jsp page code is
<div id = "pamImages">
<ul class="thumbs noscript">
<c:forEach items="${images}" var="image">
<li>
<a id="${image}" class="thumb" name="leaf" href="javascript: selected_image('${image}')">
<img src="${CONFIG_URL}${image}" height="50" width="50"></td>
</a>
</li>
</c:forEach>
</ul>
</div>
Ca anyone tell me what wrong i am doing here.

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.

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