SSM(struts2+spring3+Mybatis3)框架搭建(2014-2015<6>)

数据库用的是:mysql5.6

服务器用的是:tomcat7.0

代码编译器:MyEclipse2014

jdK:1.6及以上

第一步:数据库表的创建

USE `test`;

/*Table structure for table `person` */

DROP TABLE IF EXISTS `person`;

CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

第二步:下载相应架包

 

百度网盘下载连接:http://pan.baidu.com/s/1eQ0AVsA

第三步:创建web项目(名字自定义)

第四步:搭建Mybatis

1、数据库配置xml文件(文件位置位于src同级目录下)

2、MyBatis Generator 插件的安装

 百度网盘下载:http://pan.baidu.com/s/1kT88lZx

下载压缩包解压之后将下面两个文档里面的文件对应拷贝到MyEclipse安装目录下的同名目录里就行了。

重启MyEclipse之后项目右键——》new——》other,就可以使用MyBatis Generator插件了。

点击下一步:选择插件配置文件放置位置,如下图所示,由于本人已经建好了,所以会提示文件已存在,你只要点击finish即可。

项目源码结构如下图:

generatorConfig.xml文件具体配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration >
<!-- 引入数据库文件 -->
<properties resource="jdbc.properties"/>
<!-- 此处指定生成针对MyBatis3的DAO -->
  <context id="context1"  targetRuntime="MyBatis3">
<!-- jdbc连接信息 -->
    <jdbcConnection driverClass="${driverClassName}"  
    connectionURL="${url}" 
    userId="${username}" password="${password}" />
   <!-- 生成entity对象  targetProject为: 项目名称 -->
    <javaModelGenerator targetPackage="org.mb.entity" targetProject="MB2" />
    <!-- 生成用于查询的Example对象 -->
    <sqlMapGenerator targetPackage="org.mb.mapper" targetProject="MB2" />
    <!-- 生成DAO的类文件以及配置文件 -->
    <javaClientGenerator targetPackage="org.mb.dao" targetProject="MB2" type="XMLMAPPER" />
    <!-- 想要生成的数据库表,自动化工具会根据该表的结构生成相应的vo对象 -->
    <table schema="" tableName="person" >
    </table>
  </context>
</generatorConfiguration>

 

然后generatorConfig.xml右键运行就可以把dao层代码自动生成好了,如下图所示:

第五步:搭建Spring

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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-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/jdbc
   http://www.springframework.org/schema/aop/spring-jdbc-3.1.xsd
">
<context:component-scan base-package="com.org" 
    use-default-filters="false">
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Controller"/>
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Service"/>
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:jdbc.properties</value>
    </property>
</bean>
<!-- 数据源配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <property name="driverClassName" value="${driverClassName}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
    <property name="maxActive" value="100"/>
    <property name="maxIdle" value="30"/>
    <property name="maxWait" value="500"/>
    <property name="defaultAutoCommit" value="true"/>
</bean>
<!-- 全局事务控制-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
 </bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"/>  
        <property name="mapperLocations" value="classpath:org/mb/mapper/*.xml"></property>
        <property name="typeAliasesPackage" value="org.mb.entity"></property>
</bean>
<!-- 自动扫描mapper,允许自动注入(根据类型匹配),不需要逐个配置mapper -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="org.mb.dao"/>
</bean>

<!-- 此处配置dao,class为一工厂类,需要注入对应的dao接口和sqlsessionfactory -->  
<bean id="personMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
       <property name="mapperInterface" value="org.mb.dao.PersonMapper"/> 
       <property name="sqlSessionFactory" ref="sqlSessionFactory"/>  
</bean>
</beans>

 

第六步:搭建struts实现登录功能

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.i18n.encoding" value="UTF-8" />  
    <!-- 开发模式 1、每次请求都会重新加载资源文件,所以当对properties文件进行修改后,下一次请求是就能够反映相应的变化。(struts.i18n.reload = true也可以达到相同的效果)
   2、每次请求的时候也会重新加载xml配置文件、验证文件等,这样可以方便调试或者修改相应的配置文件,而不用重新部署重启web服务器。(struts.configuration.xml.reload = true 也可以达到相同的效果) -->
    <constant name="struts.devMode" value="true"></constant>
    <!-- 说明Struts2的 对象池创建工厂 -->
    <constant name="struts.objectFactory" value="spring"></constant>
    <!-- 动态方法调用  -->
    <constant name="struts.enable.DynamicMethodInvocation" value="true"></constant>

    <package name="json" namespace="/test" extends="struts-default">  
        <action name="login" class="org.mb.action.LoginAction" method="execute" >  
            <result name="success" type="redirect">/success.jsp</result>  
            <result name="error">/error.jsp</result>
        </action>
    </package>
</struts>

 

 

登录功能项目源码结构如下:

loginAction.java

package org.mb.action;

import com.opensymphony.xwork2.ActionSupport;
import org.mb.service.PersonService;

public class LoginAction extends ActionSupport {  
  
    private static final long serialVersionUID = -1006252987556326592L;  
    private PersonService ps;  
    private String name;  
    private String password;  
    
    public LoginAction() {
        ps = new PersonService();
    }

    public String getName() {  
    return name;  
    }  
  
    public void setName(String name) {  
    this.name = name;  
    }  
  
    public String getPassword() {  
    return password;  
    }  
  
    public void setPassword(String password) {  
    this.password = password;  
    }  
  
    @Override  
    public String execute() throws Exception {  
    if (ps.login(name, password) != null) {  
        return SUCCESS;
    } else {  
        return ERROR;  
    }  
    }      
}

 

PersonService.java
package org.mb.service;

import org.mb.dao.PersonMapper;
import org.mb.entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonService {
    private ApplicationContext conText;
    public PersonService() {
        conText = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    
    public Person login(String username,String password)
    {
        PersonMapper personMapper  = (PersonMapper) conText.getBean("personMapper");
        Person person = personMapper.selectByPersonName(username);
        if(person != null)
        {
            if(person.getPassword().equals(password))
            {
                return person;
            }
            else
            {
                Person personnull=null;
                return personnull;
            }
        }
        else
        {
            Person personnull=null;
            return personnull;
        }
    }
}

 

 

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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">
    -->
  </head>
  <body>
    <hr>
    <div>
    <form action="<%=path%>/test/login.action" method="post">
    <label>登录名</label>    <input name="name" id="name"/><br>
    <label>密码</label>    <input name="password" id="password"/><br>
    <button type="submit">登录</button>
    </form>
    </div>
  </body>
</html>

 

最后是web项目的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"
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>MB2</display-name> <filter> <filter-name>struts-cleanup</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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>

 

至此,所有工作基本完成了,就差部署到Tomcat下了。

运行成功之后,别忘了把Tomcat的架包,放到MyEclipse项目的lib,并引用到项目中。以便于项目在移植到其他机器上时不会报缺少架包的错误, Good luck to you~

 

posted @ 2015-02-25 13:03  Enast  阅读(188)  评论(0编辑  收藏  举报