SSM框架搭建之傳統方式(一)

SSM框架搭建之傳統方式

Jdk安裝配置請參照此博客
eclipse配置jdk/tomcat參照此博客。css

打開eclipse,點擊File--New—Dynamic Web Projecthtml

SSM框架搭建之傳統方式(一)

點擊Finish便可完成web項目的建立 按照此目錄進行文件建立java

SSM框架搭建之傳統方式(一)

1.導入以下圖所示jar包
只用導入一種數據源便可,這裏有c3p0、druid、dbcp三種鏈接池mysql

SSM框架搭建之傳統方式(一)

2.datasource.properties
mysql8的驅動名稱不是com.mysql.jdbc.Driver;格外注意url的寫法web

datasource.driverClassName=com.mysql.cj.jdbc.Driver
datasource.userName=root
datasource.userPassword=123456
datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC

3. log4j.propertiesspring

#定義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

#mybatis顯示SQL語句日誌配置     net.cxp.blog.dao是你的dao接口所在的包名  
#log4j.logger.org.mybatis=DEBUG
log4j.logger.com.lymn.it.mapper=DEBUG

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

4. spring-mvc.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.xsd    
                        http://www.springframework.org/schema/context    
                        http://www.springframework.org/schema/context/spring-context.xsd    
                        http://www.springframework.org/schema/mvc    
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器,此處必須排除掉@Service組件 -->
    <context:component-scan base-package="com.lymn.it.controller" />
    <!-- 會自動註冊RequestMappingHandlerMapping與RequestMappingHandlerAdapter兩個Bean,這是Spring MVC
    爲@Controller分發請求所必需的。啓動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
    <mvc:annotation-driven/>

    <!-- 視圖解析器 -->
    <!-- 定義跳轉的文件的先後綴 ,視圖模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裏的配置個人理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--對靜態資源文件的訪問 -->
    <!-- 針對springMVC的restful風格的url而言,配置了 -->
    <mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
    <mvc:resources mapping="/css/**" location="/WEB-INF/css/" />

</beans>

