1:Struts2表单数据校验:
(1)前台校验,也称之为客户端校验,主要是通过Javascript编程的方式进行数据的验证。
(2)后台校验,也称之为服务器校验,这里指的是使用Struts2通过xml配置的方式进行表单数据的校验。
(3)代码方式验证Action中所有的方法;代码方式验证Action中指定的方法;xml方式验证Action中所有的方法;xml方式验证Action中指定的方法;
2:代码方式验证Action中所有的方法(自己记得导jar包和我配置web.xml文件,自己脑补吧):
注册的jsp页面:
代码语言:javascript复制 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>数据校验</title>
8 </head>
9 <body>
10
11 <form action="${pageContext.request.contextPath}/data_checkData.action" method="post">
12 账号:<input type="text" name="user.name"/><br/>
13 密码:<input type="password" name="user.password"/><br/>
14 邮箱:<input type="text" name="user.email"/><br/>
15 生日:<input type="text" name="user.birthday"/><br/>
16
17 <input type="submit" value="注册"/>
18 <input type="reset" value="重置"/>
19 </form>
20
21 </body>
22 </html>
数据校验的Action类的实现:
代码语言:javascript复制 1 package com.bie.lesson10;
2
3 import com.opensymphony.xwork2.ActionSupport;
4
5 /**
6 * @author Author:别先生
7 * @date Date:2017年9月24日 下午3:28:25
8 *
9 * 1:注意,如果想要用struts的数据校验功能,必须继承ActionSupport或者实现相关接口;
10 */
11 public class CheckAction extends ActionSupport{
12
13 /**
14 *
15 */
16 private static final long serialVersionUID = 1L;
17
18 //封装请求数据
19 private User user;
20 public void setUser(User user) {
21 this.user = user;
22 }
23 public User getUser() {
24 return user;
25 }
26
27 //重写数据校验的功能
28 @Override
29 public void validate() {
30 //用户名非空校验
31 if(user.getName() == null || "".equals(user.getName())){
32 //保存错误信息
33 super.addFieldError("name", "用户的账号不能为空。");
34 }
35 //密码非空校验
36 if(user.getPassword() == null || "".equals(user.getPassword())){
37 //保存错误信息
38 super.addFieldError("password", "用户的密码不能为空");
39 }
40 //用户的邮箱校验
41 /*if(user.getEmail() == null || "".equals(user.getEmail())){
42 //保存错误信息
43 super.addFieldError("email", "用户的邮箱不能为空");
44 }*/
45 //用户的生日不能为空
46 /*if(user.getBirthday() == null || "".equals(user.getBirthday())){
47 //保存错误信息
48 super.addFieldError("birthday" , "用户的生日不能为空");
49 }*/
50
51 }
52
53 //业务方法
54 public String checkData(){
55
56 System.out.println(user);
57 return SUCCESS;
58 }
59
60 }
struts2的配置xml文件:
代码语言:javascript复制 1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6 <struts>
7 <package name="checkPackage" extends="struts-default">
8 <action name="data_*" class="com.bie.lesson10.CheckAction" method="{1}">
9 <result name="success">success2.jsp</result>
10 <result name="input">error.jsp</result>
11 </action>
12
13 </package>
14
15 </struts>
16
代码语言:javascript复制 1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6 <struts>
7 <!-- struts在允许的时候会加载这个总配置文件:src/struts.xml -->
8
9 <!-- 全局配置 -->
10 <!-- 修改Struts的默认访问后缀 -->
11 <!-- <constant name="struts.action.extension" value="action,do,struts,"></constant> -->
12 <include file="constant.xml"></include>
13
14 <!-- 在总配置文件中引入其他所有的配置文件 -->
15
16 <!-- <include file="com/bie/lesson/helloStruts.xml"></include> -->
17
18 <!-- <include file="com/bie/lesson02/strutsAction.xml"></include> -->
19
20 <!-- <include file="com/bie/lesson03/strutsConfig.xml"></include> -->
21
22 <!-- <include file="com/bie/lesson04/strutsData.xml"></include> -->
23
24 <!-- <include file="com/bie/lesson05/strutsType.xml"></include> -->
25
26 <!-- <include file="com/bie/lesson06/strutsUpload.xml"></include> -->
27
28 <!-- <include file="com/bie/lesson07/strutsInterceptor.xml"></include> -->
29
30 <!-- <include file="com/bie/lesson08/action/strutsAdmin.xml"></include> -->
31
32 <!-- <include file="com/bie/lesson09/strutsOgnl.xml"></include> -->
33
34 <include file="com/bie/lesson10/strutsCheck.xml"></include>
35
36
37
38
39 </struts>
用户的实体类的内容:
代码语言:javascript复制 1 package com.bie.lesson10;
2
3 import java.util.Date;
4
5 /**
6 * @author Author:别先生
7 * @date Date:2017年9月24日 下午3:59:21
8 *
9 *
10 */
11 public class User {
12
13 private String name;
14 private String password;
15 private String email;
16 private Date birthday;
17 public String getName() {
18 return name;
19 }
20 public void setName(String name) {
21 this.name = name;
22 }
23 public String getPassword() {
24 return password;
25 }
26 public void setPassword(String password) {
27 this.password = password;
28 }
29 public String getEmail() {
30 return email;
31 }
32 public void setEmail(String email) {
33 this.email = email;
34 }
35 public Date getBirthday() {
36 return birthday;
37 }
38 public void setBirthday(Date birthday) {
39 this.birthday = birthday;
40 }
41 public User(String name, String password, String email, Date birthday) {
42 super();
43 this.name = name;
44 this.password = password;
45 this.email = email;
46 this.birthday = birthday;
47 }
48 public User() {
49 super();
50 }
51
52
53 }
成功的页面和失败的页面:
代码语言:javascript复制 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>struts2 hello </title>
9 </head>
10 <body>
11
12 <h1>成功注册</h1>
13
14
15
16 <!-- struts的调试标签:可以观测值栈数据 -->
17 <s:debug></s:debug>
18 </body>
19 </html>
代码语言:javascript复制 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib uri="/struts-tags" prefix="s"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>Insert title here</title>
9 </head>
10 <body>
11
12 <h1>错误的视图</h1>
13 <h1>错误的error</h1>
14
15 <!-- 查看struts框架在运行时期产生的所有错误信息 -->
16 <s:fielderror></s:fielderror>
17 </body>
18 </html>
3:代码方式验证Action中指定的方法(写验证方法命名规则,validate 要验证的方法名称,举例如下所示:);
代码语言:javascript复制 1 package com.bie.lesson10;
2
3 import com.opensymphony.xwork2.ActionSupport;
4
5 /**
6 * @author Author:别先生
7 * @date Date:2017年9月24日 下午3:28:25
8 *
9 * 1:注意,如果想要用struts的数据校验功能,必须继承ActionSupport或者实现相关接口;
10 */
11 public class CheckAction extends ActionSupport{
12
13 /**
14 *
15 */
16 private static final long serialVersionUID = 1L;
17
18 //封装请求数据
19 private User user;
20 public void setUser(User user) {
21 this.user = user;
22 }
23 public User getUser() {
24 return user;
25 }
26
27 //重写数据校验的功能
28 /*@Override
29 public void validate() {
30 //用户名非空校验
31 if(user.getName() == null || "".equals(user.getName())){
32 //保存错误信息
33 super.addFieldError("name", "用户的账号不能为空。");
34 }
35 //密码非空校验
36 if(user.getPassword() == null || "".equals(user.getPassword())){
37 //保存错误信息
38 super.addFieldError("password", "用户的密码不能为空");
39 }
40 //用户的邮箱校验
41 if(user.getEmail() == null || "".equals(user.getEmail())){
42 //保存错误信息
43 super.addFieldError("email", "用户的邮箱不能为空");
44 }
45 //用户的生日不能为空
46 if(user.getBirthday() == null || "".equals(user.getBirthday())){
47 //保存错误信息
48 super.addFieldError("birthday" , "用户的生日不能为空");
49 }
50
51 }*/
52
53
54 public void validatecheckData() {
55 //用户名非空校验
56 if(user.getName() == null || "".equals(user.getName())){
57 //保存错误信息
58 super.addFieldError("name", "用户的账号不能为空。");
59 }
60 //密码非空校验
61 if(user.getPassword() == null || "".equals(user.getPassword())){
62 //保存错误信息
63 super.addFieldError("password", "用户的密码不能为空");
64 }
65 //用户的邮箱校验
66 /*if(user.getEmail() == null || "".equals(user.getEmail())){
67 //保存错误信息
68 super.addFieldError("email", "用户的邮箱不能为空");
69 }*/
70 //用户的生日不能为空
71 /*if(user.getBirthday() == null || "".equals(user.getBirthday())){
72 //保存错误信息
73 super.addFieldError("birthday" , "用户的生日不能为空");
74 }*/
75
76 }
77
78 //业务方法
79 public String checkData(){
80
81 System.out.println(user);
82 return SUCCESS;
83 }
84
85 //用户列表的展示
86 public String list(){
87
88 System.out.println("模拟是否验证");
89 return "list";
90 }
91
92 }
4:xml方式验证Action中所有的方法(代码验证比较繁琐,设计很多重复的验证逻辑,例如,非空验证,数值验证,email,日期等等,struts2对于常用的验证,进行了封装,即提供了验证器,验证指定额常用业务逻辑;);
4.1:Struts提供的验证器:xwork-core-2.3.16.3.jar ---》com.opensymphony.xwork2.validator.validators ---》default.xml
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator Definition 1.0//EN"
"http://struts.apache.org/dtds/xwork-validator-definition-1.0.dtd">
<!-- START SNIPPET: validators-default -->
<validators>
<validator name="required" class="com.opensymphony.xwork2.validator.validators.RequiredFieldValidator"/>
<validator name="requiredstring" class="com.opensymphony.xwork2.validator.validators.RequiredStringValidator"/>
<validator name="int" class="com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator"/>
<validator name="long" class="com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator"/>
<validator name="short" class="com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator"/>
<validator name="double" class="com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator"/>
<validator name="date" class="com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator"/>
<validator name="expression" class="com.opensymphony.xwork2.validator.validators.ExpressionValidator"/>
<validator name="fieldexpression" class="com.opensymphony.xwork2.validator.validators.FieldExpressionValidator"/>
<validator name="email" class="com.opensymphony.xwork2.validator.validators.EmailValidator"/>
<validator name="url" class="com.opensymphony.xwork2.validator.validators.URLValidator"/>
<validator name="visitor" class="com.opensymphony.xwork2.validator.validators.VisitorFieldValidator"/>
<validator name="conversion" class="com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator"/>
<validator name="stringlength" class="com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator"/>
<validator name="regex" class="com.opensymphony.xwork2.validator.validators.RegexFieldValidator"/>
<validator name="conditionalvisitor" class="com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator"/>
</validators>
<!-- END SNIPPET: validators-default -->
4.2:如何写xml,从而定义验证规则:
(a)xml文件名称语法:ActionClassName-validation.xml,注意,此xml需要与当前要验证的action在同一个目录; (b)举例:CheckXmlAction-validation.xml,找到xwork-core-2.3.16.3.jar/xwork-validator-1.0.3.dtd复制一下dtd的头文件:
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
代码语言:javascript复制 1 package com.bie.lesson11;
2
3 import com.opensymphony.xwork2.ActionSupport;
4
5 /**
6 * @author Author:别先生
7 * @date Date:2017年9月24日 下午3:28:25
8 *
9 * 1:注意,如果想要用struts的数据校验功能,必须继承ActionSupport或者实现相关接口;
10 */
11 public class CheckXmlAction extends ActionSupport{
12
13 /**
14 *
15 */
16 private static final long serialVersionUID = 1L;
17
18 //封装请求数据
19 private User user;
20 public void setUser(User user) {
21 this.user = user;
22 }
23 public User getUser() {
24 return user;
25 }
26
27
28 //业务方法
29 public String checkData(){
30
31 System.out.println(user);
32 return SUCCESS;
33 }
34
35 /*//用户列表的展示
36 public String list(){
37
38 System.out.println("模拟是否验证");
39 return "list";
40 }*/
41
42 }
验证的xml配置,注意起名规则:
代码语言:javascript复制 1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE validators PUBLIC
3 "-//Apache Struts//XWork Validator 1.0.3//EN"
4 "http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
5 <validators>
6
7 <!-- 验证的每一字段用field表示 -->
8 <field name="user.name">
9 <!-- 指定使用的验证器 -->
10 <field-validator type="requiredstring">
11 <!-- 验证失败的错误提示信息 -->
12 <message>用户名不能为空</message>
13 </field-validator>
14 </field>
15
16 <!-- 验证的每一字段用field表示 -->
17 <field name="user.password">
18 <!-- 指定使用的验证器 -->
19 <field-validator type="requiredstring">
20 <!-- 验证失败的错误提示信息 -->
21 <message>密码不能为空</message>
22 </field-validator>
23
24 <!-- 密码的长度校验 -->
25 <field-validator type="stringlength">
26 <param name="minLength">6</param>
27 <param name="maxLength">10</param>
28 <message>密码长度必须6-10位</message>
29 </field-validator>
30 </field>
31
32 <!-- 验证日期和验证邮箱 -->
33 <field name="user.email">
34 <field-validator type="email">
35 <message>邮箱格式不正确</message>
36 </field-validator>
37 </field>
38 <field name="user.birthday">
39 <field-validator type="date">
40 <message>日期格式不正确</message>
41 </field-validator>
42 </field>
43
44 </validators>
45
46
5:xml方式验证Action中指定的方法(与上面xml验证方式大致相同,验证xml文件内容不变);
5.1:命名规则:语法,ActionClassName-ActionName-validation.xml,举例:CheckXmlAction-data_checkData-validation.xml即验证CheckXmlAction的checkData方法;
验证总结 代码验证: 重写validate() , 验证action所有方法 Validate方法名(), 验证指定“方法名”的方法 Xml: 验证所有方法: ActionClassName-validation.xml 验证指定方法: ActionClassName-actionName-validation.xml 代码验证: 比较灵活,可以满足所有的需求. 比较繁琐,要写重复的验证判断逻辑! 适合: 表单字段较少的情况用! XML验证: 通用,但不够灵活; 可以验证特定简单的业务。 适合: 验证表单字段较多,可以大大简化代码! (配置文件过多)
6:验证错误处理的三种方法,如果数据输入错误就依旧跳转到输入数据的界面,这点在struts.xml里面控制:
代码语言:javascript复制 1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6 <struts>
7 <package name="checkXmlPackage" extends="struts-default">
8 <!-- 注册失败跳转到注册页面,显示失败信息 -->
9 <global-results>
10 <result name="input">/dataXmlCheck.jsp</result>
11 </global-results>
12
13 <action name="data_*" class="com.bie.lesson11.CheckXmlAction" method="{1}">
14 <result name="success">/success2.jsp</result>
15 <!-- <result name="input">/error.jsp</result> -->
16 <!-- <result name="list">success2.jsp</result> -->
17 </action>
18
19 </package>
20
21 </struts>
22
然后在输入数据的页面进行错误提示:
代码语言:javascript复制 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <%@ taglib prefix="s" uri="/struts-tags"%>
4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
5 <html>
6 <head>
7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8 <title>数据校验</title>
9
10 <!-- 修改struts标签默认的样式: 不让换行 -->
11 <style type="text/css">
12 ul{display: inline;}
13 ul li{display: inline;color: red;}
14 </style>
15
16 </head>
17 <body>
18
19 <!-- 显示的是Struts2在运行时期产生的所有错误 -->
20 <!-- 方式一 -->
21 <%-- <s:fielderror></s:fielderror> --%>
22
23 <%-- <s:fielderror fieldName="user.name"></s:fielderror>
24 <s:fielderror fieldName="user.password"></s:fielderror>
25 <s:fielderror fieldName="user.email"></s:fielderror>
26 <s:fielderror fieldName="user.birthday"></s:fielderror> --%>
27
28 <form action="${pageContext.request.contextPath}/data_checkXmlData.action" method="post">
29 账号:<input type="text" name="user.name"/>
30 <!-- 方式二 -->
31 <s:fielderror fieldName="user.name"></s:fielderror><br/>
32 密码:<input type="password" name="user.password"/>
33 <s:fielderror fieldName="user.password"></s:fielderror><br/>
34 邮箱:<input type="text" name="user.email"/><br/>
35 <%-- <s:fielderror fieldName="user.email"></s:fielderror> --%>
36 生日:<input type="text" name="user.birthday"/><br/>
37 <%-- <s:fielderror fieldName="user.birthday"></s:fielderror> --%>
38 <input type="submit" value="注册"/>
39 <input type="reset" value="重置"/>
40 </form>
41
42 </body>
43 </html>
方式三(fielderror.ftl文件):
代码语言:javascript复制方式3: 修改标签定义的模板 找到fielderror标签定义的模板文件: Struts-core.jartemplatesimple fielderror.ftl 把修改后的fielderror.ftl文件,放到src/ template/ simple/ fielderror.ftl 这样标签显示的样式就修改了!
<#--
/*
* $Id: fielderror.ftl 805635 2009-08-19 00:18:54Z musachy $
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-->
<#if fieldErrors??><#t/>
<#assign eKeys = fieldErrors.keySet()><#t/>
<#assign eKeysSize = eKeys.size()><#t/>
<#assign doneStartUlTag=false><#t/>
<#assign doneEndUlTag=false><#t/>
<#assign haveMatchedErrorField=false><#t/>
<#if (fieldErrorFieldNames?size > 0) ><#t/>
<#list fieldErrorFieldNames as fieldErrorFieldName><#t/>
<#list eKeys as eKey><#t/>
<#if (eKey = fieldErrorFieldName)><#t/>
<#assign haveMatchedErrorField=true><#t/>
<#assign eValue = fieldErrors[fieldErrorFieldName]><#t/>
<#if (haveMatchedErrorField && (!doneStartUlTag))><#t/>
<#assign doneStartUlTag=true><#t/>
</#if><#t/>
<#list eValue as eEachValue><#t/>
${eEachValue}
</#list><#t/>
</#if><#t/>
</#list><#t/>
</#list><#t/>
<#if (haveMatchedErrorField && (!doneEndUlTag))><#t/>
<#assign doneEndUlTag=true><#t/>
</#if><#t/>
<#else><#t/>
<#if (eKeysSize > 0)><#t/>
<ul<#rt/>
<#if parameters.cssClass??>
class="${parameters.cssClass?html}"<#rt/>
<#else>
class="errorMessage"<#rt/>
</#if>
<#if parameters.cssStyle??>
style="${parameters.cssStyle?html}"<#rt/>
</#if>
>
<#list eKeys as eKey><#t/>
<#assign eValue = fieldErrors[eKey]><#t/>
<#list eValue as eEachValue><#t/>
<li><span><#if parameters.escape>${eEachValue!?html}<#else>${eEachValue!}</#if></span></li>
</#list><#t/>
</#list><#t/>
</ul>
</#if><#t/>
</#if><#t/>
</#if><#t/>
7:staruts的表单主题样式修改(default学习.properties搜索theme,找到struts.ui.theme=xhtml默认样式,修改一下):
代码语言:javascript复制<!--对于struts标签默认的主题样式:default.xml/struts.ui.theme=xhtml
可以通过常量修改, 改为简单主题:-->
<constant name="struts.ui.theme" value="simple"></constant>
8:Struts2中常用的几个技术:数据回显,模型驱动,防止表单重复提交的应用。
(1):Struts2的数据回显技术必须使用Struts2的标签。 《手动通过value设置显示的值value="%{#request.user.name}"这个格式是通过ognl表达式进行显示数据的》。 (2):数据回显技术,通过值栈存放,然后直接通过页面的name属性进行取值<s:textfield name="userName"></textfield>,如: ActionContext ac = ActionContext.getContext(); ValueStack vs = ac.getValueStack(); //vs.pop();//移除栈顶元素 vs.push("user");//将user对象存放到值栈里面
9:综合应用:
第一步:创建数据库和数据表,这里使用mysql默认的数据库test,创建数据表如下所示:
代码语言:javascript复制-- 创建数据表
CREATE TABLE employee(
employeeId INT PRIMARY KEY AUTO_INCREMENT,
employeeName VARCHAR(20),
employeeTime DATE
)
第二步:搭建Struts的环境(导包,配置web.xml和c3p0的配置,):
代码语言:javascript复制导包,包含struts的包和mysql的包还有c3p0的包: c3p0-0.9.1.2.jar commons-dbutils-1.6.jar commons-fileupload-1.3.1.jar commons-io-2.2.jar commons-lang3-3.1.jar freemarker-2.3.19.jar javassist-3.11.0.GA.jar jstl-1.2.jar mysql-connector-java-5.1.12-bin.jar ognl-3.0.6.jar struts2-core-2.3.16.3.jar xwork-core-2.3.16.3.jar
<c3p0-config>
<!-- c3p0默认配置,下面还可以配置多个数据库 -->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">6</property>
<property name="maxPoolSize">50</property>
<property name="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
配置一下web.xml文件:
代码语言:javascript复制 1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
3 <display-name>struts</display-name>
4 <welcome-file-list>
5 <welcome-file>index.html</welcome-file>
6 <welcome-file>index.htm</welcome-file>
7 <welcome-file>index.jsp</welcome-file>
8 <welcome-file>default.html</welcome-file>
9 <welcome-file>default.htm</welcome-file>
10 <welcome-file>default.jsp</welcome-file>
11 </welcome-file-list>
12
13 <!-- struts2的核心过滤器 -->
14 <filter>
15 <filter-name>struts</filter-name>
16 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
17 </filter>
18 <filter-mapping>
19 <filter-name>struts</filter-name>
20 <url-pattern>/*</url-pattern>
21 </filter-mapping>
22 </web-app>
配置一下Struts的总配置文件struts.xml文件:
代码语言:javascript复制 1 <?xml version="1.0" encoding="UTF-8" ?>
2 <!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6 <struts>
7 <!-- struts在允许的时候会加载这个总配置文件:src/struts.xml -->
8
9 <!-- 全局配置 -->
10 <!-- 修改Struts的默认访问后缀 -->
11 <!-- <constant name="struts.action.extension" value="action,do,struts,"></constant> -->
12 <!-- <include file="constant.xml"></include> -->
13
14 <!-- 在总配置文件中引入其他所有的配置文件 -->
15
16 <!-- <include file="com/bie/lesson01/helloStruts.xml"></include> -->
17
18 <include file="com/bie/lesson02/strutsTest.xml"></include>
19
20 </struts>
第三步:弄一下连接数据库的操作:
代码语言:javascript复制 1 package com.bie.lesson02.utils;
2
3 import java.sql.Connection;
4 import java.sql.SQLException;
5
6 import javax.sql.DataSource;
7
8 import org.apache.commons.dbutils.QueryRunner;
9
10 import com.mchange.v2.c3p0.ComboPooledDataSource;
11
12 /***
13 * 数据库连接工具类
14 * @author 别先生
15 *
16 */
17 public class BaseUtils {
18
19 //初始化c3p0
20 private static DataSource dataSource = null;
21
22 //自动加载src目录下面的c3p0配置文件。c3p0-config.xml
23 static{
24 dataSource = new ComboPooledDataSource();
25 }
26
27 public static QueryRunner getQueryRunner(){
28 //第一步:创建QueryRunner对象,传入连接池对象
29 //在创建QueryRunner对象的时候,如果传入数据对象dataSource,
30 //那么在使用QueryRunner对象的方法时候,就不需要传入连接对象
31 QueryRunner query=new QueryRunner(dataSource);
32 //第二步:会自动从数据源中获取连接(不用关闭连接)
33 return query;
34 }
35
36 //测试一下是否连接通数据库
37 /*public static void main(String[] args) {
38 QueryRunner qr = getQueryRunner();
39 DataSource ds = qr.getDataSource();
40 try {
41 Connection conn = ds.getConnection();
42 System.out.println("连接数据库成功");
43 } catch (SQLException e) {
44 // TODO Auto-generated catch block
45 e.printStackTrace();
46 }
47
48 }*/
49 }
第四步:开始开发dao层,这里使用接口和实现接口的方式来开发:
代码语言:javascript复制 1 package com.bie.lesson02.dao;
2
3 import java.util.List;
4
5 import com.bie.lesson02.po.Employee;
6
7 public interface EmployeeDao {
8
9 //查询所有的员工信息
10 List<Employee> getALL();
11
12 //根据员工编号进行查询操作
13 Employee getById(int employeeId);
14
15 //添加员工信息
16 void save(Employee employee);
17
18 //修改员工信息
19 void update(Employee employee);
20 }
代码语言:javascript复制 1 package com.bie.lesson02.dao.impl;
2
3 import java.sql.SQLException;
4 import java.util.List;
5
6 import org.apache.commons.dbutils.handlers.BeanHandler;
7 import org.apache.commons.dbutils.handlers.BeanListHandler;
8
9 import com.bie.lesson02.dao.EmployeeDao;
10 import com.bie.lesson02.po.Employee;
11 import com.bie.lesson02.utils.BaseUtils;
12
13 public class EmployeeDaoImpl implements EmployeeDao{
14
15 @Override
16 public List<Employee> getALL() {
17
18 //查询的sql语句
19 String sql = " select * from employee ";
20 try {
21 return BaseUtils.getQueryRunner().query(sql, new BeanListHandler<Employee>(Employee.class));
22 } catch (SQLException e) {
23 throw new RuntimeException();
24 }
25 }
26
27 @Override
28 public Employee getById(int employeeId) {
29 //根据员工的编号进行查询
30 String sql ="select * from employee where employeeId = ? ";
31 //问号?这个参数传到后面,切记传参数
32 try {
33 return BaseUtils.getQueryRunner().query(sql, new BeanHandler<Employee>(Employee.class),employeeId);
34 } catch (SQLException e) {
35 throw new RuntimeException();
36 }
37 }
38
39 @Override
40 public void save(Employee employee) {
41 //保存员工的信息,即插入操作
42 String sql = " insert into employee(employeeName,employeeTime) values(?,?)";
43
44 //使用c3p0的插入操作
45 try {
46 BaseUtils.getQueryRunner().update(sql, employee.getEmployeeName(),employee.getEmployeeTime());
47 } catch (SQLException e) {
48 throw new RuntimeException();
49 }
50 }
51
52 @Override
53 public void update(Employee employee) {
54 //修改操作
55 String sql = "update employee set employeeName =?,employeeTime=? where employeeId =? ";
56
57 try {
58 BaseUtils.getQueryRunner().update(sql, employee.getEmployeeName(),employee.getEmployeeTime(),employee.getEmployeeId());
59 } catch (SQLException e) {
60 throw new RuntimeException();
61 }
62 }
63
64
65 }
第五步:开始开发service层,这里使用接口和实现接口的方式来开发:
代码语言:javascript复制 1 package com.bie.lesson02.service;
2
3 import java.util.List;
4
5 import com.bie.lesson02.po.Employee;
6
7 public interface EmployeeService {
8
9 //查询所有的员工信息
10 List<Employee> getALL();
11
12 //根据员工编号进行查询操作
13 Employee getById(int employeeId);
14
15 //添加员工信息
16 void save(Employee employee);
17
18 //修改员工信息
19 void update(Employee employee);
20 }
代码语言:javascript复制 1 package com.bie.lesson02.service.impl;
2
3 import java.util.List;
4
5 import com.bie.lesson02.dao.EmployeeDao;
6 import com.bie.lesson02.dao.impl.EmployeeDaoImpl;
7 import com.bie.lesson02.po.Employee;
8 import com.bie.lesson02.service.EmployeeService;
9
10 public class EmployeeServiceImpl implements EmployeeService{
11
12 private EmployeeDao dao = new EmployeeDaoImpl();
13
14 @Override
15 public List<Employee> getALL() {
16
17 return dao.getALL();
18 }
19
20 @Override
21 public Employee getById(int employeeId) {
22 if(employeeId != 0){
23 return dao.getById(employeeId);
24 }
25
26 return null;
27 }
28
29 @Override
30 public void save(Employee employee) {
31 if(employee != null){
32 dao.save(employee);
33 }
34
35 }
36
37 @Override
38 public void update(Employee employee) {
39 if(employee != null){
40 dao.update(employee);
41 }
42
43 }
44
45
46 }
第六步:以上全部搞完,基本只剩下使用Struts进行Action的开发,以及页面的书写: