建立SSM心得

SSM所依賴的jar包html

<properties>
  <!-- spring版本號 -->
  <spring.version>4.0.2.RELEASE</spring.version>
  <!-- mybatis版本號 -->
  <mybatis.version>3.2.6</mybatis.version>
  <!-- log4j日誌文件管理包版本 -->
  <slf4j.version>1.7.7</slf4j.version>
  <log4j.version>1.2.17</log4j.version>
</properties>

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <!-- 表示開發的時候引入,發佈的時候不會加載此包 -->
    <scope>test</scope>
  </dependency>
  <!-- spring核心包 -->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-oxm</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <!-- mybatis核心包 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>
  <!-- mybatis/spring包 -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.2.2</version>
  </dependency>
  <!-- 導入java ee jar 包 -->
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
  </dependency>
  <!-- 導入Mysql數據庫連接jar包 -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.30</version>
  </dependency>

  <!-- 數據源 c3p0 -->
  <dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5-pre8</version>
  </dependency>
  <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
  <dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.2.2</version>
  </dependency>
  <!-- JSTL標籤類 -->
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency>
  <!-- 日誌文件管理包 -->
  <!-- log start -->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
  </dependency>


  <!-- 格式化對象,方便輸出日誌 -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.1.41</version>
  </dependency>


  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>

  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <!-- log end -->
  <!-- 映入JSON -->
  <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.13</version>
  </dependency>
  <!-- 上傳組件包 -->
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>
  <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
  </dependency>


</dependencies>

 

配置信息從後往前來弄:java

jdbc.propertiesmysql

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://125.221.225.113:3306/test
username=demao
password=demao
#定義初始鏈接數
initialSize=0
#定義最大鏈接數
maxActive=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWait=60000

 

log4j.propertiesweb

#定義LOG輸出級別
log4j.rootLogger=INFO,Console,File
#定義日誌輸出目的地爲控制檯
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#能夠靈活地指定日誌輸出格式,下面一行是指定具體的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到達指定尺寸的時候產生一個新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定輸出目錄
log4j.appender.File.File = logs/ssm.log
#定義文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 輸出因此日誌,若是換成DEBUG表示輸出DEBUG以上級別日誌
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

 

mybatis-config.xmlspring

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 經過別名簡化對類的使用 -->
    <typeAliases>
        <!-- 經過package, 能夠直接指定package的名字, mybatis會自動掃描你指定包下面的javabean, 而且默認設置一個別名,默認的名字爲非限定類名來做爲它的別名。 -->
        <package name="com.alibaba.entity" />
    </typeAliases>
</configuration>

 

spring-mybatis.xmlsql

<?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:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-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/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
   <!-- 自動掃描 -->
   <context:component-scan base-package="com.alibaba" />
   <!-- 引入配置文件 -->
   <bean id="propertyConfigurer"
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="location" value="classpath:jdbc.properties" />
   </bean>

   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
      destroy-method="close">
      <property name="driverClassName" value="${driver}" />
      <property name="url" value="${url}" />
      <property name="username" value="${username}" />
      <property name="password" value="${password}" />
      <!-- 初始化鏈接大小 -->
      <property name="initialSize" value="${initialSize}"></property>
      <!-- 鏈接池最大數量 -->
      <property name="maxActive" value="${maxActive}"></property>
      <!-- 鏈接池最大空閒 -->
      <property name="maxIdle" value="${maxIdle}"></property>
      <!-- 鏈接池最小空閒 -->
      <property name="minIdle" value="${minIdle}"></property>
      <!-- 獲取鏈接最大等待時間 -->
      <property name="maxWait" value="${maxWait}"></property>
   </bean>

   <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
   <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- 自動掃描mapping.xml文件 -->
      <property name="mapperLocations" value="classpath:cn/mob/jekin/dao/*.xml"></property>
   </bean>

   <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <property name="basePackage" value="com.cn.hnust.dao" />
      <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>

   <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
   <bean id="transactionManager"
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource" />
   </bean>

