一、数据库设计:
/*
NavicatMySQLDataTransfer
SourceServer:localhost
SourceServerVersion:50611
SourceHost:localhost:3306
SourceDatabase:mldn
TargetServerType:MYSQL
TargetServerVersion:50611
FileEncoding:65001
Date:2013-09-1621:03:49
*/
SETFOREIGN_KEY_CHECKS=0;
------------------------------
--Tablestructurefor`person`
------------------------------
DROPTABLEIFEXISTS`person`;
CREATETABLE`person`(
`id`int(4)NOTNULLAUTO_INCREMENT,
`name`varchar(20)NOTNULL,
`password`varchar(20)DEFAULTNULL,
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=25DEFAULTCHARSET=utf8;
------------------------------
--Recordsofperson
------------------------------
INSERTINTO`person`VALUES('1','aa','aa');
INSERTINTO`person`VALUES('2','user','user12');
INSERTINTO`person`VALUES('4','mldn','mldn');
INSERTINTO`person`VALUES('14','cc','aa');
INSERTINTO`person`VALUES('15','cc','aa');
INSERTINTO`person`VALUES('19','xiaoqun','aa');
INSERTINTO`person`VALUES('21','cc','cc');
INSERTINTO`person`VALUES('22','cc','dd');
INSERTINTO`person`VALUES('23','bb','cc');
二、DAO设计
1、DataBaseConnection.java
//本类只用于数据库连接及关闭操作
packageorg.lxh.dbc;
importjava.sql.*;
publicclassDataBaseConnection
{
//属性
//定义数据库操作的常量、对象
//数据库驱动程序
privatefinalStringDBDRIVER="com.mysql.jdbc.Driver";
//数据库连接地址
privatefinalStringDBURL="jdbc:mysql://localhost:3306/mldn";
//数据库用户名
privatefinalStringDBUSER="root";
//数据库连接密码
privatefinalStringDBPASSWORD="root";
//声明一个数据库连接对象
privateConnectionconn=null;
//在构造方法之中连接数据库
publicDataBaseConnection()
{
try
{
//加载驱动程序
Class.forName(DBDRIVER);
//连接数据库
conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
}
catch(Exceptione)
{
System.out.println(e);
}
}
//返回一个数据库连接
publicConnectiongetConnection()
{
///返回连接对象
returnthis.conn;
}
//关闭数据库连接
publicvoidclose()
{
try
{
this.conn.close();
}
catch(Exceptione)
{
}
}
};
2、PersonVo.java
//只包含setter和getter方法的类
packageorg.lxh.vo;
publicclassPersonVo
{
privateintid;
privateStringname;
privateStringpassword;
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
};
3、PersonDAO.java
//本接口定义本项目中所操作person表的全部方法
packageorg.lxh.dao;
//使用PersonVo类
importorg.lxh.vo.*;
importjava.util.List;
//登录验证的接口
publicinterfacePersonDAO
{
//需要一个登陆验证的方法
publicbooleanisLogin(PersonVopv);
publicvoidinsert(PersonVopv)throwsException;
publicvoiddelete(intid)throwsException;
publicvoidupdate(PersonVopv)throwsException;
publicListqueryById(intid)throwsException;
publicListqueryAll()throwsException;
publicListqueryByLike(Stringcond)throwsException;
}
4、PersonDAOIpml.java
//具体实现DAO接口的类
packageorg.lxh.daoimpl;
//需要连接数据库
//需要对VO的内容进行具体的验证
importjava.sql.*;
importjava.util.List;
importorg.lxh.dao.*;
importorg.lxh.dbc.*;
importorg.lxh.factory.DAOFactory;
importorg.lxh.vo.*;
importjava.util.List;
importjava.util.ArrayList;
publicclassPersonDAOImplimplementsPersonDAO
{
//验证登录,已实现
publicbooleanisLogin(PersonVopv)
{
booleanflag=false;
//在此处成具体的数据库验证
//声明一个数据库操作对象
PreparedStatementpstmt=null;
//声明一个结果集对象
ResultSetrs=null;
//声明一个SQL变量,用于保存SQL语句
Stringsql=null;
//DataBaseConnection为具体的数据库连接及关闭操作类
DataBaseConnectiondbc=null;
//连接数据库
dbc=newDataBaseConnection();
//编写SQL语句
sql="SELECT*FROMpersonWHEREname=?andpassword=?";
try
{
//实例化数据库操作对象
pstmt=dbc.getConnection().prepareStatement(sql);
//设置pstmt的内容,是按ID和密码验证
pstmt.setString(1,pv.getName());//设置pstmt第一个?号的值
pstmt.setString(2,pv.getPassword());//设置pstmt第二个?号的值
//查询记录
rs=pstmt.executeQuery();
//判断是否有记录
if(rs.next())
{
//如果有记录,则执行此段代码
//用户是合法的,可以登陆
flag=true;
}
//依次关闭
rs.close();
pstmt.close();
}
catch(Exceptione)
{
System.out.println(e);
}
finally
{
//最后一定要保证数据库已被关闭
dbc.close();
}
returnflag;
}
//插入数据
publicvoidinsert(PersonVopv)throwsException{
//TODOAuto-generatedmethodstub
Stringsql="INSERTINTOperson(name,password)VALUES(?,?)";
PreparedStatementpstmt=null;
DataBaseConnectiondbc=null;
dbc=newDataBaseConnection();
try
{
pstmt=dbc.getConnection().prepareStatement(sql);
pstmt.setString(1,pv.getName());
pstmt.setString(2,pv.getPassword());
pstmt.executeUpdate();
pstmt.close();
}
catch(Exceptione)
{
//System.out.println(e);
thrownewException("操作中出现错误!!!");
}
finally
{
dbc.close();
}
}
publicvoiddelete(intid)throwsException{
//TODOAuto-generatedmethodstub
Stringsql="DELETEFROMpersonWHEREid=?";
PreparedStatementpstmt=null;
DataBaseConnectiondbc=null;
dbc=newDataBaseConnection();
try
{
pstmt=dbc.getConnection().prepareStatement(sql);
pstmt.setInt(1,id);
pstmt.executeUpdate();
pstmt.close();
}
catch(Exceptione)
{
thrownewException("操作中出现错误!!!");
}
finally
{
dbc.close();
}
}
//更新
publicvoidupdate(PersonVopv)throwsException{
//TODOAuto-generatedmethodstub
Stringsql="updatepersonsetname=?,password=?whereid=?";
PreparedStatementpstmt=null;
DataBaseConnectiondbc=null;
dbc=newDataBaseConnection();
try
{
pstmt=dbc.getConnection().prepareStatement(sql);
pstmt.setString(1,pv.getName());
pstmt.setString(2,pv.getPassword());
pstmt.setInt(3,pv.getId());
pstmt.executeUpdate();
pstmt.close();
}
catch(Exceptione)
{
//System.out.println(e);
thrownewException("操作中出现错误!!!");
}
finally
{
dbc.close();
}
}
//根据id根据,用于更新
publicListqueryById(intid)throwsException{
Listlist=newArrayList();
PersonVopv=null;
Stringsql="selectid,name,passwordfrompersonwhereid=?";
PreparedStatementpstmt=null;
DataBaseConnectiondbc=null;
dbc=newDataBaseConnection();
try
{
pstmt=dbc.getConnection().prepareStatement(sql);//预编译sql
pstmt.setInt(1,id);
ResultSetrs=pstmt.executeQuery();//执行操作,返回结果集
while(rs.next())//循环读取结果
{
pv=newPersonVo();//实例化PersonVo
pv.setId(rs.getInt(1));
pv.setName(rs.getString(2));
pv.setPassword(rs.getString(3));
list.add(pv);//将user对象中加入到list集合中
}
}
catch(Exceptione)
{
thrownewException("操作错误!");
}
finally
{
dbc.close();
}
returnlist;
}
//查询全部,已实现
publicListqueryAll()throwsException{
//TODOAuto-generatedmethodstub
Listall=newArrayList();
PersonVopv=null;
Stringsql="selectid,name,passwordfromperson";
PreparedStatementpstmt=null;
DataBaseConnectiondbc=null;
dbc=newDataBaseConnection();
try
{
pstmt=dbc.getConnection().prepareStatement(sql);//预编译sql
ResultSetrs=pstmt.executeQuery();//执行操作,返回结果集
while(rs.next())//循环读取结果
{
pv=newPersonVo();//实例化PersonVo
pv.setId(rs.getInt(1));
pv.setName(rs.getString(2));
pv.setPassword(rs.getString(3));
all.add(pv);//将user对象中加入到list集合中
}
}
catch(Exceptione)
{
thrownewException("操作错误!");
}
finally
{
dbc.close();
}
returnall;
}
//模糊查询
publicListqueryByLike(Stringcond)throwsException{
//TODOAuto-generatedmethodstub
Listall=newArrayList();
PersonVopv=null;
Stringsql="selectid,name,pwdfrompersonwherenamelike?orpasswordlike?";
PreparedStatementpstmt=null;
DataBaseConnectiondbc=null;
dbc=newDataBaseConnection();
try
{
pstmt=dbc.getConnection().prepareStatement(sql);//预编译sql
pstmt.setString(1,"%"+cond+"%");
pstmt.setString(2,"%"+cond+"%");
ResultSetrs=pstmt.executeQuery();//执行操作,返回结果集
while(rs.next())//循环读取结果
{
pv=newPersonVo();
pv.setId(rs.getInt(1));
pv.setName(rs.getString(2));
pv.setPassword(rs.getString(3));
all.add(pv);//将user对象中加入到list集合中
}
}
catch(Exceptione)
{
thrownewException("操作错误!");
}
finally
{
dbc.close();
}
returnall;
}
};
5、DAOFactory.java
//取得DAO实例的工厂类
packageorg.lxh.factory;
importorg.lxh.dao.*;
importorg.lxh.daoimpl.*;
publicclassDAOFactory
{
publicstaticPersonDAOgetPersonDAOInstance()
{
returnnewPersonDAOImpl();
}
};
二、struts2.1的Action
UserAction.java
packageorg.lxh.action;
importjava.util.ArrayList;
importjava.util.List;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpSession;
importorg.apache.struts2.ServletActionContext;
importorg.apache.struts2.interceptor.ServletRequestAware;
importorg.apache.struts2.ServletActionContext;
importorg.lxh.dao.*;
importorg.lxh.factory.DAOFactory;
importorg.lxh.vo.*;
importcom.opensymphony.xwork2.ActionSupport;
publicclassUserActionextendsActionSupport{
privatestaticfinallongserialVersionUID=1L;
//name与password与登录表单中的控件名称一致
privateStringname;
privateStringpassword;
privateStringmsg;
privateStringinfo;//测试用例
publicStringgetMsg(){
returnmsg;
}
publicvoidsetMsg(Stringmsg){
this.msg=msg;
}
publicStringgetInfo(){
returninfo;
}
publicvoidsetInfo(Stringinfo){
this.info=info;
}
publicvoidsetName(Stringname){
this.name=name;
System.out.print("name:"+name);
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
System.out.print("password:"+password);
}
//查询所有
publicStringqueryAll()throwsException
{
try
{
HttpSessionsession=ServletActionContext.getRequest().getSession();
session.setAttribute("listAll",DAOFactory.getPersonDAOInstance().queryAll());
}
catch(Exceptione)
{
e.printStackTrace();
}
return"queryAll";
}
//添加
publicStringadd()throwsException{
try
{
PersonVopv=newPersonVo();
Stringname=ServletActionContext.getRequest().getParameter("name");
Stringpassword=ServletActionContext.getRequest().getParameter("password");
pv.setName(name);
pv.setPassword(password);
DAOFactory.getPersonDAOInstance().insert(pv);
queryAll();
}
catch(Exceptione)
{
e.printStackTrace();
}
returnqueryAll();
}
//删除用户--已实现
publicStringdelete()throwsException
{
try
{
//获取传送过来的id
Integerid=Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
DAOFactory.getPersonDAOInstance().delete(id);
}
catch(Exceptione)
{
e.printStackTrace();
}
returnqueryAll();
}
//通过id查询
publicStringqueryById()throwsException
{
Integerid=Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
try
{
HttpSessionsession=ServletActionContext.getRequest().getSession();
session.setAttribute("query",DAOFactory.getPersonDAOInstance().queryById(id));
}
catch(Exceptione)
{
e.printStackTrace();
}
return"update";
}
//验证登录
publicStringlogin()throwsException
{
booleanflag=false;
PersonVopv=newPersonVo();
if(name==null||"".equals(name))
{
msg="用户名不能为空";
return"err";
}
if(password==null||"".equals(password))
{
msg="密码不能为空";
return"err";
}
pv.setName(name);
pv.setPassword(password);
if(DAOFactory.getPersonDAOInstance().isLogin(pv)==true)
{
//声明session
HttpSessionsession_user=ServletActionContext.getRequest().getSession();
//把登录的用户名保存到session中
session_user.setAttribute("name",name);
flag=true;
returnqueryAll();
}
else
{
msg="用户名或密码不正确";
return"err";
}
}
//更新
publicStringupdate()throwsException{
try
{
PersonVopv=null;
pv=newPersonVo();
Integeridstr=Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
Stringnames=ServletActionContext.getRequest().getParameter("name");
Stringpasswords=ServletActionContext.getRequest().getParameter("password");
pv.setId(idstr);
//info=idstr.toString();测试用例
pv.setName(name);
pv.setPassword(password);
DAOFactory.getPersonDAOInstance().update(pv);
}
catch(Exceptione)
{
e.printStackTrace();
}
//return"err";测试用例
returnqueryAll();
}
/*
publicstaticvoidmain(String[]args)
{
PersonVopv=newPersonVo();
Stringname="aa";
Stringpassword="aa";
pv.setPassword(password);
pv.setName(name);
if(DAOFactory.getPersonDAOInstance().isLogin(pv))
{
System.out.println("执行成功");
System.out.print("存在此条记录!!!!");
}
}
*/
}
四、Struts.xml配置
<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN""http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<packagename="Mypackage"extends="struts-default"namespace="/">
<actionname="test"class="org.lxh.action.UserAction">
<resultname="queryAll">queryAll.jsp</result>
<resultname="update">update.jsp</result>
<resultname="err">login.jsp</result>
<resultname="error">error.jsp</result>
<resultname="add_success">add_success.jsp</result>
</action>
</package>
</struts>
五、web.xml配置
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns: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>struts_2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list><!--Struts2过滤器-->
<filter>
<!--过滤器名称-->
<filter-name>struts2</filter-name>
<!--过滤器类-->
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!--Struts2过滤器映射-->
<filter-mapping>
<!--过滤器名称-->
<filter-name>struts2</filter-name>
<!--过滤器映射,这是重点-->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
六、页面设计
1、Login.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="gbk"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>登陆界面</title>
</head>
<body>
<center>
<h2>
<fontcolor=red>
<s:propertyvalue="msg"/>
</font>
</h2>
</center>
<s:formaction="test!login.action">
<tablewidth="250"align="center">
<tr>
<tdcolspan="2"align="center"><h1>登陆界面</h1></td>
</tr>
<tr>
<td><s:textfieldlabel="用户名"name="name"cssStyle="width:160px;height:20">
</s:textfield></td>
</tr>
<tr>
<td><s:passwordlabel="密码:"name="password"cssStyle="width:160px;height:20">
</s:password></td>
</tr>
<tr>
<tdcolspan="2"align="center"valign="middle"><s:submitvalue="提交"align="left"theme="simple">
</s:submit><c:resetvalue="重置"align="left"theme="simple"></c:reset></td>
</tr>
</table>
</s:form>
</body>
</html>
2、queryAll.jsp
<%@pagelanguage="java"pageEncoding="UTF-8"%>
<%@tagliburi="http://java.sun.com/jstl/core_rt"prefix="c"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>查询所以信息界面</title>
</head>
<%
if(session.getAttribute("name")==null)
{
response.setHeader("refresh","2;URL=login.jsp");
%>
您还未登陆,请先登陆!!!<br>
两秒后自动跳转到登陆窗口!!!<br>
如果没有跳转,请按<ahref="login.jsp">这里</a>!!!<br>
<%
}
%>
<body>
<h1><%=session.getAttribute("name")%>,你好,欢迎你!</h1>
<center>
<tableborder="1"align="center">
<tr>
<tdcolspan="5"align="center">用户信息列表</td>
</tr>
<tr>
<tdcolspan="5"align="center"><ahref="add.jsp">添加用户信息</a></td>
</tr>
<tr>
<td>id</td>
<tdalign="center">name</td>
<tdalign="center">password</td>
<tdalign="center"colspan="2">操作</td>
</tr>
<c:forEachitems="${session.listAll}"var="list">
<tr>
<tdalign="center">${list.id}</td><!--输出id-->
<td>${list.name}</td><!--输出name-->
<td>${list.password}</td><!--输出password-->
<tdalign="center"><ahref="test!queryById?id=${list.id}">修改</a></td>
<tdalign="center"><ahref="test!delete?id=${list.id}">删除</a></td>
</tr>
</c:forEach>
</tr>
</table></center>
</body>
</html>
3.Update.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
<%@tagliburi="http://java.sun.com/jstl/core_rt"prefix="c"%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<title>修改用户</title>
</head>
<%
if(session.getAttribute("name")==null)
{
response.setHeader("refresh","2;URL=login.jsp");
%>
您还未登陆,请先登陆!!!<br>
两秒后自动跳转到登陆窗口!!!<br>
如果没有跳转,请按<ahref="login.jsp">这里</a>!!!<br>
<%
}
%>
<body>
<center>
<c:forEachitems="${session.query}"var="list">
<formname="myForm"action="test!update.action"method="post">
<tableborder="1"cellpadding="1"cellspacing="1"width="480">
<tr><tdcolspan="2"align="center">修改</td></tr>
<tr>
<td>用户名:</td><td><inputtype="text"value="${list.name}"name="name">
<inputtype="hidden"value="${list.id}"name="id"></td></tr>
<tr><td>密码:</td><td><inputtype="text"value="${list.password}"name="password"></td>
</tr>
<tr><tdalign="center"colspan="2"><inputvalue="提交"type="submit">
<inputvalue="重置"type="reset"></td></tr>
</form>
</c:forEach>
</center>
</body>
</html>
4、Add.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@taglibprefix="s"uri="/struts-tags"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'save.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<%
if(session.getAttribute("name")==null)
{
response.setHeader("refresh","2;URL=login.jsp");
%>
您还未登陆,请先登陆!!!<br>
两秒后自动跳转到登陆窗口!!!<br>
如果没有跳转,请按<ahref="login.jsp">这里</a>!!!<br>
<%
}
%>
<body>
<center>
<s:formname="myForm"action="test!add.action"method="post">
<tableborder="1"cellpadding="1"cellspacing="1"width="480">
<tr><tdcolspan="2"align="center">增加用户</td></tr>
<tr>
<tdalign="center">用户名:</td><td><inputtype="text"name="name"></td></tr>
<tr><tdalign="center">密码:</td><td><inputtype="password"name="password"></td></tr>
<tr><tdalign="center"colspan="2"><inputvalue="提交"type="submit">
<inputvalue="重置"type="reset"></td></tr>
</s:form>
</center>
</body>
</html>