Struts学习过程中的Struts经验(3)——实例转载
墨初 知识笔记 86阅读
010- 第二步:实现controller。010你好饰StrutsInnerhalb行动2004年,德国,德国,荷兰,荷兰,荷兰,数据插入议员Prozedur弹簧等。代码如下地址:SignAction.java1/* */* * 2 * @作者韩3 *苏州大学4 *现实主义者行动控制器5 */6 出版者cyclasssignactiondextension {78 ./spanpublicActionForwardexecute(actionmapping mapping,ActionForm,9HttpServletRequestrequest,httpservlet response response 10)throw exception { 1112/* *//* Parameter Beschreibung:13 * actionmappingcrealisieren Sprung,Kontrolle Seite14*ActionForm于ViewerIm erreichtenbean,获得形式在日期15 * http servlet requestrequest 16 * http servlet rsponse response 17
1)">*/18
19 ActionErrors errors = new ActionErrors(); //错误处理,详细信息见本blog的《Struts错误处理》
20
21 /*
22 * 得到form中的数据,因为form中的数据在SignForm中,做一类型转换即可;
23 * 这个要在struts-config.xml中进行说明
24 */
25 SignForm sf = (SignForm) form;
26
27 /*
28 * 调用Model业务逻辑。
29 */
30 SignModel sign = new SignModel();
31
32 sign.setEmail(sf.getEmail());
33 sign.setUserid(sf.getUserid());
34
35 /*
36 * 调用Model的findUserByEmail 和 findUserByUserid 判断
37 * email和userid是否存在。
38 * 如果存在,则添加出错信息,页面跳转到mapping.getInputforward(),需要在
39 * struts-config.xml中定义。
40 * 关于错误的详细信息请参看本blog的《struts错误处理》文章。
41 */
42 //email existed
43 if (sign.findUserByEmail()){
44 errors.add("email.existed",new ActionError("email.existed", sign.getEmail()));
45 this.saveErrors(request, errors);
46 return mapping.getInputForward();
47 }
48
49 //userid existed
50 if (sign.findUserByUserid()){
51 errors.add("userid.existed", new ActionError("userid.existed",sf.getUserid()));
52 this.saveErrors(request, errors);
53 return mapping.getInputForward();
54 }
55
56 /*
57 * 调用Model的sendPassword将系统生成的密码发送到用户信箱。
58 * 如果发生错误转到mapping.getInputForward(),这个需要在struts-config.xml中定义
59 * 详细信息见后面的struts-config.xml文件说明
60 */
61 if (sign.sendPassword()){
62 sign.saveNewUser();
63 }else{ //邮件发送错误
64 errors.add("email.send.error", new ActionError("email.send.error", sf.getEmail()));
65 this.saveErrors(request, errors);
66 return mapping.getInputForward();
67 }
68
69 /*
70 * 如果注册成功,页面跳转到mapping.findForward("home")
71 * 这个需要在struts-config.xml中定义
72 * 详细信息见后面的struts-config.xml文件说明
73 */
74 return mapping.findForward("home");
75
76
77 }
78}
说明:
1、SignAction实现MVC中的controller,通过mapping参数来实现跳转,在controller中调用了Model中的一些操作,根据操作结果来实现跳转。
2、程序中包括了Struts的错误处理(请见本blog的《struts错误处理》)、资源文件的使用,并且好多处代码都和struts的配置文件struts-config.xml有联系
3、关键代码处都有详细的注释,若还有疑问,请您留言,我们共同探讨。
第三步:实现Model,业务逻辑。用户注册程序比较简单,主要实现findUserByUserid()、findUserByEmail()、sendPassword()、saveNewUser()等功能。代码如下:
SignForm.java
1/**
2 * @author han
3 * soochow university
4 * 用户注册的Model
5 */
6public class SignModel {
7 private String email;
8 private String userid;
9 private String MsgBox = "";
10 private String password;
11 private boolean sended;
12
13
14/**
15 * @return Returns the email.
16 */
17public String getEmail() {
18 return email;
19}
20/**
21 * @param email The email to set.
22 */
23public void setEmail(String email) {
24 this.email = email;
25}
26/**
27 * @return Returns the userid.
28 */
29public String getUserid() {
30 return userid;
31}
32/**
33 * @param userid The userid to set.
34 */
35public void setUserid(String userid) {
36 this.userid = userid;
37}
38
39 //用户名和email是否存在
40 public boolean findUserByUserid() throws Exception{
41 String selectsql = "select userid from password where userid = ?";
42 Mysql mysql = new Mysql(selectsql);
43 try{
44 mysql.setString(1, this.userid);
45 ResultSet rs = mysql.executeQuery();
46 if(!rs.next()) return false;
47 } catch (Exception e){
48 throw new Exception("user.select" + e.getMessage());
49 } finally{
50 mysql.close();
51 }
52 return true;
53
54 }
55 public boolean findUserByEmail() throws Exception{
56 String selectsql = "select * from password where email = ?";
57 Mysql mysql = new Mysql(selectsql);
58 try{
59 mysql.setString(1, this.email);
60 ResultSet rs = mysql.executeQuery();
61 if(!rs.next()) return false;
62 } catch (Exception e){
63 throw new Exception("user.select" + e.getMessage());
64 } finally{
65 mysql.close();
66 }
67 return true;
68 }
69
70 public void saveNewUser() throws HibernateException{
71 Session session = HibernateUtil.currentSession();
72
73 Transaction transaction;
74 try{
75 transaction = session.beginTransaction();
76 SignForm newUser = new SignForm();
77 newUser.setEmail(this.email);
78 newUser.setUserid(this.userid);
79
80 newUser.setPassword(password);
81 session.save(newUser);
82 transaction.commit();
83 }catch(Exception e){
84 //throw new Exception(e);
85 e.printStackTrace();
86 }finally{
87 HibernateUtil.closeSession();
88 }
89 }
90
91 //发送email给用户初始密码
92 public boolean sendPassword() throws Exception{
93
94 SendMail sendMail = new SendMail();
95
96 sendMail.setFrom(Constants.FROM);
97 sendMail.setTo(this.email);
98 sendMail.setSubject(Constants.SUBJECT);
99 sendMail.setSmtpHost(Constants.smtpHost);
100
101 // 生成密码
102 password = new RandStringGenerator(8).generatorString();
103 MsgBox = Constants.WELCOME_MESSAGE_HEAD + "\r用户名:"+this.userid+"\r密码:" + this.password + "\r" + Constants.WELCOME_MESSAGE_FOOT;
104 sendMail.setMsgText(MsgBox);
105
106
107
108 try{
109 sendMail.sendnow();
110 sended = true;
111 }catch (Exception e){
112 System.err.println("send mail error:" + e.getMessage());
113 //throw new Exception("send mail error" + e.getMessage());
114 sended = false;
115 }
116 return sended;
117 }
118}
2 * @author han
3 * soochow university
4 * 用户注册的Model
5 */
6public class SignModel {
7 private String email;
8 private String userid;
9 private String MsgBox = "";
10 private String password;
11 private boolean sended;
12
13
14/**
15 * @return Returns the email.
16 */
17public String getEmail() {
18 return email;
19}
20/**
21 * @param email The email to set.
22 */
23public void setEmail(String email) {
24 this.email = email;
25}
26/**
27 * @return Returns the userid.
28 */
29public String getUserid() {
30 return userid;
31}
32/**
33 * @param userid The userid to set.
34 */
35public void setUserid(String userid) {
36 this.userid = userid;
37}
38
39 //用户名和email是否存在
40 public boolean findUserByUserid() throws Exception{
41 String selectsql = "select userid from password where userid = ?";
42 Mysql mysql = new Mysql(selectsql);
43 try{
44 mysql.setString(1, this.userid);
45 ResultSet rs = mysql.executeQuery();
46 if(!rs.next()) return false;
47 } catch (Exception e){
48 throw new Exception("user.select" + e.getMessage());
49 } finally{
50 mysql.close();
51 }
52 return true;
53
54 }
55 public boolean findUserByEmail() throws Exception{
56 String selectsql = "select * from password where email = ?";
57 Mysql mysql = new Mysql(selectsql);
58 try{
59 mysql.setString(1, this.email);
60 ResultSet rs = mysql.executeQuery();
61 if(!rs.next()) return false;
62 } catch (Exception e){
63 throw new Exception("user.select" + e.getMessage());
64 } finally{
65 mysql.close();
66 }
67 return true;
68 }
69
70 public void saveNewUser() throws HibernateException{
71 Session session = HibernateUtil.currentSession();
72
73 Transaction transaction;
74 try{
75 transaction = session.beginTransaction();
76 SignForm newUser = new SignForm();
77 newUser.setEmail(this.email);
78 newUser.setUserid(this.userid);
79
80 newUser.setPassword(password);
81 session.save(newUser);
82 transaction.commit();
83 }catch(Exception e){
84 //throw new Exception(e);
85 e.printStackTrace();
86 }finally{
87 HibernateUtil.closeSession();
88 }
89 }
90
91 //发送email给用户初始密码
92 public boolean sendPassword() throws Exception{
93
94 SendMail sendMail = new SendMail();
95
96 sendMail.setFrom(Constants.FROM);
97 sendMail.setTo(this.email);
98 sendMail.setSubject(Constants.SUBJECT);
99 sendMail.setSmtpHost(Constants.smtpHost);
100
101 // 生成密码
102 password = new RandStringGenerator(8).generatorString();
103 MsgBox = Constants.WELCOME_MESSAGE_HEAD + "\r用户名:"+this.userid+"\r密码:" + this.password + "\r" + Constants.WELCOME_MESSAGE_FOOT;
104 sendMail.setMsgText(MsgBox);
105
106
107
108 try{
109 sendMail.sendnow();
110 sended = true;
111 }catch (Exception e){
112 System.err.println("send mail error:" + e.getMessage());
113 //throw new Exception("send mail error" + e.getMessage());
114 sended = false;
115 }
116 return sended;
117 }
118}
说明:
1、saveNewUser()使用了Hibernate作为持久化工具,关于Hibernate请参阅相关资料,也可以留言我们共同讨论。
2、sendPassword()使用JavaMail发送Email,本文件通过SendMail工具类实现。
3、密码生成由RandStringGenerator()工具类生成。
4、工具类可以点击这里下载。
第四步:配置struts-config.xml。
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "">
<struts-config>
<global-forwards> 全局转发
<!-- 对应SignAction.java 中的return mapping.findForward("home"); -->
<forward name="home" path="/index.jsp"/>
<forward name="userhome" path="/user/userhome.jsp"/>
</global-forwards>
<form-beans>
<!-- bean的声明,这个在下面的Action设置中要用到 -->
<form-bean name="signForm" type="user.SignForm" />
</form-beans>
<!-- 设置Aciton -->
<action-mappings>
<action path="/sign" 对应<form action>中action的值,在signin.jsp中的action=/login.do
name="signForm" 设置的formBean,名称对应<from-bean>中的声明,在SignAction.java中对应输入参数ActionForm
type="user.SignAction" Action的类
validate="true" 是否验证
scope="request" 作用域 这些应该不用解释了
input="/user/signin.jsp"> 当发生错误时定向的页面,对应SignAction.java中的mapping.getInputForward()
</action>
</action-mappings>
<!-- ========== 资源文件定义,详细信息在《Struts中资源文件使用》中说明=========== -->
<message-resources parameter="Application"/>
</struts-config>
<struts-config>
<global-forwards> 全局转发
<!-- 对应SignAction.java 中的return mapping.findForward("home"); -->
<forward name="home" path="/index.jsp"/>
<forward name="userhome" path="/user/userhome.jsp"/>
</global-forwards>
<form-beans>
<!-- bean的声明,这个在下面的Action设置中要用到 -->
<form-bean name="signForm" type="user.SignForm" />
</form-beans>
<!-- 设置Aciton -->
<action-mappings>
<action path="/sign" 对应<form action>中action的值,在signin.jsp中的action=/login.do
name="signForm" 设置的formBean,名称对应<from-bean>中的声明,在SignAction.java中对应输入参数ActionForm
type="user.SignAction" Action的类
validate="true" 是否验证
scope="request" 作用域 这些应该不用解释了
input="/user/signin.jsp"> 当发生错误时定向的页面,对应SignAction.java中的mapping.getInputForward()
</action>
</action-mappings>
<!-- ========== 资源文件定义,详细信息在《Struts中资源文件使用》中说明=========== -->
<message-resources parameter="Application"/>
</struts-config>
第五步:调试程序。经过上面的说明和代码示例是不是对Struts中的MVC架构有了比较清晰的了解,我们知道在java特别是j2ee的软件中,需要设置很多的配置文件,刚开始的时候非常烦,特别是频频出错的时候,那种感觉学java的人应该都尝过哦!但是当你彻底了解了配置文件的确切含义,并且能和代码中的内容进行联系时,就会豁然开朗了,就不会觉得象走进死胡同似的。
有了上面struts-config.xml中的说明,相信你已经和代码联系起来了,如果将这个程序调试成功,那么你就可以说我已经对struts设计MVC Web程序入门了,一旦跨进了这个门槛,你会觉得学习起来是那么的轻松,一些来得是那么自然。
好了,希望以上三篇文章能带你走进Struts,理解Struts,特别是熟悉Struts的基本流程,当然要想对一种模式由深入的了解,必须要多加实践,从实践中来体验到它的好处。
最后,希望你能彻底了解Struts,能为你所用。如果有什么意见和评论,请留言,我们共同讨论,共同进步。
谢谢你的阅读!

标签: