使用mysql数据库作为测试数据库支持,官网地址http://www.mysql.com/download建立mydb数据库并且在其中新建users表,插入2条数据。具体做法如下:
a) 使用mysql command line client登录
b) 创建mydb数据库
create database mydb;
c) 切换到mydb
use mydb;
d) 创建用户表包含三列uid(主键自增),uname,upass
create table users(
uid int auto_increment primary key,
uname varchar(20),
upass varchar(20)
);
e) 插入2条数据,(注意列使用的不是单引号)
insert into users(`uname`,`upass`) values ('admin','123');
insert into users(`uname`,`upass`) values ('abc','123');
f) 完成
打开Myeclipse8.5,新建web工程,命名为ssh,点击完成。
获得目录结构如下:
a) 转到数据库浏览视图
b) 在DB Browser空白处点右键,新建数据库连接
c) 选择mysql数据库连接模板,填写相关连接信息
d) 驱动可以在mysql官方网站上下载mysql-connector-java-5.0.8-bin.jar,注意安装的mysql数据库和驱动版本之间的对应。
下载地址:http://www.mysql.com/downloads/connector/odbc/
e) 点击TestDriver测试成功。
a) 右键点击项目,选择MyEclipse->Add Struts Capabilities,或者点击菜单栏中MyEclipse->Project Capabilities->Add Struts Capabilities。
b) 选择struts2.1版本
c) 点击下一步,选择Struts Core(核心库)和Struts 2 Spring(包含集成Spring插件)的两个最基本库,其他根据需要可以添加。
d) 点击完成,添加后的项目多了一个Struts.xml(用于配置action),web.xml中添加了核心过滤器的配置。
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
a) 右键点击项目,选择MyEclipse->Add Spring Capabilities,或者点击菜单栏中MyEclipse->Project Capabilities->Add Spring Capabilities。
b) 选择Spring3.0版本,类库选择 Spring 3.0 AOP、Spring 3.0 Core、Spring 3.0 Persistence Core、Spring 3.0 Persistence JDBC、Spring 3.0 Web 5个库,并勾选复制到本地WEB-INF/lib目录。
c) 点击下一步,默认配置不需修改。
d) 点击完成,查看添加Spring后的项目,增加了applicationContex.xml文件
a) 右键点击项目,选择MyEclipse->Add Hibernate Capabilities,或者点击菜单栏中MyEclipse->Project Capabilities->Add Hibernate Capabilities。
b) 选择Hibernate3.3版本,如果要使用注记可选中启用annotation,但是会对后续自动生成实体类造成麻烦,不选就是用xml文件形式进行实体类映射,默认勾选Hibernate 3.3 Annotation & Entity Manager、Hibernate 3.3 Core Libraries两个类库,复制jar文件到本地WEB-INF/lib文件夹下。
c) 点击下一步,选择使用Spring的配置文件applicationContext.xml,这样就不会生成hibernate.cfg.xml,生成与否看个人习惯。
d) 点击下一步,选择已经存在的applicationContext.xml文件的位置以及创建sessionFactory的名字
e) 下一步,选择已经建立好的数据库连接mydb
f) 点击下一步,取消勾选,不生成HibernateSessionFactory类
g) 点击完成,查看工程,applicationContext.xml文件中增加了数据库连接的配置,包括datasource和sessionFactory
a) 创建包结构:model(实体类)、dao(数据库访问类)、service(业务逻辑类)、web(控制类)
利用Myeclipse生成model和dao(最好自己构建可以减少冗余代码)
转到MyEclipse数据库浏览视图下,双击mydb进行连接
右键点击users表,选择Hibernate反向工程
选择生成目录为app.model,勾选创建POJO即创建表对应的Javabean,同时创建映射文件hbm.xml,勾选更新hibernate配置,勾选创建spring dao。
下一步,选择id生成策略为native,因为users主键自增,或者在下一步中选择也可以
点击完成,回到代码视图查看工程变化,model包下面增加了Users.java、UsersDAO.java、Users.hbm.xml三个文件
将UsersDAO移动到dao包中,并抽出接口IUsersDAO
因为位置移动需要修改applicationContex.xml中的配置
<bean id="UsersDAO" class="app.dao.UsersDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"></ref>
</property>
</bean>
a) 编写service层代码,创建IUsersService接口和UsersService实现类,编写CRUD的方法。
package app.service;
import java.util.List;
import app.model.Users;
public interface IUsersService {
public List<Users> findAll();
public List<Users> findByName(String uname);
public Users findByUid(Integer uid);
public void addUsers(Users u) throws Exception ;
public void updateUsers(Users u) throws Exception ;
public void delUsers(Integer uid) throws Exception ;
public Users login(String uname,String upass);
}
package app.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import app.dao.IUsersDAO;
import app.dao.UsersDAO;
import app.model.Users;
public class UsersService implements IUsersService {
private static final Logger log = LoggerFactory.getLogger(UsersService.class);
private IUsersDAO usersDAO=null;
public void setUsersDAO(IUsersDAO usersDAO) {
this.usersDAO = usersDAO;
}
public void addUsers(Users u) throws Exception {
usersDAO.save(u);
}
public void delUsers (Integer uid) throws Exception {
usersDAO.delete(findByUid(uid));
}
public List<Users> findAll() {
return usersDAO.findAll();
}
public List<Users> findByName(String uname) {
return usersDAO.findByUname(uname);
}
public Users findByUid(Integer uid) {
return usersDAO.findById(uid);
}
public Users login(String uname, String upass) {
List list = usersDAO.findByUname(uname);
if(null==list||list.size()==0)
return null;
Users u=(Users) usersDAO.findByUname(uname).get(0);
if(null==u)
return null;
if(uname.equals(u.getUname())&&upass.equals(u.getUpass()))
return u;
else
return null;
}
public void updateUsers (Users u) throws Exception {
usersDAO.attachDirty(u);
}
}
b) 编写web层UsersAction代码,用于对用户增删改查进行处理
package app.web;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import app.model.Users;
import app.service.IUsersService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UsersAction extends ActionSupport{
private static final Logger log = LoggerFactory.getLogger(UsersAction.class);
private Integer uid=new Integer(0);// 用于修改删除时传参数
private Users u=new Users();//用于增改
private List<Users> userList=new ArrayList<Users>();//用于查询
private IUsersService usersService=null;
public String addUser() throws Exception{
try {
usersService.addUsers(u);
} catch (Exception e) {
log.error("保存用户错误",e);
return ERROR;
}
return SUCCESS;
}
public String listUser() throws Exception{
userList=usersService.findAll();
return SUCCESS;
}
public String editUser() throws Exception{
try {
u=usersService.findByUid(uid);
} catch (Exception e) {
log.error("修改用户错误",e);
return ERROR;
}
return SUCCESS;
}
public String updateUser() throws Exception{
try {
usersService.updateUsers(u);
} catch (Exception e) {
log.error("更新用户错误",e);
return ERROR;
}
return SUCCESS;
}
public String delUser() throws Exception{
try {
usersService.delUsers(uid);
} catch (Exception e) {
log.error("删除用户错误",e);
return ERROR;
}
return SUCCESS;
}
public String login() throws Exception{
try {
Users loginUser=usersService.login(u.getUname(), u.getUpass());
if(null!=loginUser){
ActionContext context=ActionContext.getContext();
context.getSession().put("LOGINUSER",loginUser);
return SUCCESS;
}
} catch (Exception e) {
log.error("登录查询错误",e);
return ERROR;
}
return INPUT;
}
public void setUsersService(IUsersService usersService) {
this.usersService = usersService;
}
public Users getU() {
return u;
}
public void setU(Users u) {
this.u = u;
}
public List<Users> getUserList() {
return userList;
}
public void setUserList(List<Users> userList) {
this.userList = userList;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
}
a) 补充applicationContext.xml配置文件,装配注入关系和事务处理
增加spring配置文件节点的命名空间,否则事务处理节点不识别:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" 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.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
增加装配关系
<bean id="UsersDAO" class="app.dao.UsersDAO">
<property name="sessionFactory">
<ref bean="sessionFactory"></ref>
</property>
</bean>
<bean id="UsersService" class="app.service.UsersService">
<property name="usersDAO" ref="UsersDAO" />
</bean>
<bean id="UsersAction" class="app.web.UsersAction">
<property name="usersService" ref="UsersService" />
</bean>
增加事务处理机制
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 配置事务的传播特性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
<!—哪些类的哪些方法参与事务 -->
<aop:config>
<aop:pointcut id="allServiceMethod" expression="execution(* app.service.*.*(..))" />
<aop:advisor pointcut-ref="allServiceMethod" advice-ref="txAdvice" />
</aop:config>
b) 配置Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.objectFactory" value="spring"></constant>
<package name="usermanage" extends="struts-default">
<action name="addUser" class="UsersAction" method="addUser">
<result name="success" type="redirect">listUser.action</result>
<result name="error">/error.jsp</result>
</action>
<action name="editUser" class="UsersAction" method="editUser">
<result name="success">/user/user_edit.jsp</result>
</action>
<action name="updateUser" class="UsersAction" method="updateUser">
<result name="success" type="redirect">listUser.action</result>
<result name="error">/error.jsp</result>
</action>
<action name="delUser" class="UsersAction" method="delUser">
<result name="success" type="redirect">listUser.action</result>
<result name="error">/error.jsp</result>
</action>
<action name="listUser" class="UsersAction" method="listUser">
<result name="success">/user/user_list.jsp</result>
</action>
<action name="login" class="UsersAction" method="login">
<result name="success">/index.jsp</result>
<result name="input">/login.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
c) 配置web.xml,设定applicationContex.xml的加载位置,如果放在WEB-INF下则不需要设定,配置监听。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
a) 页面关键代码
User_add.jsp
<s:form action="addUser">
<table border="1">
<tr><s:textfield label="用户名" name="u.uname"></s:textfield></tr>
<tr><s:textfield label="密码" name="u.upass"></s:textfield></tr>
<tr><td colspan="2"><s:submit value="保存"></s:submit></td></tr>
</table>
</s:form>
User_edit.jsp
<s:form action="updateUser">
<table border="1">
<s:hidden name="u.uid"></s:hidden>
<tr><s:textfield label="用户名" name="u.uname"></s:textfield></tr>
<tr><s:textfield label="密码" name="u.upass"></s:textfield></tr>
<tr><td colspan="2"><s:submit value="保存"></s:submit></td></tr>
</table>
</s:form>
User_list.jsp
<table border="1">
<tr><td>编号</td><td>用户名</td><td>密码</td><td>操作</td></tr>
<s:iterator value="userList">
<tr>
<td>${uid}</td>
<td>${uname }</td>
<td>${upass }</td>
<td><a href='<s:url action="editUser"><s:param name="uid" value="uid" /></s:url>'>修改</a>
<a onclick="return confirm('确定要删除吗?');" href='<s:url action="delUser"><s:param name="uid" value="uid" /></s:url>'>删除</a></td>
</tr>
</s:iterator>
</table>
Login.jsp
<s:form action="login">
<table border="1">
<tr><s:textfield label="用户名" name="u.uname"></s:textfield></tr>
<tr><s:textfield label="密码" name="u.upass"></s:textfield></tr>
<tr><td colspan="2"><s:submit value="登录"></s:submit></td></tr>
</table>
</s:form>
http://localhost:8080/ssh/login.jsp