虽然之前在长沙实习的时候就是用Struts2.x做的一个《企业多媒体管理系统》的网站,而且这个网站做的还挺好的,最后小组甚至被评为同一班级中最佳的小组。那二十天里是一边学习一边做东西,而最后老师们是帮我们把很基本的环境搭建好,我们只需要写个jsp页面,然后再写上DAO,Service和Action就可以了。其实最重要的也就这么几部。可是现在毕业正式工作以后才发现自己连最基本的搭建SSH环境都不会。认真的把Hibernate,Struts2.x和Spring再看了一下,经过二十天终于搞清楚了。写下这篇博文方便自己的巩固和日后的复习。可能有很多地方还没有深刻的了解,只是知道如果做,或者有错误的地方,欢迎提出来一起讨论。
说一下我的工具:
Myeclipse 2013、mysql5.0、navicate for mysql、tomcat7.x。
有了这些就好办了,我们先创建一个Web project 项目名叫“SSH”,然后把package之类的都准备好:
action 包中存放 Action类;
bean包中存放实体类;
dao包中存放DAO接口;
daoimpl中存放通过实现dao中的接口对POJO对象的操作;
service存放Service接口;
serviceimpl中存放通过实现service中的接口对事物的处理;
(我个人觉得,dao层和service层的区别很明显,dao层就是对底层数据的基本操作,比如增删改查之类的,而service则是对行为具体的实现,比如验证用户存在,查找用户等等)
Myeclipse是个很强大的工具,直接右击项目-Myeclipse-Project Facets-xxx 中依次添加 spring,hibernate,struts2.x 。这里需要说明的是,我们在添加hibernate的时候不需要hibernate.cfg.xml。因为spring吧所有的这些配置都可以整合在applicationContext.xml中。 还有一点就是,最后不要忘了添加com.mysql.jdbc.Driver的jar包(右击SSH--Build Path-Add external Archves...。
很简单,基本的框架就已经搭建完成,下面就可以先写在com.ssh.bean中写实体类了:
package com.ssh.bean;
/**
* User entity. @author MyEclipse Persistence Tools
*/
public class User implements java.io.Serializable {
// Fields
private Integer id;
private String username;
private String password;
// Constructors
/** default constructor */
public User() {
}
/** full constructor */
public User(String username, String password) {
this.username = username;
this.password = password;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
我们使用的是hibernate 中的xml注解,所以:com.ssh.bean中还有User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.ssh.bean.User" table="user" catalog="text">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="50" not-null="true" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="50" not-null="true" />
</property>
</class>
</hibernate-mapping>
</pre><pre name="code" class="java">我们要实现用户的登录和注册,所以会有如下方法:
<span style="white-space:pre"> </span><pre name="code" class="java">int getUser(String userName, String userPassword); //查找用户,返回登录结果
void saveUser(String userName,String userPassword); //用户注册时用,保存用户
boolean isExist(String userName, String userPassword); //半段用户是否已经存在
所以com.ssh.dao :
package com.ssh.dao;
import java.util.List;
import com.ssh.bean.User;
public interface UserDao {
int getUser(String userName, String userPassword); //查找用户,返回登录结果
void saveUser(String userName,String userPassword); //用户注册时用,保存用户
boolean isExist(String userName, String userPassword); //半段用户是否已经存在
}
package com.ssh.daoimpl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.opensymphony.xwork2.ActionSupport;
import com.ssh.bean.User;
import com.ssh.dao.UserDao;
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@SuppressWarnings("unchecked")
@Override
public int getUser(String userName, String userPassword) {
// TODO Auto-generated method stub
// System.out.println("---------here1-----------");
final String s1 = userName;
final String s2 = userPassword;
List<User> list = new ArrayList<User>();
list = (ArrayList<User>)this.getHibernateTemplate().execute(new HibernateCallback() {
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
// TODO Auto-generated method stub
// System.out.println("-----------here2------");
// System.out.println("=======>"+ session.createQuery("from User u where u.username='"+s1+"' ").list());
return session.createQuery("from User u where u.username='"+s1+"' ").list();
}
});
//System.out.println("-----用户不存在测试-----");
if(null == list || 0 == list.size()){
return -1; //用户不存在
}
list = (ArrayList<User>)this.getHibernateTemplate().executeFind(new HibernateCallback() {
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
// TODO Auto-generated method stub
// System.out.println("=======>"+session.createQuery("from User u where u.username='"+s1+"' and u.password='"+s2+"'").list());
return session.createQuery("from User u where u.username = '"+s1+"' and u.password = '"+s2+"'").list();
}
});
//System.out.println("------密码不正确测试-----");
if(null == list || 0 == list.size()){
return -2; //密码不正确
}
return 1;
}
@Override
public void saveUser(String userName, String userPassword) {
// TODO Auto-generated method stub
final String s1=userName;
final String s2=userPassword;
User user = new User();
user.setUsername(userName);
user.setPassword(userPassword);
this.getHibernateTemplate().save(user);
}
@SuppressWarnings("unchecked")
@Override
public boolean isExist(String userName, String userPassword) {
// TODO Auto-generated method stub
final String s1=userName;
final String s2=userPassword;
//System.out.println("------here is UserDaoImpl-------------");
List<User> list = new ArrayList<User>();
list = (ArrayList<User>)this.getHibernateTemplate().executeFind(new HibernateCallback() {
@Override
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
// TODO Auto-generated method stub
//System.out.println("========>"+session.createQuery("from User u where u.username='"+s1+"'").list());
return session.createQuery("from User u where u.username='"+s1+"'").list();
}
});
if(0 == list.size() || null == list)
{
return false; //该用户不存在,该用户名可用
}else{
return true; //该用户已经存在,不可用
}
}
}
然后com.ssh.service:
package com.ssh.service;
import java.util.List;
import com.ssh.bean.User;
public interface UserService {
int getUser(String userName, String userPassword);
void saveUser(String userName, String userPassword);
boolean isExist(String userName, String userPassword);
}
com.ssh.serviceimpl:
package com.ssh.serviceimpl;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.ssh.bean.User;
import com.ssh.dao.UserDao;
import com.ssh.daoimpl.UserDaoImpl;
import com.ssh.service.UserService;
public class UserServiceImpl implements UserService {
private UserDao userDaoImpl;
public UserDao getUserDaoImpl() {
return userDaoImpl;
}
public void setUserDaoImpl(UserDao userDaoImpl) {
this.userDaoImpl = userDaoImpl;
}
@SuppressWarnings("unchecked")
public int getUser(String userName, String userPassword) {
return userDaoImpl.getUser(userName, userPassword);
}
@Override
public void saveUser(String userName, String userPassword){
userDaoImpl.saveUser(userName, userPassword);
}
@Override
public boolean isExist(String userName, String userPassword) {
// TODO Auto-generated method stub
return userDaoImpl.isExist(userName, userPassword);
}
}
写完这些,我们可以先把页面写出来了:
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script charset="Shift_JIS"
src="http://chabudai.sakura.ne.jp/blogparts/honehoneclock/honehone_clock_tr.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/jquery.easyui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#register").hide();
$("#reg_btn").click(function() {
$("#register").show("slow");
$("#user").hide("slow");
});
$("#back_btn").click(function(){
$("#user").show("slow");
$("#register").hide("slow");
});
});
function isValid(form) {
//alert("--------here-------");
//alert("form.userPassword2.value.length="
// + form.userPassword2.value.length);
//alert("----here2------");
//alert("form.userPassword2.value=" + form.userPassword2.value
// + "and form.confirmPassword.value="
// + form.confirmPassword.value);
if (((form.userPassword2.value.length < 3) || (form.userPassword2.value.length > 8))
&& (form.userPassword2.value != "")) {
alert("密码必须是3-8位的字母或数字!");
return false;
} else if (form.userPassword2.value != form.confirmPassword.value) {
alert("两次输入的密码不同!");
return false;
} else{
//alert("注册成功!请登录!");
return true;
}
}
</script>
</head>
<body>
<br/>
<hr/>
<br/>
<form id="user" method="post" action="userAction.action">
<table width="300" align="center">
<tr>
<td>用户名:</td>
<td><input type="text" name="userName" placeholder="userName"
required="required" /></td>
</tr>
<tr>
<td>密 码</td>
<td><input type="password" name="userPassword"
placeholder="userPassword" required="required" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="登录" id="sub_btn" /> <input
type="button" value="注册" id="reg_btn" /></td>
</tr>
</table>
</form>
<form id="register" method="post" action="registerAction.action"
οnsubmit="return isValid(this)">
<table width="300" align="center">
<tr>
<td>用户名:</td>
<td><input type="text" name="userName2"
placeholder="type your username" required="required" /></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="userPassword2"
placeholder="type your password" required="required" /></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="password" name="confirmPassword"
placeholder="confirm your password" required="required" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="好!注册!" />
<input type="button" value="返回登录!" id="back_btn" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
</script>
<p>
<s:fielderror cssStyle="color:red" />
</p>
</body>
</html>
然后就是com.ssh.action中的 UserAction.java (网页中的userName 、userPassword就是通过这里的get,set方法传入后台的)
package com.ssh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.ssh.service.UserService;
@SuppressWarnings("serial")
public class UserAction extends ActionSupport {
private UserService userService;
private String userName;
private String userPassword;
private String message;
private int state;
public String execute() throws Exception {
//System.out.println("userName="+userName+"and userPassword="+userPassword);
state = userService.getUser(userName, userPassword);
if (state == -1) {
System.out.println("用户名不存在!");
this.addFieldError(userName, "*该用户名不存在!");
return ERROR;
} else if (state == -2) {
System.out.println("密码不正确");
this.addFieldError(userPassword, "*您输入的密码不正确,请重新输入");
return ERROR;
}
//System.out.println("userName="+userName+"and userPassword="+userPassword);
return SUCCESS;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
RegisterAction.java
package com.ssh.action;
import com.opensymphony.xwork2.ActionSupport;
import com.ssh.service.UserService;
public class RegisterAction extends ActionSupport {
private UserService userService;
private String userName2;
private String userPassword2;
public String execute() throws Exception{
//System.out.println("-----UserService...execute()-----");
if(userService.isExist(userName2, userPassword2)){
// System.out.println("该用户名已经存在!");
this.addFieldError(userName2, "*用户名已经存在,请重新注册!");
return ERROR;
}else{
// System.out.println("该用户名不存在,成功注册!");
userService.saveUser(userName2, userPassword2);
this.addFieldError(userName2, "*哈哈!注册成功!请登录!");
return SUCCESS;
}
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public String getUserName2() {
return userName2;
}
public void setUserName2(String userName2) {
this.userName2 = userName2;
}
public String getUserPassword2() {
return userPassword2;
}
public void setUserPassword2(String userPassword2) {
this.userPassword2 = userPassword2;
}
}
然后配置一下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>
<constant name="struts.il8n.encoding" value="utf-8"></constant>
<package name="userManage" extends="json-default">
<action name="userAction" class="com.ssh.action.UserAction"> <!-- 这个地方的class中的action name要与applicationContext中的action的id相同 -->
<result name="error" >/index.jsp</result>
<result name="success">/home.jsp</result>
</action>
<action name="registerAction" class="com.ssh.action.RegisterAction">
<result name="success">/index.jsp</result>
<result name="error">/index.jsp</result>
</action>
</package>
</struts>
home.jsp就随意了。
最后配置一下applicationContext.xml:
applicationContext.xml:
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="jdbc:mysql://localhost:3306/text"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/ssh/bean/User.hbm.xml</value></list>
</property></bean>
<bean id="userDaoImpl" class="com.ssh.daoimpl.UserDaoImpl" scope="prototype">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="com.ssh.serviceimpl.UserServiceImpl" scope="prototype">
<property name="userDaoImpl" ref="userDaoImpl"></property>
</bean>
<bean id="userAction" class="com.ssh.action.UserAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
<bean id="registerAction" class="com.ssh.action.RegisterAction" scope="prototype">
<property name="userService" ref="userService"></property>
</bean>
</beans>
另外说明几点,有时候toncat启动部署的时候会出错,需要将web.xml中的 url-pattern 的 *.action 改为 /* :
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</filter>
网页中userName 数据传输顺序: index.jsp(form action=xxx) =====> struts.xml(action class=xxxxx) ===========> com.ssh.action(xxxAction.java) =========>com.ssh.service, com.ssh.serviceimpl===========>com.ssh.dao, com.ssh.daoimpl (其中一直会有com.ssh.bean 中User ) 还需要applicationContex.xml的整体调控