SSH框架搭建 笔记 (含spring注解驱动)

 

分类: web 开发

好久没有搭建框架了,今天整理下以前的知识,整合下SSH,没想到手生了,一时半会各种异常出来,经过一番挣扎后,终于搞出来了雏形,

下面是我做整合框架的笔记,如果大家开发过程中又遇到的情况,可以参考下

 

首先是包的结构,(命名不算正规哈~,临时写的仓促了点)

 SSH框架搭建 笔记 (含spring注解驱动)

框架是基于JAR包的基础上构建的,所以必须必备的jar包必须先下好,

如图:

 SSH框架搭建 笔记 (含spring注解驱动)

没有的可以在本文源代码里下:

 

 

搭建框架: 

修改web.xml, 加入 struts配置

 

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<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>

</web-app>

 

 

创建struts .xml

 

 <?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

<package name="struts2" extends="struts-default">

        <action name="login" class="test.action.loginAction">

            <result name="success" type="redirect">index.jsp</result>

            <result name="input">login.jsp</result>

            <result name="error">login.jsp</result>

        </action>

    </package>

 

</struts>

 接下来我们创建一个 测试用的ACTION类,loginAction

 

package test.action;

 

import com.opensymphony.xwork2.ActionSupport;

 public class LoginAction extends ActionSupport {

public String username;

public String password;

public String execute(){

if(!username.equals("admin")){

super.addFieldError("username", "用户名错误!");

return ERROR;

}

if(!password.equals("001")){

super.addFieldError("password", "密码错误!");

return ERROR;

}

return SUCCESS;

}

public void validate(){

if(username==null||username.length()==0){

super.addActionError("用户名不能为空");

}

if(password==null||password.length()==0){

super.addActionError("密码不能为空");

}

}

}

 

 

为了方便我们调试strut是否有效,我们创建一个login.jsp  用于测试

 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <title>登录</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="expires" content="0">    

  </head>

  <body>

   <s:form name="form1" action="login" >

       <s:textfield  name="username" label="username" ></s:textfield>

       <s:password name="password" label="password" ></s:password>

       <s:submit label="submit"></s:submit>

   </s:form>

   <s:actionerror/>

  </body>

</html>

 

 

修改下index.jsp 页面 登陆成功则友好提示一下

 

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

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">

  </head>

  

  <body>

    login success. <br>

  </body>

</html>

 

使用tomcat加载项目,如果启动时候不爆出异常,说明strust 基本配置完成,我们进入页面

 

 SSH框架搭建 笔记 (含spring注解驱动)

如果登陆成功则转到

Index.jsp

 SSH框架搭建 笔记 (含spring注解驱动)

 

 

 

接下配置spring 和hibernate  

 

重新回归到  web.xml

 

 

我们在其中添加,spring的相关配置

 

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

            classpath:spring/applicationContext*.xml

        </param-value>

</context-param>

<listener>

     <listener-class>

         org.springframework.web.context.ContextLoaderListener

     </listener-class>

 </listener>

 

 

创建applicationContext.xml 文件 我们在此使用注解驱动(其实说真的,spring到后面不用注解去写,也就失去它本身的意义,精髓就在于注解的简洁和易用)

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

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-2.5.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

<aop:aspectj-autoproxy /> 

<context:annotation-config></context:annotation-config>

<context:component-scan base-package="test" />

 

<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="configLocation">

<value>classpath:spring/hibernate.cfg.xml</value>

</property>

</bean>

<!-- 配置事务管理器 -->

<bean id="transactionManager"

class="org.springframework.orm.hibernate3.HibernateTransactionManager">

<property name="sessionFactory">

<ref bean="sessionFactory" />

</property>

</bean>

 

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">

<property name="sessionFactory">

<ref bean="sessionFactory" />

</property>

</bean>

 

<tx:advice id="smAdvice" transaction-manager="transactionManager" >

<tx:attributes>

<tx:method name="save*" propagation="REQUIRED" />

<tx:method name="del*" propagation="REQUIRED" />

<tx:method name="update*" propagation="REQUIRED" />

</tx:attributes>

</tx:advice>

<aop:config>

<aop:pointcut id="smMethod" expression="execution(* test.service.impl.*.*(..))" />

<aop:advisor pointcut-ref="smMethod" advice-ref="smAdvice" />

</aop:config>

</beans>

 

 

创建hibernate.cfg.xml  (用户名密码,可以自己修改一下)

 

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

       "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 

<hibernate-configuration>

    <session-factory>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>

        <property name="connection.url">jdbc:mysql://localhost/test?characterEncoding=utf-8</property>

        <property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>

        <property name="connection.username">root</property>

        <property name="connection.password">123456</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="show_sql">true</property>

        <mapping resource="test/hibernate/TUser.hbm.xml" />

    </session-factory>

