1、创建mysql数据库,结构如下图所示:
2、新建数据连接:
3、新建NetBeans项目,在第四步“框架”中选择“Spring Web MVC”、“Struts2”和“Hibernate”选项,如果IDE不包含“Struts2”选项,则需要下载插件安装:
系统自动生成如下配置文件:web.xml、applicationContext.xml、hibernate.cfg.xml、struts.xml和dispatcher-servlet.xml。
web.xml中的重要内容:
<context-param>配置,引入spring配置文件applicationContext.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
Struts2过滤器:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
将<filter-mapping>修改为:
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
删除web.xml中的dispatcher<servlet>配置:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
删除dispatcher-servlet.xml文件及JSP文件夹。
hibernate.cfg.xml:配置了数据源
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/book</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456</property>
</session-factory>
</hibernate-configuration>
4、创建如下的包结构:
5、新建hibernate逆向工程:注意在hibernate.cfg.xml文件中连接数据库的语句一定要正确,如果在hibernate.cfg.xml文件中没有下面的语句,则一定要加入,否则无法找到可用表。
<property name="hibernate.connection.password">********</property>
6、通过“”新建“Hibernate映射文件”和POJO
完成后新增了Admin类:
public class Admin implements java.io.Serializable {
private int UId;
private String UName;
private String UPass;
public Admin() {
}
public Admin(int UId) {
this.UId = UId;
}
public Admin(int UId, String UName, String UPass) {
this.UId = UId;
this.UName = UName;
this.UPass = UPass;
}
public int getUId() {
return this.UId;
}
public void setUId(int UId) {
this.UId = UId;
}
public String getUName() {
return this.UName;
}
public void setUName(String UName) {
this.UName = UName;
}
public String getUPass() {
return this.UPass;
}
public void setUPass(String UPass) {
this.UPass = UPass;
}
}
新增了Admin.hbm.xml映射文件,给出数据库book中的数据表admin和类Admin之间的映射关系:
<hibernate-mapping>
<class name="book.model.Admin" table="admin" catalog="book">
<id name="UId" type="int">
<column name="u_id" />
<generator class="assigned" />
</id>
<property name="UName" type="string">
<column name="u_Name" length="20" />
</property>
<property name="UPass" type="string">
<column name="u_Pass" length="20" />
</property>
</class>
</hibernate-mapping>
在hibernate.cfg.xml文件中增加了映射语句:
<mapping resource="book/model/Admin.hbm.xml"/>
7、在applicationContext.xml文件中添加如下语句,创建“sessionFactory”工厂,整合Hibernate和Spring:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!--确定配置文件hibernate.cfg.xml的位置-->
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
8、在idao包中新建IUserDao接口,完成系统的DAO规范(面向数据):
package book.idao;
import book.model.Admin;
import java.util.List;
public interface IUserDao {
Admin getAdmin(Integer id);
Admin getAdmin(String usernaem);
Admin getAdmin(String username,String password);
List getAdmins(String username);
List getAll();
void saveAdmin(Admin admin);
void removeAdmin(String username);
void removeAdmin(Integer id);
}
在iservice包中新建IUserService接口,完成系统的业务逻辑规范(面向应用):
package book.iservice;
import book.model.Admin;
import java.util.List;
public interface IUserService {
Admin findAdmin(String username);
List findAdmins(String username);
void addAdmin(Admin admin);
void deleteAdmin(Integer id);
Admin findByUsernameAndPassword(String username,String password);
}
9、实现IUserDao接口:需要继承HibernateDaoSupport,使用HibernateTemplate模板实现DAO接口,需要注意的是queryString查询语句类似SQL查询语句,但queryString查询语句针对的是类和它的属性,这里是Admin和UName、UPass、UId,而SQL查询语句针对的是数据表和它的字段。
package book.dao;
import book.idao.IUserDao;
import book.model.Admin;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class UserDao extends HibernateDaoSupport implements IUserDao{
@Override
public Admin getAdmin(String username) {
String queryString="select o from Admin o where o.UName=?";
Admin admin=null;
List list=getHibernateTemplate().find(queryString,username);
if(!list.isEmpty()){
admin=(Admin) list.get(0);
}
return admin;
}
@Override
public Admin getAdmin(String username, String password) {
String queryString="select o from Admin o where o.UName=? and o.UPass=?";
Admin admin=null;
List list=getHibernateTemplate().find(queryString,username,password);
if(!list.isEmpty()){
admin=(Admin) list.get(0);
}
return admin;
}
@Override
public void saveAdmin(Admin admin) {
getHibernateTemplate().saveOrUpdate(admin);
getHibernateTemplate().flush();
}
@Override
public void removeAdmin(String username) {
getHibernateTemplate().delete(getAdmin(username));
}
@Override
public Admin getAdmin(Integer id) {
Admin admin=null;
admin=(Admin)getHibernateTemplate().get(Admin.class, id);
return admin;
}
@Override
public void removeAdmin(Integer id) {
getHibernateTemplate().delete(getAdmin(id));
}
@Override
public List getAdmins(String username) {
String queryString="select o from Admin o where o.UName=?";
List list=getHibernateTemplate().find(queryString,username);
return list;
}
@Override
public List getAll() {
String queryString="select o from Admin o";
List list=getHibernateTemplate().find(queryString);
return list;
}
}
10、在applicationContext.xml文件中添加如下语句,配置接口注入,实现面向接口IUserDao的编程:
<!--配置DAO组件-->
<bean id="IUserDao" class="book.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
11、实现IUserService接口:
package book.service;
import book.idao.IUserDao;
import book.iservice.IUserService;
import book.model.Admin;
import java.util.List;
public class UserService implements IUserService{
private IUserDao idao;
public void setIUserDao(IUserDao idao){
this.idao=idao;
}
@Override
public Admin findAdmin(String username) {
return idao.getAdmin(username);
}
@Override
public List findAdmins(String username) {
return idao.getAdmins(username);
}
@Override
public void addAdmin(Admin admin) {
idao.saveAdmin(admin);
}
@Override
public void deleteAdmin(Integer id) {
idao.removeAdmin(id);
}
@Override
public Admin findByUsernameAndPassword(String username, String password) {
return idao.getAdmin(username, password);
}
}
接口实现类UserService中的setIUserDao方法实现了set注入,实现了使用接口IUserDao的编程。
12、在applicationContext.xml文件中添加如下语句,配置业务逻辑组件:
<!--配置业务逻辑组件的事务代理,使用了bean的继承-->
<bean id="IUserService" parent="txProxyTemplate">
<!--配置事务代理时,指定代理的目标,此处的目标是嵌套bean-->
<property name="target">
<!--嵌套bean无需使用id属性-->
<bean class="book.service.UserService">
<!--为业务逻辑组件注入DAO组件-->
<property name="IUserDao" ref="IUserDao"/>
</bean>
</property>
</bean>
13、在applicationContext.xml文件中添加如下语句,配置Hibernate事务管理器:
<!--配置Hibernate对应的事务管理器-->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<!--为事务管理器注入sessionFactory引用-->
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!--定义事务模板类,模板类增加abstract="true"属性-->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<!--注入事务管理器-->
<property name="transactionManager" ref="transactionManager"/>
<!--配置事务属性-->
<property name="transactionAttributes">
<props>
<!--所有以add开头的方法的事务属性-->
<prop key="add*">PROPAGATION_REQUIRED</prop>
<!--所有以delete开头的方法的事务属性-->
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<!--其他方法的事务属性-->
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
14、创建UserAction.java,实现struts2架构的MVC:
package book.action;
import com.opensymphony.xwork2.ActionContext;
import book.iservice.IUserService;
import book.model.Admin;
public class UserAction {
private String userName;
private String userPassword;
private String msg;
private IUserService iuserService;
public void setIUserService(IUserService iuserService){
this.iuserService=iuserService;
}
public String execute()throws Exception{
Admin user=iuserService.findByUsernameAndPassword(userName, userPassword);
if(user!=null){
msg="登录成功!"+user.getUName();
ActionContext.getContext().getSession().put("user",user);
}else{
msg="登录失败!<a href=\"JavaScript:window.history.back()\">返回</a>";
}
return "msg";
}
public void setUserName(String userName){
this.userName=userName;
}
public void setUserPassword(String userPassword){
this.userPassword=userPassword;
}
public String getMsg(){
return msg;
}
}
15、在文件中在applicationContext.xml文件中添加如下语句,配置action注入:
<!--配置Struts2的Action组件-->
<bean name="UserAction" class="book.action.UserAction">
<!--注入IUserService-->
<property name="IUserService">
<ref bean="IUserService"/>
</property>
</bean>
16、配置struts.xml文件:
<struts>
<package name="book" extends="struts-default">
<action name="UserAction" class="book.action.UserAction">
<result name="msg">/index.jsp</result>
</action>
</package>
</struts>
17、创建如下两个页面:
Login.jsp:
<%@ page pageEncoding="gb2312" %>
<%@ page contentType="text/html; charset=gb2312" %>
<% request.setCharacterEncoding("gb2312"); %>
<%@ page language="java" %>
<html>
<head><title>登录网页</title></head>
<body>
<form method="POST" action="UserAction.action">
<table >
<tr>
<td width="890" align="left" colspan="2">
<b><font size="5">系统登录</font></b>
<hr>
</td>
</tr>
<% if (request.getAttribute("error") != null){ %>
<tr>
<td width=100% align=center colspan=4 height=36>
<font color=red><b><%=request.getAttribute("error")%></b></font>
</td>
</tr>
<%
}
%>
<tr>
<td width="75" align="center">
<p align="right">账号:</p>
</td>
<td width="809" align="center">
<p align="left">
<input type="text" name="userName" size="20"></td>
</tr>
<tr>
<td width="75" align="center">
<p align="right">密码:</p>
</td>
<td width="809" align="center">
<p align="left">
<input type="password" name="userPassword" size="20">
<input type="submit" value="登录" name="loginButton"></td>
</tr>
</table>
</form>
</body>
</html>
在这个页面中,下面的form标记语句:
<form method="POST" action="UserAction.action">
表示该页面提交一个名为:"UserAction"的action,注意和struts.xml文件中的action的name相对应。
index.jsp:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>显示信息</title>
</head>
<body>
<h1>Hello World!</h1>
<div id="content">
<center>
<br/><%=request.getAttribute("msg")%>
</center>
</div>
</body>
</html>
该页面的标记语句:
<%=request.getAttribute("msg")%>
表示接收来自action的msg字符串。
18. 生成项目,并运行http://localhost:8080/login/login.jsp