</beans>

 

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:context="http://www.springframework.org/schema/context"
       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.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">


    <!-- 配置數據源,記得去掉myBatis-config.xml的數據源相關配置 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true" />
        <property name="user" value="root" />
        <property name="password" value="root" />
    </bean>
    <!-- 配置session工廠 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:myBatis-config.xml" />
        <!--配置掃描式加載SQL映射文件,記得去掉mybatis-config配置-->
        <property name="mapperLocations" value="classpath:com/alibaba/dao/*.xml"/>

    </bean>

    <!-- 配置事務管理器,管理數據源事務處理 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 配置事務通知 -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 默認只處理運行時異常,可加rollback-for="Exception/Throwable"等處理全部異常或包括錯誤 -->
            <tx:method name="insert*" propagation="REQUIRED"
                       rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED"
                       rollback-for="Exception" />
            <tx:method name="delete*" propagation="REQUIRED"
                       rollback-for="Exception" />
            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <!-- 配置切面織入的範圍,後邊要把事務邊界定在service層 -->
    <aop:config>
        <aop:advisor advice-ref="advice"
                     pointcut="execution(* com.alibaba.service.impl.*.*(..))" />
    </aop:config>
    <!-- 配置SessionTemplate,已封裝了繁瑣的數據操做 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

    <!-- 自動掃描組件,要把controller去除,他們是在spring-mvc.xml中配置,若是不去除會影響事務管理。 -->
    <context:component-scan base-package="com.alibaba">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 配置 轉換器,對於在basePackage設置的包(包括子包)下的接口類,
    若是接口類的全類名在Mapper.xml文件中和定義過命名空間一致,
     將被轉換成spring的BEAN,在調用
        的地方經過@Autowired方式將能夠注入接口實例 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        <property name="basePackage" value="cn.mob.jekin.dao" />
    </bean>
</beans>

 

spring-mvc.xmlexpress

<?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:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans-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/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
   <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器 -->
   <context:component-scan base-package="com.alibaba.controller" />
   <!--避免IE執行AJAX時,返回JSON出現下載文件 -->
   <bean id="mappingJacksonHttpMessageConverter"
      class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
      <property name="supportedMediaTypes">
         <list>
            <value>text/html;charset=UTF-8</value>
         </list>
      </property>
   </bean>
   <!-- 啓動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
   <bean
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="messageConverters">
         <list>
            <ref bean="mappingJacksonHttpMessageConverter" />  <!-- JSON轉換器 -->
         </list>
      </property>
   </bean>
   <!-- 定義跳轉的文件的先後綴 ,視圖模式配置-->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>
   
   <!-- 配置文件上傳,若是沒有使用文件上傳能夠不用配置,固然若是不配,那麼配置文件中也沒必要引入上傳組件包 -->
   <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 默認編碼 -->
        <property name="defaultEncoding" value="utf-8" />  
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />  
        <!-- 內存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />  
    </bean> 

</beans>

 

下面就要根據這些配置文件中的包來---建立這些這些包apache

BaseActionjson

package com.alibaba.control;
  
import javax.annotation.Resource;  
import javax.servlet.ServletContext;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
@Controller  
@RequestMapping("/base")  
public class BaseAction {  
  
    @Resource  
    ServletContext application;  
  
    // 方法參數folder經過@PathVariable指定其值能夠從@RequestMapping的{folder}獲取,同理file也同樣  
    @RequestMapping("/goURL/{folder}/{file}")  
    public String goURL(@PathVariable String folder, @PathVariable String file) {  
        System.out.println("goURL.folder|file===" + folder + "/" + file);  
        return "forward:/WEB-INF/" + folder + "/" + file + ".jsp";  
    }  
}

UserAction

package com.alibaba.control;
  
import javax.annotation.Resource;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpSession;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
import com.alibaba.entity.User;
import com.alibaba.modal.UserService;
  
@Controller  
@RequestMapping("/user")  
public class UserAction extends BaseAction {  
      