</hibernate-configuration>

 

 

创建相关DTO类,以及hbm.xml 配置文件

 

TUser.java

package test.hibernate;

 public class TUser implements java.io.Serializable {

 private int userid ;

 

   

private String username;

   private String allname;

    private String address;

 

    public String getUsername() {

        return this.username;

    }

     public void setUsername(String username) {

       this.username = username;

   }

    public String getAllname() {

        return this.allname;

    }

     public void setAllname(String allname) {

       this.allname = allname;

    }

     public String getAddress() {

        return this.address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public int getUserid() {

return userid;

}

public void setUserid(int userid) {

this.userid = userid;

}

 }

 

TUser.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">

<hibernate-mapping>

<class name="test.hibernate.TUser" table="tuser">

<id name="userid" type="java.lang.Integer" column="userid">

<generator class="increment"></generator>

</id>

<property name="username" type="string" column="username" />

<property name="allname" type="string" column="allname" />

<property name="address" type="string" column="address" />

 

</class>

</hibernate-mapping>

 

由于测试关系,我们在这里就省略了DAO层,直接写service层类去测试 ,采用注解标记

 

创建相关service 接口以及实现类

IUserService.java

package test.service.imp;

import java.util.List;

import test.hibernate.TUser;

 

public interface IUserService {

public void saveTuser(TUser user);

public List<TUser> getUserById( String id);

 }

 

 

UserServiceImpl.java

package test.service.impl;

 

import java.sql.SQLException;

import java.util.List;

 

import javax.annotation.Resource;

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.HibernateTemplate;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;

import org.springframework.transaction.annotation.Transactional;

 

import test.hibernate.TUser;

import test.service.imp.IUserService;

@Service("userServiceImpl")

public class UserServiceImpl implements IUserService {

@Resource(name = "hibernateTemplate")

private HibernateTemplate hibernateTemplate;

public void saveTuser(TUser user) {

hibernateTemplate.save(user);

hibernateTemplate.flush();

}

@SuppressWarnings("unchecked")

    @Transactional(propagation=Propagation.REQUIRED) 

public List<TUser> getUserById(String id) {

final String ids = id;

//List<TUser> list = hibernateTemplate.find("from TUser where userid = ?");

List<TUser> list =hibernateTemplate.executeFind(new HibernateCallback() {

public List<TUser> doInHibernate(Session session) throws HibernateException,

SQLException {

  Query query =  (Query) session.createQuery("from TUser where userid = ? ");

  query.setString(0, ids);

return  query.list() ;

}

});

return list;

}

 

}

 

 

 

 

接下来我们写一个main 主类来测试我们的spring 和hibernate

SpringTest.java

package test.spring;

  import java.util.List;

 

import javax.annotation.Resource;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.stereotype.Component;

 

import test.hibernate.TUser;

import test.service.imp.IUserService;

 

@Component("springTest")

 public class SpringTest {

@Resource(name = "userServiceImpl")

private IUserService userService ;

public static void main( String[] args ) {

        //加载spring配置文件,初始化IoC容器

         ApplicationContext ac = new ClassPathXmlApplicationContext("spring/applicationContext.xml");

        //从容器 接管Bean

//        TUser user = (TUser) ac.getBean("TUser");

       //输出欢迎信息

//        System.out.println( "Hello:" + user.getUsername() + ";u is in " + user.getAddress() + " ; and b is  " + user.getAllname() );

        

//        SessionFactory ss = (SessionFactory) ac.getBean("sessionFactory");

//        HibernateTemplate ht = new HibernateTemplate(ss);

//        HibernateTemplate ht = (HibernateTemplate) ac.getBean("hibernateTemplate");

//        

//        List<TUser> list =    ht.find("from TUser ");

        

         SpringTest st =(SpringTest) ac.getBean("springTest");

//        TUser tu = new TUser();

//        tu.setAddress("河西");

//        tu.setAllname("河西走廊");

//        tu.setUserid(45);

//        tu.setUsername("故乡");

//        

//        st.userService.saveTuser(tu);

        List<TUser> list = st.userService.getUserById("4");//ID在数据库内找到相应的

        for(TUser xx : list){

 

        System.out.println(xx.getAddress()+"||"+xx.getAllname()+"||"+xx.getUsername());

        }

   }

 }

 

如果出现下面提示,说明你的配置已经完成

 SSH框架搭建 笔记 (含spring注解驱动)

 

 

上一篇:最佳实践:使用阿里云CDN加速OSS访问


下一篇:RedisManager使用手册(七) -- 集群伸缩