-
30 Mar 2012 4:25 AM #1
Answered: Mail function using springmvc and extjs
Answered: Mail function using springmvc and extjs
I am working on a mail application using springMVC and hibernate.
I have used the MailService for sending the email.But,I get the following error
Debug log for mail
This seems fine and the mails are sent properly as required.Code:DEBUG: JavaMail version 1.4ea DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre6\lib\javamail.providers (The system cannot find the file specified) DEBUG: !anyLoaded DEBUG: not loading resource: /META-INF/javamail.providers DEBUG: successfully loaded resource: /META-INF/javamail.default.providers DEBUG: Tables of loaded providers DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]} DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]} DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map DEBUG: !anyLoaded DEBUG: not loading resource: /META-INF/javamail.address.map DEBUG: java.io.FileNotFoundException: C:\Program Files\Java\jre6\lib\javamail.address.map (The system cannot find the file specified) DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false 220 mx.google.com ESMTP u5sm4666866pbu.76 DEBUG SMTP: connected to host "smtp.gmail.com", port: 587 EHLO office-l58g7rse 250-mx.google.com at your service, [122.169.38.83] 250-SIZE 35882577 250-8BITMIME 250-STARTTLS 250 ENHANCEDSTATUSCODES DEBUG SMTP: Found extension "SIZE", arg "35882577" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "STARTTLS", arg "" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" STARTTLS 220 2.0.0 Ready to start TLS EHLO office-l58g7rse 250-mx.google.com at your service, [122.169.38.83] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH 250 ENHANCEDSTATUSCODES DEBUG SMTP: Found extension "SIZE", arg "35882577" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Attempt to authenticate AUTH LOGIN 334 VXNlcm5hbWU6 c2FjaGl0YXdhcmUyMQ== 334 UGFzc3dvcmQ6 MjExMDg4c2FjaGlu 235 2.7.0 Accepted DEBUG SMTP: use8bit false MAIL FROM:<sachitaware21@gmail.com> 250 2.1.0 OK u5sm4666866pbu.76 RCPT TO:<sachitaware21@gmail.com> 250 2.1.5 OK u5sm4666866pbu.76 DEBUG SMTP: Verified Addresses DEBUG SMTP: sachitaware21@gmail.com DATA 354 Go ahead u5sm4666866pbu.76 Date: Thu, 29 Mar 2012 15:27:19 +0530 (IST) From: sachitaware21@gmail.com To: sachitaware21@gmail.com Message-ID: <19097634.01333015039154.JavaMail.Administrator@office-l58g7rse> Subject: TEst MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Test@@@@EEEEEWWWWdssfdg . 250 2.0.0 OK 1333015042 u5sm4666866pbu.76 QUIT 221 2.0.0 closing connection u5sm4666866pbu.76 DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false 220 mx.google.com ESMTP j3sm4689853pbb.29 DEBUG SMTP: connected to host "smtp.gmail.com", port: 587 EHLO office-l58g7rse 250-mx.google.com at your service, [122.169.38.83] 250-SIZE 35882577 250-8BITMIME 250-STARTTLS 250 ENHANCEDSTATUSCODES DEBUG SMTP: Found extension "SIZE", arg "35882577" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "STARTTLS", arg "" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" STARTTLS 220 2.0.0 Ready to start TLS EHLO office-l58g7rse 250-mx.google.com at your service, [122.169.38.83] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH 250 ENHANCEDSTATUSCODES DEBUG SMTP: Found extension "SIZE", arg "35882577" DEBUG SMTP: Found extension "8BITMIME", arg "" DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH" DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg "" DEBUG SMTP: Attempt to authenticate AUTH LOGIN 334 VXNlcm5hbWU6 c2FjaGl0YXdhcmUyMQ== 334 UGFzc3dvcmQ6 MjExMDg4c2FjaGlu 235 2.7.0 Accepted DEBUG SMTP: use8bit false MAIL FROM:<sachitaware21@gmail.com> 250 2.1.0 OK j3sm4689853pbb.29 RCPT TO:<sachitaware21@gmail.com> 250 2.1.5 OK j3sm4689853pbb.29 DEBUG SMTP: Verified Addresses DEBUG SMTP: sachitaware21@gmail.com DATA 354 Go ahead j3sm4689853pbb.29 Date: Thu, 29 Mar 2012 15:27:24 +0530 (IST) From: sachitaware21@gmail.com To: sachitaware21@gmail.com Message-ID: <21565491.11333015044853.JavaMail.Administrator@office-l58g7rse> Subject: Alert - Exception occurred MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Exception occurred . 250 2.0.0 OK 1333015048 j3sm4689853pbb.29 QUIT 221 2.0.0 closing connection j3sm4689853pbb.
Here,is the error in firebug and due to this I don't get a success message of the mail delivery.
In firebug console I get an error like this under the response tab.
and this under XML tabCode:uncaught exception: [Exception... "'You're trying to decode an invalid JSON String: ' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001c (NS_ERROR_XPC_JS_THREW_JS_OBJECT)" location: "JS frame :: resource://firebug_rjs/net/spy.js :: callPageHandler :: line 798" data: no]`
But,I checked the returned Json and it is in the correct format.And it is returned before the mail function is even called.Code:XML Parsing Error: no element found Location: moz-nullprincipal:{564d3946-b1b0-48d4-8791-8a5ea8069a85} Line Number 1, Column 1: ^
This is my config file for spring bean
Can someone guide me through this??Code:<!--*************************** E-Mail bean******************************--> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com"/> <property name="port" value="587"/> <property name="username" value="sachitaware21"/> <property name="password" value="mypass"/> <property name="javaMailProperties"> <props> <!-- Use SMTP transport protocol --> <prop key="mail.transport.protocol">smtp</prop> <!-- Use SMTP-AUTH to authenticate to SMTP server --> <prop key="mail.smtp.auth">true</prop> <!-- Use TLS to encrypt communication with SMTP server --> <prop key="mail.smtp.starttls.enable">true</prop> <prop key="mail.debug">true</prop> </props> </property> </bean> <bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage"> <property name="from"> <value>sachitaware21@gmail.com</value> </property> <property name="to"> <value>sachitaware21@gmail.com</value> </property> <property name="subject" value="Alert - Exception occurred"/> </bean>
Thanks
Sachin
S/W Engg
www.optionsconsultancy.com
-
Best Answer Posted by friend
I noticed that the PHP error message you posted shows the file name as applicationContect.xml instead of applicationContext.xml. That may be the problem. Also, I kinda confused about the use of PHP when you have a Java Web container on the backend.
Regardless, as for file paths, Spring uses root-relative paths in its config files. Note that I never load the application context manually. I let the web container do all the work by specifying everything in Tomcat's web.xml.
Below is a pared-down example of my web.xml which loads the application and servlet context configs for me, where I also have a Spring Security config in there. Note that I'm old-school/retarded and like '.action' on the end of my URL mappings. A more modern approach would be to place all of your MVC-related URL mappings into an 'mvc' context instead:
For thoroughness, here's my applicationContext.xml as well, noting that I break everything out into separate XML files for compartmentalization/ease of reading:Code:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>MyApp</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/application-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>myapp</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myapp-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Any request which ends with ".action" gets serviced. --> <servlet-mapping> <servlet-name>myapp</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- The client app uses a 15 minute session timeout, where a 2 minute slop factor is added here. --> <session-config> <session-timeout>17</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
The included application-data.xml:Code:<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="com.stinkypete.myapp" /> <!-- <aop:aspectj-autoproxy /> --> <import resource="application-data.xml" /> <import resource="application-security.xml" /> <import resource="application-utility.xml" /> </beans>
My application-security.xml config, noting that I use a SALT Source for password hashing/comparison:Code:<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> <!-- DataSource configured in Tomcats conf/context.xml and referenced as a JNDI object. --> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/myapp" /> </bean> <!-- For those times when you just want to do simple SQL and get a Map of name/value pairs. --> <bean id="npjt" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" autowire-candidate="true"> <constructor-arg ref="dataSource"></constructor-arg> </bean> <!-- Hibernate SessionFactory instance, which allows you to get at the current Session. --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- Instructs Spring to scan only the target package for Domain Entities. --> <property name="packagesToScan" value="com.stinkypete.myapp.domain"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!-- Set show_sql to true if you want to see Hibernate's SQL on the Eclipse console. --> <prop key="hibernate.show_sql">false</prop> <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> --> </props> </property> </bean> <!-- Let the transaction manager know how to get a Session. --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Enable Transactions via annotations. --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
And lastly, my application-utility.xml stuff:Code:<?xml version="1.0" encoding="UTF-8"?> <b:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:b="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/security" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- ============================================================================ == SPRING SECURITY CONFIGURATION ========================================== ============================================================================ Encapsulates all Spring Security Configuration. All security settings are mananged here, including role-based user access by URL pattern and authentication mechanism configuration. ============================================================================ --> <!-- ============================================================================ == GLOBAL SECURITY CONFIG ================================================== ============================================================================ The <global-method-security> tag enables the ability to annotate individual Controller methods for security, like: @RolesAllowed("ROLE_ADMIN") @RolesAllowed({"ROLE_USER", "ROLE_GUEST"}) @PemitAll @DenyAll ============================================================================ --> <global-method-security jsr250-annotations="enabled" /> <!-- ============================================================================ == HTTP CONFIG ============================================================= ============================================================================ In the <http> tag below, the 'use-expressions="true"' attribute allows you to use complex boolean expressions when configuring the 'access' attributes of <intercept-url> tags, e.g.: access="hasRole('ROLE_ADMIN') and hasIpAddress('192.168.1.0/24')" Visit http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html for details. ============================================================================ --> <http auto-config="false" use-expressions="true"> <form-login login-page="/loadLogin.action" default-target-url='/home.action' always-use-default-target="true"/> <logout logout-url="/logout" logout-success-url="/loadLogin.action" invalidate-session="true" /> <session-management session-authentication-error-url="/loadLogin.action"> <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" /> </session-management> <!-- No security filters on public resources. --> <intercept-url pattern="/loadLogin.action" access="permitAll" /> <intercept-url pattern="/forgotPword.action" access="permitAll" /> <intercept-url pattern="/requestPword.action" access="permitAll" /> <intercept-url pattern="/index.html" access="permitAll" /> <intercept-url pattern="/app.js" access="permitAll" /> <intercept-url pattern="/app/**" access="permitAll" /> <intercept-url pattern="/extjs/**" access="permitAll" /> <intercept-url pattern="/resources/**" access="permitAll" /> <intercept-url pattern="/**" access="isAuthenticated()" /> </http> <b:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource"> <b:property name="userPropertyToUse" value="salt" /> </b:bean> <b:bean id="hibernateUserService" class="com.stinkypete.myapp.security.MyUserService" /> <authentication-manager> <authentication-provider user-service-ref="hibernateUserService"> <password-encoder hash="md5"> <salt-source ref="saltSource"/> </password-encoder> </authentication-provider> </authentication-manager> </b:beans>
And the overall project layout:Code:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- =========================================================================== == APPLICATION UTILITY == == General/utility beans, properties files, etc. == =========================================================================== ============================================================================ == JAVA MAIL USING SECURE SMTP ============================================= ============================================================================ Here a more complex example of using Secure SMTP to send email via a foreign mail host (Gmail, in this case). ============================================================================ --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com" /> <property name="port" value="465" /> <property name="protocol" value="smtps" /> <property name="username" value="yourGmailAccountName@gmail.com" /> <property name="password" value="yourpassword" /> <property name="javaMailProperties"> <props> <prop key="mail.smtps.auth">true</prop> <prop key="mail.smtps.starttls.enable">true</prop> <prop key="mail.smtps.debug">true</prop> </props> </property> </bean> --> <!-- ============================================================================= == File Upload Multipart Resolver =========================================== ============================================================================= If your application has need to upload files, Spring's CommonsMultipartResolver bean will allow you to control the maximum upload size, set default encoding, etc. In this example, a maximum file size of 10Meg (specified in bytes) can be uploaded. ============================================================================= --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> </bean> <!-- ============================================================================= == Global Properties File =================================================== ============================================================================= If your application requires any configuration properties, you can load the Properties files from the classpath, as a named bean. You can then inject the bean into any classes which need access to the properties. In this example, global.properties is placed in the root of the /src folder. If you need to dynamically insert properties into your application's context config at startup, visit the documentation for PropertyPlaceholderConfigurer. ============================================================================= --> <bean id="globalProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:global.properties"/> </bean> </beans>
Attachment 35248
-
30 Mar 2012 9:42 AM #2Sencha - Senior Forum Manager
- Join Date
- Mar 2007
- Location
- St. Louis, MO
- Posts
- 33,684
- Vote Rating
- 435
- Answers
- 3111
It's saying the JSON is invalid. Have you made sure it's valid JSON?
Mitchell Simoens @SenchaMitch
Sencha Inc, Senior Forum Manager
________________
http://www.JSONPLint.com - Source to lint your JSONP!
Check out my GitHub, lots of nice things for Ext JS 4 and Sencha Touch 2
https://github.com/mitchellsimoens
Think my support is good? Get more personalized support via a support subscription. https://www.sencha.com/store/
Need more help with your app? Hire Sencha Services services@sencha.com
Want to learn Sencha Touch 2? Check out Sencha Touch in Action that is almost in print!
When posting code, please use BBCode's CODE tags.
-
30 Mar 2012 11:05 AM #3
Yes the JSON is very much valid.Infact it is returned even before I go to the email function.(I use store content already fetched for sending mails).So,the JSON is returned before this.Also,when I check it in CHROME browser,no such error is generated and I get a Mail success message
. Mozilla FF gives this error and gets stuck on the progress bar once I submit the mail form.
Thanks
Sachin
S/W Engg
www.optionsconsultancy.com
-
1 Apr 2012 9:45 PM #4
@mitchellsimoens
This is what I get under the XML tab in firebug,tried to google and learnt that response may be a problem.I have added the js that throws the error with line number.Please guide me over this.
Code:XML Parsing Error: no element found Location: moz-nullprincipal:{564d3946-b1b0-48d4-8791-8a5ea8069a85} Line Number 1, Column 1:This is what I return on success and failure.Works fine in Chrome but not in FFCode:originalHandler.handleEvent(event); spy.js (line 798)
Code:var f = Ext.getCmp('sendEmailForm'); f.form.submit({ reset: true, url:'email/view.action', method:'Post', waitMsg:'Sending Email...', success:function(form,action){ Ext.Msg.alert('Status', 'Mail has been sent Successfully!!', function(btn, text){ if (btn == 'ok'){ // var redirect = 'success.html'; // window.location = redirect; } }); }, failure:function(form, action){ if(action.failureType == 'server'){ obj = Ext.util.JSON.decode(action.response.responseText); Ext.Msg.alert('Login Failed!', obj.errors.reason); //Ext.Msg.alert('Login Failed!'); } else{ Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText); } } });
-
12 Apr 2012 4:35 AM #5
@mitchellsimoens
I am still stuck with the issue.Can you please suggest any clue?
Thanks
Sach
-
14 May 2012 5:36 AM #6
So you have something to compare against, here's my Spring bean config for the JavaMailSender:
And here's my Controller method which constructs/sends email, noting that I go overboard on input parameter checking, in case a user tries hacking around with the request parameters. Note that I'm using the Jackson JSON Mapping view support in Spring 3.1, hence the return type annotation of @ResponseBody where Spring auto-magically handles the content type and JSON conversion:Code:<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com" /> <property name="port" value="465" /> <property name="protocol" value="smtps" /> <property name="username" value="yourGmailAccountName@gmail.com" /> <property name="password" value="yourpassword" /> <property name="javaMailProperties"> <props> <prop key="mail.smtps.auth">true</prop> <prop key="mail.smtps.starttls.enable">true</prop> <prop key="mail.smtps.debug">true</prop> </props> </property> </bean>
This code is currently used in a production app and works well.Code:@RolesAllowed({Utility.ROLE_ADMIN,Utility.ROLE_EMAIL_USERS}) @RequestMapping("/user/emailSubmit") public @ResponseBody Map<String,Object> emailSubmit(Authentication auth, @RequestParam("from") String from, @RequestParam("to") String to, @RequestParam("subject") String subject, @RequestParam("message") String message) { // simple utility method which constructs a new Map and adds // a default "success"/true key/value pair. Map<String,Object> results = Utility.getJsonResultMap(); if (from == null || from.isEmpty()) { results.put("success", false); results.put("title", "Error"); results.put("msg", "Please enter a 'From' email address."); } else if (!Utility.isValidEmailAddress(from)) { results.put("success", false); results.put("title", "Error"); results.put("msg", "Invalid 'From' email address."); } else if (to == null || to.isEmpty()) { results.put("success", false); results.put("title", "Error"); results.put("msg", "Please enter one or more 'To' email addresses."); } else if (subject == null || subject.isEmpty()) { results.put("success", false); results.put("title", "Error"); results.put("msg", "Please enter a 'Subject' for your email."); } else if (message == null || message.isEmpty()){ results.put("success", false); results.put("title", "Error"); results.put("msg", "Please enter a message for the body of your email."); } else { MimeMessage mailMessage = this.mailSender.createMimeMessage(); MimeMessageHelper helper = null; try { helper = new MimeMessageHelper(mailMessage, true); String[] recipients = to.split(","); for (String address : recipients) { if (!Utility.isValidEmailAddress(address)) { results.put("success", false); results.put("title", "Error"); results.put("msg", "Email '" + address + "' in the list of recipients doesn't appear to be valid."); return results; } helper.setTo(address.trim()); } helper.setFrom(from); helper.setSubject(subject); helper.setSentDate(new Date()); helper.setText(message, true); this.mailSender.send(mailMessage); results.put("msg", "Email sent successfully."); results.put("title", "Email Sent"); } catch (Exception e) { logger.error("Error sending user email: " + e); results.put("success", false); results.put("title", "Error sending email"); results.put("msg", "An error occurred while attempting to send your email. Please contact Tech Support."); } } return results; }
-
14 May 2012 8:58 PM #7
Thanks @friend
I have problem with applicationContext.xml for bean definition in my project.
I have to give the absolute path here(on my machine) and in production for it to work i have to give a relative one.Code:ApplicationContext context = new FileSystemXmlApplicationContext("C:/Documents and Settings/Administrator/workspace/StaffingApplication/WebContent/WEB-INF/applicationContext.xml");
When I try to give a relative path I get an error
For example this one doesn't work.So the path has to be given relative to .java files or .class files in the classes folder.(Confused a bit)Code:File not found exception:Cannot find applicationContext.xml at given path.

I tried to read about it and went through examples,but I am not able to resolve it.(Learnt that FileSystemXmlApplicationContext requires the entire path )Code:ApplicationContext context = new FileSystemXmlApplicationContext("WEB-INF/applicationContext.xml");
This is the navigation view of my app.How can I resolve this issue.Please throw some light on it.
NavigatorView.JPG
Thanks
-
15 May 2012 4:21 AM #8
I noticed that the PHP error message you posted shows the file name as applicationContect.xml instead of applicationContext.xml. That may be the problem. Also, I kinda confused about the use of PHP when you have a Java Web container on the backend.
Regardless, as for file paths, Spring uses root-relative paths in its config files. Note that I never load the application context manually. I let the web container do all the work by specifying everything in Tomcat's web.xml.
Below is a pared-down example of my web.xml which loads the application and servlet context configs for me, where I also have a Spring Security config in there. Note that I'm old-school/retarded and like '.action' on the end of my URL mappings. A more modern approach would be to place all of your MVC-related URL mappings into an 'mvc' context instead:
For thoroughness, here's my applicationContext.xml as well, noting that I break everything out into separate XML files for compartmentalization/ease of reading:Code:<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>MyApp</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/application-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>myapp</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/myapp-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Any request which ends with ".action" gets serviced. --> <servlet-mapping> <servlet-name>myapp</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- The client app uses a 15 minute session timeout, where a 2 minute slop factor is added here. --> <session-config> <session-timeout>17</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
The included application-data.xml:Code:<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> <mvc:annotation-driven/> <context:component-scan base-package="com.stinkypete.myapp" /> <!-- <aop:aspectj-autoproxy /> --> <import resource="application-data.xml" /> <import resource="application-security.xml" /> <import resource="application-utility.xml" /> </beans>
My application-security.xml config, noting that I use a SALT Source for password hashing/comparison:Code:<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"> <!-- DataSource configured in Tomcats conf/context.xml and referenced as a JNDI object. --> <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="java:comp/env/jdbc/myapp" /> </bean> <!-- For those times when you just want to do simple SQL and get a Map of name/value pairs. --> <bean id="npjt" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" autowire-candidate="true"> <constructor-arg ref="dataSource"></constructor-arg> </bean> <!-- Hibernate SessionFactory instance, which allows you to get at the current Session. --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- Instructs Spring to scan only the target package for Domain Entities. --> <property name="packagesToScan" value="com.stinkypete.myapp.domain"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <!-- Set show_sql to true if you want to see Hibernate's SQL on the Eclipse console. --> <prop key="hibernate.show_sql">false</prop> <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> --> </props> </property> </bean> <!-- Let the transaction manager know how to get a Session. --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- Enable Transactions via annotations. --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
And lastly, my application-utility.xml stuff:Code:<?xml version="1.0" encoding="UTF-8"?> <b:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:b="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/security" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd"> <!-- ============================================================================ == SPRING SECURITY CONFIGURATION ========================================== ============================================================================ Encapsulates all Spring Security Configuration. All security settings are mananged here, including role-based user access by URL pattern and authentication mechanism configuration. ============================================================================ --> <!-- ============================================================================ == GLOBAL SECURITY CONFIG ================================================== ============================================================================ The <global-method-security> tag enables the ability to annotate individual Controller methods for security, like: @RolesAllowed("ROLE_ADMIN") @RolesAllowed({"ROLE_USER", "ROLE_GUEST"}) @PemitAll @DenyAll ============================================================================ --> <global-method-security jsr250-annotations="enabled" /> <!-- ============================================================================ == HTTP CONFIG ============================================================= ============================================================================ In the <http> tag below, the 'use-expressions="true"' attribute allows you to use complex boolean expressions when configuring the 'access' attributes of <intercept-url> tags, e.g.: access="hasRole('ROLE_ADMIN') and hasIpAddress('192.168.1.0/24')" Visit http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html for details. ============================================================================ --> <http auto-config="false" use-expressions="true"> <form-login login-page="/loadLogin.action" default-target-url='/home.action' always-use-default-target="true"/> <logout logout-url="/logout" logout-success-url="/loadLogin.action" invalidate-session="true" /> <session-management session-authentication-error-url="/loadLogin.action"> <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" /> </session-management> <!-- No security filters on public resources. --> <intercept-url pattern="/loadLogin.action" access="permitAll" /> <intercept-url pattern="/forgotPword.action" access="permitAll" /> <intercept-url pattern="/requestPword.action" access="permitAll" /> <intercept-url pattern="/index.html" access="permitAll" /> <intercept-url pattern="/app.js" access="permitAll" /> <intercept-url pattern="/app/**" access="permitAll" /> <intercept-url pattern="/extjs/**" access="permitAll" /> <intercept-url pattern="/resources/**" access="permitAll" /> <intercept-url pattern="/**" access="isAuthenticated()" /> </http> <b:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource"> <b:property name="userPropertyToUse" value="salt" /> </b:bean> <b:bean id="hibernateUserService" class="com.stinkypete.myapp.security.MyUserService" /> <authentication-manager> <authentication-provider user-service-ref="hibernateUserService"> <password-encoder hash="md5"> <salt-source ref="saltSource"/> </password-encoder> </authentication-provider> </authentication-manager> </b:beans>
And the overall project layout:Code:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <!-- =========================================================================== == APPLICATION UTILITY == == General/utility beans, properties files, etc. == =========================================================================== ============================================================================ == JAVA MAIL USING SECURE SMTP ============================================= ============================================================================ Here a more complex example of using Secure SMTP to send email via a foreign mail host (Gmail, in this case). ============================================================================ --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.gmail.com" /> <property name="port" value="465" /> <property name="protocol" value="smtps" /> <property name="username" value="yourGmailAccountName@gmail.com" /> <property name="password" value="yourpassword" /> <property name="javaMailProperties"> <props> <prop key="mail.smtps.auth">true</prop> <prop key="mail.smtps.starttls.enable">true</prop> <prop key="mail.smtps.debug">true</prop> </props> </property> </bean> --> <!-- ============================================================================= == File Upload Multipart Resolver =========================================== ============================================================================= If your application has need to upload files, Spring's CommonsMultipartResolver bean will allow you to control the maximum upload size, set default encoding, etc. In this example, a maximum file size of 10Meg (specified in bytes) can be uploaded. ============================================================================= --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> </bean> <!-- ============================================================================= == Global Properties File =================================================== ============================================================================= If your application requires any configuration properties, you can load the Properties files from the classpath, as a named bean. You can then inject the bean into any classes which need access to the properties. In this example, global.properties is placed in the root of the /src folder. If you need to dynamically insert properties into your application's context config at startup, visit the documentation for PropertyPlaceholderConfigurer. ============================================================================= --> <bean id="globalProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:global.properties"/> </bean> </beans>
appLayout.png
-
15 May 2012 5:11 AM #9
@friend
Thanks for the inputs,will go through for sure.
That was a typo(applicationContext it is as in the layout image.)!!!
Also,I changed the tag mistakenly to PHP and did not notice.When you said I realised that's why they are showing up in colors.
Will edit the question.
This is the exact error
Code:SEVERE: Servlet.service() for servlet [StaffingApplication] in context with path [/StaffingApplication] threw exception [Request processing failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [C:\Documents and Settings\Administrator\workspace\StaffingApplication\WebContent\WEB-INF\applicationContext.xml]; nested exception is java.io.FileNotFoundException: C:\Documents and Settings\Administrator\workspace\StaffingApplication\WebContent\WEB-INF\applicationContext.xml (The system cannot find the path specified)] with root cause java.io.FileNotFoundException: C:\Documents and Settings\Administrator\workspace\StaffingApplication\WebContent\WEB-INF\applicationContext.xml (The system cannot find the path specified)
Thanks
-
15 May 2012 5:35 AM #10
I think the root cause of your problem is attempting to manually load the application context. Is there a reason you need to do so?


Reply With Quote