MyEclipse:SSH快速搭建
Posted 糖goblin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyEclipse:SSH快速搭建相关的知识,希望对你有一定的参考价值。
【MyEclipse】:SSH快速搭建
ssh搭建的前提,需要掌握 spring,struts2,hibernate
这是一种快速搭建的方式,框架基本上都是自动生成好。
如有不足之处,请指教!
@
目录
1、数据库表
create table users(
uid INT auto_increment PRIMARY KEY,
uname VARCHAR(20) NOT NULL,
usex VARCHAR(2) NOT NULL,
ubirth TIMESTAMP DEFAULT CURRENT_TIMESTAMP not null
)DEFAULT CHARSET=utf8;
insert into users values(null,"张珊",\'女\',DEFAULT);
insert into users values(null,"李四",\'男\',DEFAULT);
insert into users values(null,"王五",\'男\',DEFAULT);
insert into users values(null,"赵柳",\'女\',DEFAULT);
2、新建项目
2.1、创建一个web project项目
2.2、导入spring
spring 添加玩以后,会多出很多的jar 包和一个配置文件 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.0.xsd">
</beans>
2.3、添加 struts2
导入 struts2
项目结构
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>
</struts>
2.4、添加 Hibernate
- 导入hibernate
- Hibernate 的配置自动添加到 applicationContext.xml 文件中
<!-- 连接池 -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/myschool">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></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>
</bean>
2.5、逆向工程,生成实体类
- 连接 mysql 数据库
- 导入数据库表
项目结构
- 在 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"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/myschool">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></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/pojo/Users.hbm.xml</value></list>
</property>
</bean>
<!-- 事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 注解 -->
<tx:annotation-driven/>
<bean id="UsersDAO" class="com.ssh.pojo.UsersDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
注意:
2.6、配置 web.xml
- 配置 Context Params
- Filters 过滤器
-
Listeners 监听器
-
保存,web.xml就配置完了
-
部署到Tomcat服务器上,无报错,即搭建成功!
2.7、数据编写
-
建立基本结构
- com.ssh.action
- com.ssh.dao
- com.ssh.pojo
- com.ssh.service
-
实体类和dao层
实体类
public class Users implements java.io.Serializable {
private Integer uid;
private String uname;
private String usex;
private Timestamp ubirth;
//get/set方法,有参无参构造函数,toString();
}
dao层
package com.ssh.dao;
import java.sql.Timestamp;
import java.util.List;
import org.hibernate.LockMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.ssh.pojo.Users;
public class UsersDAO extends HibernateDaoSupport {
private static final Logger log = LoggerFactory.getLogger(UsersDAO.class);
// property constants
public static final String UNAME = "uname";
public static final String USEX = "usex";
protected void initDao() {
// do nothing
}
public void save(Users transientInstance) {
log.debug("saving Users instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(Users persistentInstance) {
log.debug("deleting Users instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Users findById(java.lang.Integer id) {
log.debug("getting Users instance with id: " + id);
try {
Users instance = (Users) getHibernateTemplate().get(
"com.ssh.pojo.Users", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Users instance) {
log.debug("finding Users instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Users instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Users as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByUname(Object uname) {
return findByProperty(UNAME, uname);
}
public List findByUsex(Object usex) {
return findByProperty(USEX, usex);
}
public List findAll() {
log.debug("finding all Users instances");
try {
String queryString = "from Users";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Users merge(Users detachedInstance) {
log.debug("merging Users instance");
try {
Users result = (Users) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Users instance) {
log.debug("attaching dirty Users instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Users instance) {
log.debug("attaching clean Users instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static UsersDAO getFromApplicationContext(ApplicationContext ctx) {
return (UsersDAO) ctx.getBean("UsersDAO");
}
}
-
Users.hbm.xml
注意:里面的
not null = ‘true’
需要删除,不然做曾删改时会报错!如果没删传对象时所有属性都不能为空!
<?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">
<hibernate-mapping>
<class name="com.ssh.pojo.Users" table="users" catalog="myschool">
<id name="uid" type="java.lang.Integer">
<column name="uid" />
<generator class="identity" />
</id>
<property name="uname" type="java.lang.String">
<column name="uname" length="20" />
</property>
<property name="usex" type="java.lang.String">
<column name="usex" length="2" />
</property>
<property name="ubirth" type="java.sql.Timestamp">
<column name="ubirth" length="19"/>
</property>
</class>
</hibernate-mapping>
-
编写Service层的接口和实现类
接口
package com.ssh.service;
import java.util.List;
import com.ssh.pojo.Users;
public interface UsersService {
//查询所有用户
List<Users> queryUsersList();
//单值查询
Users queryUsers();
//添加
void addUsers(Users users);
//修改
void updateUsers(Users users);
//删除
void delUsers(Users users);
}
实现类
package com.ssh.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.ssh.dao.UsersDAO;
import com.ssh.pojo.Users;
public class UsersServiceImpl implements UsersService {
private UsersDAO usersDAO;
public void setUsersDAO(UsersDAO usersDAO) {
this.usersDAO = usersDAO;
}
//添加
@Autowired
@Transactional
public void addUsers(Users users) {
usersDAO.save(users);
}
//删除
@Autowired
@Transactional
public void delUsers(Users users) {
usersDAO.delete(users);
}
//单值查询
public Users queryUsers(int uid) {
return (Users) usersDAO.findById(uid);
}
//查询所有
public List<Users> queryUsersList() {
return usersDAO.findAll();
}
//修改
@Autowired //自动装配
@Transactional //开启事务行为,曾删改
public void updateUsers(Users users) {
usersDAO.merge(users);
}
}
- 编写action层
package com.ssh.action;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.ssh.pojo.Users;
import com.ssh.service.UsersService;
public class UsersAction extends ActionSupport {
private UsersService usersService;
private Users users;
private List<Users> list;
private int uid;
//get/set方法
public void setUsersService(UsersService usersService) {
this.usersService = usersService;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return super.execute();
}
//查询所有用户
public String list() throws Exception {
list = usersService.queryUsersList();
return "list";
}
//单值查询
public String query() throws Exception {
Users user = usersService.queryUsers(uid);
//获取session会话
HttpSession session = ServletActionContext.getRequest().getSession();
//给session赋值
session.setAttribute("user", user);
//返回
return "query";
}
//添加
public String add() throws Exception {
usersService.addUsers(users);
return list();
}
//删除
public String del() throws Exception {
usersService.delUsers(users);
return list();
}
//修改
public String update() throws Exception {
usersService.updateUsers(users);
return list();
}
}
- 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"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/myschool">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></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/pojo/Users.hbm.xml</value></list>
</property>
</bean>
<!-- 事务 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- 注解 -->
<tx:annotation-driven/>
<!-- dao层 -->
<bean id="usersDAO" class="com.ssh.dao.UsersDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- service层 -->
<bean id="usersService" class="com.ssh.service.UsersServiceImpl">
<property name="usersDAO" ref="usersDAO"/>
</bean>
<!-- action层 -->
<bean id="usersAction" class="com.ssh.action.UsersAction">
<property name="usersService" ref="usersService"/>
</bean>
</beans>
- 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>
<package name="users" namespace="/users" extends="struts-default">
<action name="usersAction_*" method="{1}" class="com.ssh.action.UsersAction">
<result name="list">/list.jsp</result>
<result name="query">/update.jsp</result>
</action>
</package>
</struts>
3、视图层
index.jsp
<h1><a href="javascript:location.href=\'users/usersAction_list\'">去list.jsp</a></h1>
list.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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 \'list.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">
-->
</head>
<body>
<table align="center" cellpadding="1" cellspacing="1" border="1" width="600px;">
<caption><h1>用户信息</h1></caption>
<caption><h3><a href="add.jsp">添加用户</a></h3></caption>
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>生日</th>
<th>操作</th>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td>${user.uid }</td>
<td>${user.uname }</td>
<td>${user.usex }</td>
<td>${user.ubirth }</td>
<td>
<a href="javaScript:location.href=\'users/usersAction_query?uid=${user.uid}\'">修改</a>
 
<a href="javaScript:delUsers(${user.uid})">删除</a>
</td>
</tr>
</c:forEach>
</table>
<script>
function delUsers(id){
if(confirm("确认删除吗?")){
location.href="users/usersAction_del?users.uid="+id;
}
}
</script>
</body>
</html>
add.jsp
<form action="users/usersAction_add" method="post">
<table align="center" cellpadding="1" cellspacing="1" border="1" width="300px;">
<caption><h3>添加用户</h3></caption>
<tr>
<th>姓名</th>
<td><input name="users.uname" type="text"/></td>
</tr>
<tr>
<th>性别</th>
<td>
<input name="users.usex" type="radio" value="男" checked="checked"/>男 
<input name="users.usex" type="radio" value="女"/>女
</td>
</tr>
<tr>
<th>生日</th>
<td><input name="users.ubirth" type="text"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/> 
<input type="button" value="返回" onclick="javaScript:history.back()"/>
</td>
</tr>
</table>
</form>
update.jsp
<form action="users/usersAction_update" method="post">
<table align="center" cellpadding="1" cellspacing="1" border="1" width="300px;">
<caption><h3>添加用户</h3></caption>
<tr>
<input type="hidden" name="users.uid" value="${user.uid}"/>
<th>姓名</th>
<td><input name="users.uname" type="text" value="${user.uname}"/></td>
</tr>
<tr>
<th>性别</th>
<td>
<input name="users.usex" type="radio" value="男" checked="checked" />男 
<input name="users.usex" type="radio" value="女" ${user.usex==\'女\'?\'checked\':\'\'} />女
</td>
</tr>
<tr>
<th>生日</th>
<td><input name="users.ubirth" type="text" value="${user.ubirth}"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="提交"/> 
<input type="button" value="返回" onclick="javaScript:history.back()"/>
</td>
</tr>
</table>
</form>
执行效果:
最终目录结构:
以上是关于MyEclipse:SSH快速搭建的主要内容,如果未能解决你的问题,请参考以下文章
myeclipse搭建SSH(Struts+spring+hibernate)由maven管理
框架 day38 SVN安装及使用,SSH练习项目CRM,环境搭建(myeclipse hibernate 反转引擎生成PO和映射)