mercredi 25 mars 2015

Access to HttpServletRequest and HttpServletResponse in Java Spring Service

I have an emailService implementation in ny Java Spring Boot project. To send email, I use JavaMailSender. In my service I need an access to HttpServletRequest and HttpServletResponse in order to instantiate WebContext. Now I am passing these 2 - request and response thrugh my mailsender methods what sounds like a bad idea. I would like to have them in my service so I can call methods in my mailsender with only 2 variables: what email template to use and a map of variables that will be printed on that email. Is there a way to instantiate request and response in my service? Can I somehow autowire them in the service? Thats how my service looks like:



@Service
@Qualifier("MailSender")
public class MailSenderService {

@Autowired
private JavaMailSender mailSender;

@Autowired
private ServletContextTemplateResolver emailTemplateResolver;


public boolean sendMail(HttpServletRequest request, HttpServletResponse
response, HashMap<String, String> info, String template) throws
MessagingException, IOException{

final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new
MimeMessageHelper(mimeMessage,true, "UTF-8"); // true = multipart

message.setFrom("sender@example.com");
message.setTo("mymail@example.com");
message.setSubject("This is the message subject");
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(emailTemplateResolver);
WebContext ctx = new WebContext(request, response,
request.getServletContext(), request.getLocale());

ctx.setVariable("info", info);


try{
String messageContent= engine.process(template, ctx);
mimeMessage.setContent(tt, "text/html; charset=utf-8");

}catch(Exception e){
e.printStackTrace();
}

this.mailSender.send(mimeMessage);
return true;

}
}

Aucun commentaire:

Enregistrer un commentaire