5.spring-mybatis.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
                        http://www.springframework.org/schema/beans/spring-beans.xsd  
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context.xsd  
                        http://www.springframework.org/schema/mvc  
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd
                        http://www.springframework.org/schema/tx
                        http://www.springframework.org/schema/tx/spring-tx.xsd
                        http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/task 
                        http://www.springframework.org/schema/task/spring-task.xsd">

    <!-- 配置包含註解的掃描路徑,可是不包括controller -->
    <context:component-scan base-package="com.lymn.it.*">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- PropertyPlaceholderConfigurer 是 BeanFactory 後置處理器的實現,也是 BeanFactoryPostProcessor 
    接口的一個實現。 容許將上下文(配置文件)中的屬性值放在另外一個單獨的標準 JavaProperties 文件中去。在 XML 文件中用相似 EL 
    表達式的 ${key} 替換指定的 properties 文件中的值 -->
    <!-- <bean id="placeHolder"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:config/datasource.properties"></property>
        多個數據源寫法
        <property name="locations">
            <list>
                <value>classpath:config/datasource1.properties</value>
                <value>classpath:config/datasource2.properties</value>
            </list>
        </property>
    </bean> -->

    <!-- Spring2.5 之後,引入了簡化的引入外部文件的方式 -->
    <context:property-placeholder location="classpath:config/datasource.properties" />
    <!-- Spring提供了的數據源,每一個鏈接請求時都新建一個鏈接 -->
     <bean id="dataSource" 
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${datasource.driverClassName}"></property>
        <property name="url" value="${datasource.url}"></property>
        <property name="username" value="${datasource.userName}"></property>
        <property name="password" value="${datasource.userPassword}"></property>
    </bean>
    <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 掃描entity包 使用別名 -->
        <property name="typeAliasesPackage" value="com.lymn.it.model"></property>
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> -->
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/lymn/it/mapper/*.xml"></property>
    </bean>
    <!-- mapper接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lymn.it.mapper" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <!-- 事務加強,這裏用的是spring提供的特性 -->
    <tx:advice id="tx" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true" />
            <tx:method name="get*" read-only="true" />
            <tx:method name="has*" read-only="true" />
            <tx:method name="count*" read-only="true" />
            <tx:method name="search*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="pc"
            expression="execution(* com.lymn.it.service.impl..*.*(..))" />
        <!--把事務控制在Service層 -->
        <aop:advisor pointcut-ref="pc" advice-ref="tx" />
    </aop:config>

</beans>

6.model--Userexpress

package com.lymn.it.model;

public class User {
        private Integer userid;
        private String username;
        private String password;
        private String email;
        private String phone;
        private Integer status;
        private String code;
        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 getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
        public Integer getStatus() {
            return status;
        }
        public void setStatus(Integer status) {
            this.status = status;
        }
        public String getCode() {
            return code;
        }
        public void setCode(String code) {
            this.code = code;
        }
        @Override
        public String toString() {
            return "User [userid=" + userid + ", username=" + username + ", password=" + password + ", email=" + email
                    + ", phone=" + phone + ", status=" + status + ", code=" + code + "]";
        }

}

7.mapper-UserMapper.javaapache

package com.lymn.it.mapper;

import java.util.List;

import com.lymn.it.model.User;

public interface UserMapper {
    public List<User> getAllUsers();

    public User getUserById(int userid);

    public boolean deleteUserById(int userid);

    public boolean insertUser(User user);

    public boolean updateUserById(User user);
}

mapper-UserMapper.java

<?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.lymn.it.mapper.UserMapper">
    <select id="getAllUsers" resultType="User">
        SELECT * FROM user
    </select>
    <select id="getUserById" parameterType="int" resultType="User">
        SELECT *
        FROM user WHERE userid = #{userid}
    </select>
    <insert id="insertUser" parameterType="User"
        useGeneratedKeys="true" keyProperty="userid">
        INSERT INTO s_user(username,password,email,phone)
        VALUES(#{username},#{password},#{email},#{phone})
    </insert>
    <update id="updateUserById" parameterType="User">
        UPDATE user SET username = #{username},
                          password = #{password},
                          email = #{email},
                          phone = #{phone}
                          WHERE 
                          userid = #{userid}
    </update>
    <delete id="deleteUserById" parameterType="int">
        DELETE  FROM user WHERE userid = #{userid}
    </delete>
</mapper>

8.service-UserService.java

package com.lymn.it.service;

import java.util.List;

import com.lymn.it.model.User;

public interface UserService {
    public List<User> getAllUsers();

    public User getUserById(int userid);

    public boolean deleteUserById(int userid);

    public boolean insertUser(User user);

    public boolean updateUserById(User user);
}

service-UserServiceImpl.java

package com.lymn.it.service.impl;

import java.util.List;

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

import com.lymn.it.mapper.UserMapper;
import com.lymn.it.model.User;
import com.lymn.it.service.UserService;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public List<User> getAllUsers() {
        return userMapper.getAllUsers();

    }

    @Override
    public User getUserById(int userid) {
        return userMapper.getUserById(userid);

    }

    @Override
    public boolean deleteUserById(int userid) {
        return userMapper.deleteUserById(userid);

    }

    @Override
    public boolean insertUser(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public boolean updateUserById(User user) {
        return userMapper.updateUserById(user);
    }

}

9.controller-UserController

package com.lymn.it.controller;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.lymn.it.model.User;
import com.lymn.it.service.UserService;

@Controller
public class UserController {
    @Autowired
    UserService userService;
    Logger logger=Logger.getLogger(UserController.class);
    @RequestMapping(value="/user")
    public String user(Map<Object,Object> map) {
        logger.info("查詢全部用戶數據");
        List<User> userList =  userService.getAllUsers();
        map.put("user", userList);
        logger.info("查詢完畢,返回頁面");
        return "user";
    }

}

10.web.xml添加以下配置

<!-- spring容器配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <!-- 注意,spring加載配置文件 -->
        <param-value>
            classpath:config/spring-mybatis.xml
        </param-value>
    </context-param>
    <!-- spring容器監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--springMVC的核心分發器 -->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 指定Spring的配置文件 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </init-param>
        <!-- 啓動加載一次 -->  
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <!-- 此處能夠能夠配置成*.do 適配Struts的習慣-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 防止Spring內存溢出監聽器 -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>

    <!-- 解決工程編碼過濾器 -->
    <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>
         <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

11.jsp/user.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User</title>
</head>
<body>
    <h1>${requestScope.user}</h1>
</body>

12.建數據庫test,而後在建立表

CREATE TABLE `user` (
  `userid` INT(11) NOT NULL AUTO_INCREMENT,
  `username` VARCHAR(255) DEFAULT NULL,
  `password` VARCHAR(255) DEFAULT NULL,
  `email` VARCHAR(255) DEFAULT NULL,
  `phone` VARCHAR(255) DEFAULT NULL,
  `status` VARCHAR(255) NOT NULL DEFAULT '0',
  `code` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=INNODB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8;

訪問以下圖表示配置成功
SSM框架搭建之傳統方式(一)

相關文章
相關標籤/搜索