    @Resource  
    private UserService userService;  
      
    @RequestMapping(value="/login")  
    public String login(User user,HttpServletRequest request,HttpSession session){  
        System.out.println("---action.user:"+user);  
        User acc= userService.login(user);  
        if(acc!=null){  
            //存session  
            session.setAttribute("user", acc);  
            return "forward:/main.jsp";  
        }else{  
            request.setAttribute("msg", "用戶名或密碼錯誤!");  
            return "forward:/login.jsp";  
        }  
          
    }  
}

BaseMapper

package com.alibaba.dao;

public interface BaseMapper<T> {
    //添加單個對象  
    public int insert(T entity);  
      
    //修改單個對象  
    public int update(T entity);  
      
    //刪除單個對象  
    public int delete(T entity);  
      
    //查詢單個對象  
    public T select(T entity);  
}

UserMapper

package com.alibaba.dao;
  
import com.alibaba.entity.User;

public interface UserMapper extends BaseMapper<User> {
    public User login(User user);  
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.alibaba.dao.UserMapper" >
    <resultMap id="userResultMap" type="com.alibaba.entity.User" >
        <id column="user_id" property="userId" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="user_pass" property="userPass" jdbcType="VARCHAR" />
    </resultMap>
    <!-- 用戶登錄 -->
    <select id="login" parameterType="User" resultMap="userResultMap">
        select * from user where user_name =#{userName} and user_pass =#{userPass}
    </select>

</mapper>

User

package com.alibaba.entity;
  
import java.io.Serializable;  
  
public class User implements Serializable{  
    private Integer userId;  
    private String userName;  
    private String userPass;  
      
    public Integer getUserId() {  
        return userId;  
    }  
    public void setUserId(Integer userId) {  
        this.userId = userId;  
    }  
    public String getUserName() {  
        return userName;  
    }  
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
    public String getUserPass() {  
        return userPass;  
    }  
    public void setUserPass(String userPass) {  
        this.userPass = userPass;  
    }  
      
      
}

BaseService

package com.alibaba.modal;
  
public interface BaseService<T> {  
    // 添加單個對象  
    public int insert(T entity) throws Exception;  
  
    // 修改單個對象  
    public int update(T entity) throws Exception;  
  
    // 刪除單個對象  
    public int delete(T entity) throws Exception;  
  
    // 查詢單個對象  
    public T select(T entity);  
}

UserService

package com.alibaba.modal;
  
import com.alibaba.entity.User;

public interface UserService extends BaseService<User> {
    public User login(User user);  
}

UserServiceImpl

package com.alibaba.modal.impl;
  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.stereotype.Service;  
  
import com.alibaba.dao.UserMapper;
import com.alibaba.entity.User;
import com.alibaba.modal.UserService;
  
@Service("userService")  
public class UserServiceImpl implements UserService{  
      
    @Autowired  
    private UserMapper userMapper;


    public User login(User user) {
        return null;
    }

    public int insert(User entity) throws Exception {
        return 0;
    }

    public int update(User entity) throws Exception {
        return 0;
    }

    public int delete(User entity) throws Exception {
        return 0;
    }

    public User select(User entity) {
        return null;
    }
}

 

web.xml

<?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">
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>

  <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>
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

 

Tomcat插件

<plugins>
  <!-- 配置Tomcat插件 ,用於啓動項目 -->
  <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <!--若是不設置,則默認爲貓的自定義端口,項目路徑爲http://localhost:默認端口/項目名  -->
    <configuration>
      <!--若是端口號改成8081:那麼訪問的時候路徑的端口就要寫成8081,不然404  -->
      <port>8080</port>
      <!-- 若是設置爲/,則項目了路徑爲http://localhost:端口號 /-->
      <!-- 若是設置爲/123,則項目了路徑爲http://localhost:端口號/123 -->
      <path>/123</path>
    </configuration>
  </plugin>
</plugins>
相關文章
相關標籤/搜索