이 장에서는 Struts2의 응용 프로그램을 사용하여 이메일을 보내는 방법을 알려줍니다. 이 연습의 경우 Javamail API 1.4.4에서 Mail.jar를 다운로드하여 설치하고 Web-Inflib 폴더에 Mail.jar 파일을 배치 한 다음 표준 단계를 따라 작업,보기 및 구성 파일을 작성하십시오.
행동 만들기 :
다음 단계는 액션 방법을 만들고 이메일을 보내는 것입니다. 다음 내용으로 emailer.java라는 새 클래스를 만들어 봅시다.
패키지 com.yiibai.struts2; import java.util.properties; import javax.mail.message; import javax.mail.passwordauthentication; import javax.mail.session; import javax.mail.transport; import javax.mail.mail.internetet.internetAddress; javax.mail.mail com.opensymphony.xwork2.actionSupport; public class emailer 확장 ActionSupport {private String from; 개인 문자열 비밀번호; 개인 문자열; 개인 문자열 주제; 개인 문자열 본체; 정적 특성 속성 = 새로운 속성 (); static {properties.put ( "mail.smtp.host", "smtp.gmail.com"); properties.put ( "mail.smtp.socketfactory.port", "465"); properties.put ( "mail.smtp.socketfactory.class", "javax.net.ssl.sslsocketfactory"); properties.put ( "mail.smtp.auth", "true"); properties.put ( "mail.smtp.port", "465"); } public String execute () {String ret = success; try {session session = session.getDefaultInstance (속성, new javax.mail.authenticator () {보호 된 passwordauthentication getPasswordAuthentication () {새 passwordAuthentication (from,}}); 메시지 메시지 = 새로운 mimemessage (세션); message.setfrom (new InternetAddress (from)); message.setRecipients (message.recipienttype.to, internetAddress.parse (to)); message.setsubject (주제); message.settext (body); 송신 .send (메시지); } catch (예외 e) {ret = error; e.printstacktrace (); } return ret; } public String getFrom () {return from; } public void setfrom (문자열) {this.from = from; } public String getPassword () {return password; } public void setpassword (문자열 비밀번호) {this.password = password; } public String getTo () {return to; } public void setto (string to) {this.to = to; } public string getSubject () {return subject; } public void setSubject (문자열 주제) {this.subject = subject; } public String getBody () {return body; } public void setbody (String body) {this.body = body; } public static 속성 getProperties () {return 속성; } public static void setProperties (속성 속성) {emailer.properties = 속성; }}위의 소스 코드에서 emailer.java는 아래 양식에 주어진 email.jsp 페이지의 해당 속성을 가지고 있음을 알 수 있습니다. 이 속성
위의 각 속성에 대한 검증을 고려했으며 다음 장에 검증이 추가됩니다. 이제 execute () 메소드를 살펴 보겠습니다. execute () 메소드는 Javax 메일 라이브러리를 사용하여 제공된 매개 변수를 사용하여 이메일을 보냅니다. 메시지가 전송되면 작업이 성공을 반환하고 그렇지 않으면 오류가 반환됩니다.
홈페이지 만들기 :
위에서 언급 한대로 이메일에 대한 정보를 수집하는 데 사용되는 홈페이지 index.jsp의 JSP 파일을 작성해 봅시다.
<%@ page language = "java"contmenttype = "text/html; charset = iso-8859-1"pageencoding = "iso-8859-1"%> <%@ taglib prefix = "s"uri = "/struts-tags"%> <! apptype html public "-/014.01. "http://www.w3.org/tr/tr/html4/loose.dtd"> html> <head< <<<<< htitle>> email form </title> </head> <body> <em> 아래 양식은 Google의 SMTP 서버를 사용합니다. 따라서 gmail 사용자 이름과 암호 </em> <form action = "emailer"method = "post"> <label for = "from </label> <brad> <br/ <br/"<input type = "text"name = "from"/> <br/> <label "> password </label> <br/> input type ="password ""password "/<br/ <br/> <blabe"를 입력해야합니다. for = "to"to </label> <br/> <input type = "text"name = "to"/> <br/> <label for = "subject"> subject <br <br/> input type = "text"name = "subject"/> <br/> <label for = "body </label> <br/> <input type ="text "/<bl/"send ""send ". 이메일 "/> </form> </body> </html>
보기 만들기 :
우리는 동작이 호출되는 경우 성공을 거부하기 위해 JSP 파일의 성공을 반환하지만, 오류가 발생하는 경우 파일이 작업에서 반환된다는 또 다른 견해를 갖게됩니다.
<%@ page language = "java"contmenttype = "text/html; charset = iso-8859-1"pageencoding = "iso-8859-1"%> <%@ taglib prefix = "s"uri = "/struts-tags"%> <! apptype html public "-/014.01. "http://www.w3.org/tr/tr/tr/html4/loose.dtd"> html> <head><Title>> email 성공 </title> </head> <body> 이메일 <s : property value ="to "to"</body> </html>
다음은 오류 케이스에 있습니다. 조치에서보기 파일 Error.jsp를 반환하십시오.
<%@ page language = "java"contmenttype = "text/html; charset = iso-8859-1"pageencoding = "iso-8859-1"%> <%@ taglib prefix = "s"uri = "/struts-tags"%> <! apptype html public "-/014.01. "http://www.w3.org/tr/tr/tr/html4/loose.dtd"> html> <head> <title>> email error </title> </head> <body> 이메일을 <s :"to "/> .</ body> </html>으로 보내는 데 문제가 있습니다.
구성 파일 :
이제이 모든 것을 struts.xml의 구성 파일과 결합하여 다음과 같이합시다.
<? xml version = "1.0"alcoding = "utf-8"?> <! doctype struts public "-// apache Software Foundation // dtd struts configuration 2.0 // en" "http://struts.apache.org/dtds/struts-2.0.dtd"> 이름 = "helloorld"extends = "struts-default"> <action name = "emailer"method = "execute"> <result name = "success">/success.jsp </result> <result name = "error.jsp </result> </action> </struts>
Web.xml 파일의 내용은 다음과 같습니다.
<? 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"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_3_0.xsd"id = "weacp_id"버전 = "> <display-name> struts 2 </display-name> <collect-file> index.jsp </welcome-file> </welcome-file-list> <filter> <filter-name> struts2 </filter-name> <filter-class> org.apache.struts2.dispatcher.filterdispatcher </filter class> </filter> <filter-name> struts2 </filter-name> <Url-pattern>/*</url-pattern> </필터 매핑> </web-app>
이제 프로젝트 이름을 마우스 오른쪽 버튼으로 클릭하고 내보내기> 전쟁 파일을 클릭하여 전쟁 파일을 만듭니다. 그런 다음 Tomcat의 WebApps 디렉토리 에이 전쟁을 배포하십시오. 마지막으로 Tomcat 서버를 시작하고 URL http : // localhost : 8080/helloworldstruts2/index.jsp에 액세스하십시오. 이것은 다음과 같은 그림을 제공합니다.
필요한 정보를 입력하고 "이메일 보내기"버튼을 클릭하십시오. 모든 것이 잘되면 다음 페이지가 표시됩니다.
세 가지 SSH 프레임 워크가 함께 사용되면 여기에 예를 들려 드리겠습니다. 그러나 Struts and Spring, Mail.jar, activation.jar의 프레임 워크 외에도 필요합니다.
1) 먼저 ApplicationContext.xml 파일에서 Bean을 구성하십시오
<bean id = "mailsender"> <property name = "host"value = "host"/> <property name = "username"value = "username"/<property name = "password"vale = "password"/> </bean> <bean id = "sendmailaction"singleton = "false"> <property name = "mailsender"> <mailsender "/bean> </bean>.
2) 이메일 보내기위한 Java 클래스 코드를 구현합니다
보호 된 javamailsenderimpl mailsender; public class sendmailaction은 ActionSupport를 확장합니다 {public void setmailsender (javamailsenderimpl mailsender) {this.mailsender = mailsender;} public void sendmail () 예외 {public void sendmail ()1 : 간단한 이메일
보호 된 javamailsenderimpl mailsender; public class sendmailaction은 ActionSupport를 확장합니다 {public void setmailsender (javamailsenderimpl mailsender) {this.mailsender = mailsender;} public void sendmail () 예외 {public void sendmail () 2 : HTML 메일을 보내십시오
// 전자 메일 메시지 만들기, 간단한 이메일 및 HTML 전자 메일 MIMEMESSAGE MailMessage = senderimpl.createmimemessage (); MimeSageHelper MessageHelper = New MimemessageHelper (MailMessage); // 수신자와 발신자 MessageHelper.setto ( "[email protected]")를 설정합니다. MessageHelper.setfrom ( "[email protected]"); MessageHelper.setSubject ( "테스트 html mail!"); // true message messagehelper.settext ( "<html> <head> </head> <hod> <h1> 안녕하세요 !! Zhangjian </h1> </body> </html>", true); // 이메일 보내기 senderimpl.send (mailmessage);
3 :이 테스트 이메일의 중첩 사진
// 전자 메일 메시지 만들기, 간단한 이메일 및 HTML 전자 메일 MIMEMESSAGE MailMessage = senderimpl.createmimemessage (); // 여기 부울은 이미지가 사실 일 때만 둥지를 틀 수 있습니다. MimemessageHelper를 구축 할 때 주어진 값은 활성화됩니다. 멀티 파트 모드 MimemessageHelper MessageHelper = New MimemessageHelper (MailMessage, True); // 수신자를 Sender MessageHelper.setto ( "[email protected]")를 설정합니다. MessageHelper.setfrom ( "[email protected]"); MessageHelper.setSubject ( "테스트 메일의 중첩 이미지 !!"); // true는 html 형식의 메시지를 messagehelper.settext로 나타냅니다. filesystemresource img = new FilesyStemResource (새 파일 ( "C : /aaa.jpg")); MessageHelper.addinline ( "AAA", IMG); // 이메일 보내기 senderimpl.send (mailmessage); }}