该例利用myeclipse集成开发工具快速开发了一个用户登录功能的web项目,用户可以根据需求基于框架继续开发。
开发环境如下:
1.myeclipse2013
2.tomcat7.0
3.jdk7
4.mysql5.6
一、快速生成SSH过程
1、首先利用数据库工具创建一张用户登录表,为后面连接数据库做准备。在这里我用的是navicat for mysql可视化工具建表,用户登录表如下:
2、在myeclipse中新建一个web project ,名称自己写,在src下分别创建如下几种包:
3、选择项目名,右键选择myeclipse->project facets[capabilities]->install apache struts(2.x) facets,如下生成struts2框架结构:
点开之后,如下:
点击next后,根据需求选择Action过滤模式,在这里我选择的是“/*”,如下:
继续点击next,在这里要注意勾选最下面enable project specific advanced configuration,勾选之后才能选择core,取消勾选antlr-2.7.2.jar,否则由于该版本比较低,造成java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I错误。操作如下:
点击finished完成对struts2的自动生成。
4、选择项目名,右键选择myeclipse->project facets[capabilities]->install spring facets,如下生成spring3框架结构:
点击next,如下:
点击finished完成对spring3的自动生成。
5、点击window->open perspective->myeclipse database explore,进入数据库视图:
在myeclipse derby上右键 选择new:
,出现:
,注意红线内的内容,填写后点击TestDriver看是否能连接成功,连接成功后点击finish即可。这里完成的是与数据库的连接。
6、返回Java ee视图,选择项目名,右键选择myeclipse->project facets[capabilities]->install hibernate facets,如下生成hibernate4框架结构:
点击next,出现如下:
点击finish,完成hibernate4的自动构造。
7、返回DB explore视图,创建数据库表与bean类的hibernate映射,如下:
点击finish,完成自动构造映射的向导
至此,完成了对SSH框架的基本生成,接下来需要实现相关功能类与一些文件的具体配置。
二、前后台简单登录功能代码及struts和spring文件的配置
1、登录页面index.jsp
<body>
<form method="post" action="login">
用户名:<input name="user.userName" type="text"/>
密码:<input name="user.password" type="password"/><br>
<input name="submit" type="submit" value="submit"/>
<input name="reset" type="reset" value="reset"/>
</form>
</body>
2、LoginAction.java
public class LoginAction extends ActionSupport {
/** * */
private Myuser user;
private UserManager userManager;
public Myuser getUser() {
return user;
}
public void setUser(Myuser user) {
this.user = user;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
private static final long serialVersionUID = 1L;
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
if(userManager.userLogin(user))
return "success";
else
return "error";
}
}
3、Myuser.java 类与Myuser.hbm.xml为配置SSH时自动生成,dao包和service包分别是daoImp包和serviceImp包对应类的接口,如UserBaseDao:
import com.shijing.bean.Myuser;
public interface UserBaseDao {
boolean checkUserLogin(Myuser user);
}
4、UserDaoImp.java
public class UserDaoImp implements UserBaseDao{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public boolean checkUserLogin(Myuser user) {
// TODO Auto-generated method stub
Session session=getMySession();
String queryString="from Myuser user where userName=:userName and password=:password";
Query query=session.createQuery(queryString);
query.setParameter("userName", user.getUserName());
query.setParameter("password", user.getPassword());
System.out.println(user.getPassword());
List<Myuser>list=query.list();
System.out.println(list);
if(!list.isEmpty())
return true;
else
return false;
}
public Session getMySession() throws HibernateException {
// SessionFactory sessionFactory=null;
// Configuration configuration=new Configuration().configure();
// ServiceRegistryBuilder builder=new ServiceRegistryBuilder().applySettings(configuration.getProperties());
// ServiceRegistry registry=builder.buildServiceRegistry();
// sessionFactory=configuration.buildSessionFactory(registry);
if (sessionFactory.getCurrentSession() != null) {
return sessionFactory.getCurrentSession();
} else {
return sessionFactory.openSession();
}
}
}
5、UserManagerImp.java
public class UserManagerImp implements UserManager {
private UserBaseDao baseDao;
public void setBaseDao(UserBaseDao baseDao) {
this.baseDao = baseDao;
}
@Override
public boolean userLogin(Myuser user) {
// TODO Auto-generated method stub
if(baseDao.checkUserLogin(user))
return true;
else {
return false;
}
}
}
6、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="default" namespace="/" extends="struts-default">
<action name="login" class="loginAction">
<result name="error">/index.jsp</result>
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
7、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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- 定义数据源的信息 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="jdbcUrl">
<value>jdbc:mysql://localhost/test</value>
</property>
<property name="user">
<value>root</value>
</property>
<property name="password">
<value>mysql</value>
</property>
<property name="maxPoolSize">
<value>80</value>
</property>
<property name="minPoolSize">
<value>1</value>
</property>
<property name="initialPoolSize">
<value>1</value>
</property>
<property name="maxIdleTime">
<value>20</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation" value="classpath:hibernate.cfg.xml">
</property>
<property name="dataSource">
<ref local="dataSource" />
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="aa" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" read-only="true" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut expression="execution(* com.shijing.daoImp.*.*(..))" id="my" />
<aop:advisor advice-ref="aa" pointcut-ref="my" />
</aop:config>
<bean id="baseDao" class="com.shijing.daoImp.UserDaoImp">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userManager" class="com.shijing.serviceImp.UserManagerImp">
<property name="baseDao" ref="baseDao"></property>
</bean>
<bean id="loginAction" class="com.shijing.action.LoginAction">
<property name="userManager" ref="userManager"></property>
</bean>
</beans>
8、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns: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_3_0.xsd" version="3.0">
<display-name>TestSSH</display-name>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
最终项目中的文件如下:
启动项目无误后,输入与数据库用户登录表myuser相匹配的用户名密码后,可以成功跳转到success.jsp页面,大家试试吧!
三、容易遇到的问题
1、antlr-2.7.2jar包低版本冲突问题,会报java.lang.NoSuchMethodError: antlr.collections.AST.getLine()I这样的错误,所以在创建struts2时一定取消勾选antlr-2.7.2.jar的选择。
2、404 No result defined for action xxx.xxxAction and result success,我在初次配置SSH时就遇到这样的错误,解决方法是在struts.xml的package里面增加 namespace=”/” 告诉系统是从根本录寻找。
3、transactionManager的错误,这类错误主要是spring文件中的配置错误,大家可以按照上面提供的注入方法或者@Transacitonal注解+的办法来解决事务管理的问题。