美文网首页
Java IntelliJ搭建SSM

Java IntelliJ搭建SSM

作者: 天不错啊 | 来源:发表于2018-04-28 18:12 被阅读0次

    大部分代码来自这里,好不容易找个写的不错的博客。
    这个博客真的是救了我
    https://www.cnblogs.com/hackyo/p/6646051.html

    没想到,配置这个SSM框架会如此难,用了我好几个小时,在此记录一下自己的过程。

    需要准备的环境

    1.JDK
    2.IJ idea
    3.Maven

    前面两个就不说了,说一下Maven。这个我也是第一次接触这个,弄了好长时间。在此下载(https://maven.apache.org/download.cgi
    解压到文件夹,配置环境变量就略过。

    1.配置Maven

    打开解压到的文件夹,找到conf文件修改settings.xml,修改目录
    <localRepository>E:\apache-maven-3.5.3\repo</localRepository>
    
    创建个repo目录,然后拷一份settings.xml到这个目录

    2.配置idea

    打开setting,照着图修改就好了

    创建Maven项目

    选择webapp,下一步,然后选择你安装的Maven(千万别忘了,自带的Maven没有setting)



    刚创建的项目如下

    打开pop.xml

     <properties>
            <!-- 设置项目编码编码 -->
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <!-- spring版本号 -->
            <spring.version>4.3.5.RELEASE</spring.version>
            <!-- mybatis版本号 -->
            <mybatis.version>3.4.1</mybatis.version>
        </properties>
    
        <dependencies>
    
            <!-- java ee -->
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-api</artifactId>
                <version>7.0</version>
            </dependency>
    
            <!-- 单元测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    
            <!-- 实现slf4j接口并整合 -->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>1.2.2</version>
            </dependency>
    
            <!-- JSON -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.8.7</version>
            </dependency>
    
    
            <!-- 数据库 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.41</version>
                <scope>runtime</scope>
            </dependency>
    
            <!-- 数据库连接池 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</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.3.1</version>
            </dependency>
    
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</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-tx</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-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
        </dependencies>
    

    把这一堆考进去,然后Import Changes 就好了。

    最重要的部分来了

    照着这个图片把目录给建好

    开始xml和一些其他的配置

    1.jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/ssmtest?useUnicode=true&characterEncoding=utf8
    jdbc.username=root
    jdbc.password=123456
    c3p0.maxPoolSize=30
    c3p0.minPoolSize=10
    #关闭连接后不自动commit
    c3p0.autoCommitOnClose=false
    c3p0.checkoutTimeout=10000
    #当获取连接失败重试次数
    c3p0.acquireRetryAttempts=2
    

    2.spring-mvc.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: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-3.0.xsd">
    
        <!-- 扫描web相关的bean -->
        <context:component-scan base-package="com.example"/>
    
        <!-- 开启SpringMVC注解模式 -->
        <mvc:annotation-driven/>
    
        <!-- 静态资源默认servlet配置 -->
        <mvc:default-servlet-handler/>
    
        <!-- 配置jsp 显示ViewResolver -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
            <property name="prefix" value="/WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
        </bean>
    
    </beans>
    

    3.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:context="http://www.springframework.org/schema/context"
           xmlns:tx="http://www.springframework.org/schema/tx"
           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/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd">
    
        <!-- 扫描service包下所有使用注解的类型 -->
        <context:component-scan base-package="com.example.service"/>
    
        <!-- 配置数据库相关参数properties的属性:${url} -->
        <context:property-placeholder location="classpath:jdbc.properties"/>
    
        <!-- 数据库连接池 -->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driver}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
            <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
            <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
            <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
            <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
        </bean>
    
        <!-- 配置SqlSessionFactory对象 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 扫描model包 使用别名 -->
            <property name="typeAliasesPackage" value="com.example.model"/>
            <!-- 扫描sql配置文件:mapper需要的xml文件 -->
            <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        </bean>
    
        <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 注入sqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!-- 给出需要扫描Dao接口包 -->
            <property name="basePackage" value="com.example.dao"/>
        </bean>
    
        <!-- 配置事务管理器 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!-- 配置基于注解的声明式事务 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
    </beans>
    

    4.web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
             version="3.1">
    
        <display-name>ssm</display-name>
        <description></description>
    
        <!-- 编码过滤器 -->
        <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>
    
        <!-- 配置DispatcherServlet -->
        <servlet>
            <servlet-name>SpringMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 配置springMVC需要加载的配置文件-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:spring-*.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
            <async-supported>true</async-supported>
        </servlet>
        <servlet-mapping>
            <servlet-name>SpringMVC</servlet-name>
            <!-- 匹配所有请求,此处也可以配置成 *.do 形式 -->
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
    
    </web-app>
    

    这种地方很容易出错,能复制就复制。

    现在开始SQL语句的编写

    http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html
    我也不解释了,自己去看。

    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
      `email` varchar(255) NOT NULL COMMENT '用户邮箱',
      `password` varchar(255) NOT NULL COMMENT '用户密码',
      `username` varchar(255) NOT NULL COMMENT '用户昵称',
      `role` varchar(255) NOT NULL COMMENT '用户身份',
      `status` int(1) NOT NULL COMMENT '用户状态',
      `regTime` datetime NOT NULL COMMENT '注册时间',
      `regIp` varchar(255) NOT NULL COMMENT '注册IP',
      PRIMARY KEY (`id`),
      UNIQUE KEY `email` (`email`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    INSERT INTO `user` VALUES ('1', 'xxx', 'xxxxx', 'xxxxx', 'root', '0', '2017-03-28 09:40:31', '127.0.0.1');
    SET FOREIGN_KEY_CHECKS=1;
    
    <?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">
    <!-- 设置为IUserDao接口方法提供sql语句配置 -->
    <mapper namespace="com.example.dao.IUserDao">
    
        <select id="selectUser" resultType="User" parameterType="long">
            SELECT * FROM user WHERE id = #{id}
        </select>
    
        <insert id="insertUser" parameterType="com.example.model.User" flushCache="true">
            INSERT INTO user
            (email,password,username,role,status,regTime,regIp)
            VALUE(#{email},#{password},#{username},#{role},#{status},#{regTime},#{regIp})
        </insert>
    
        <update id="updateUser" parameterType="com.example.model.User" flushCache="true">
            UPDATE user set
            email = #{email},
            password = #{password},
            username = #{username},
            role = #{role},
            status = #{status},
            regTime = #{regTime},
            regIp = #{regIp}
            WHERE id = #{id}
        </update>
    
        <delete id="deleteUser"  parameterType="long" flushCache="true" >
            delete from user where id = #{id}
        </delete>
    </mapper>
    

    开始代码的编写

    1.dao

    public interface IUserDao {
        User selectUser(long id);
    
        int insertUser(User user);
    
        int updateUser(User user);
    
        int deleteUser(long id);
    }
    

    2.model

    public class User {
        private long id;
        private String email;
        private String password;
        private String username;
        private String role;
        private int status;
        private Date regTime;
        private String regIp;
    }
    GET AND SET 自己去生成
    

    3.service

    public interface IUserService {
        User selectUser(long userId);
    
        int insertUser(User user);
    
        int updateUser(User user);
    
        int deleteUser(long userId);
    }
    

    3.5.service impl

    @Service("userService")
    public class UserServiceImpl implements IUserService {
    
        @Resource
        private IUserDao userDao;
    
        public User selectUser(long userId) {
            return userDao.selectUser(userId);
        }
    
        public int insertUser(User user) {
            return userDao.insertUser(user);
        }
    
        public int updateUser(User user) {
            return userDao.updateUser(user);
        }
    
        public int deleteUser(long userId) {
            return userDao.deleteUser(userId);
        }
    }
    

    4.controller

    @Controller
    @RequestMapping("/user")
    public class UserController {
        @Resource
        private IUserService userService;
    
        @RequestMapping("/showUser.do")
        public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
    
            long useId = Long.parseLong(request.getParameter("id"));
            User user = this.userService.selectUser(useId);
    
            ObjectMapper mapper = new ObjectMapper();
            response.getWriter().write(mapper.writeValueAsString(user));
            response.getWriter().close();
        }
    }
    

    5.Test

    // 加载spring配置文件
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath:spring-mybatis.xml"})
    public class IUserDaoTest {
    
        @Autowired
        private IUserDao dao;
    
        @Test
        public void testSelectUser() throws Exception {
            //查询
    //        long id = 1;
    //        User user = dao.selectUser(id);
    //        System.out.println(user.getUsername());
            // 添加
    //        user = new User();
    //        user.setEmail("1515023qweq757@qq.com");
    //        user.setPassword("123456");
    //        user.setUsername("Test2");
    //        user.setRole("admin");
    //        user.setStatus(1);
    //        Date date = new Date();
    //        user.setRegTime(date);
    //        user.setRegIp("127.0.0.1");
    //        System.out.println(dao.insertUser(user));
            // 删除
    //        System.out.println("Delete:"+dao.deleteUser(2));
    
            //修改
    //        User user = new User();
    //        user.setId(1);
    //        user.setEmail("update_email");
    //        user.setPassword("update_password");
    //        user.setUsername("update1_name");
    //        user.setRole("update1_role");
    //        user.setStatus(100);
    //        Date date = new Date();
    //        user.setRegTime(date);
    //        user.setRegIp("update1_ip");
    //        System.out.println("Update:"+dao.updateUser(user));
        }
    }
    
    

    到这一步,应该就可以运行了。
    框架搭建就差不多了。



    勉强测试跑通了

    代码来自一开始那个博客,他那个XML哪里有个小问题。


    这样看起来有问题,其实没问题。浪费了我好久时间。

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>test</title>
    </head>
    <script>
        function selectUser() {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    document.getElementById("test").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("POST", "user/showUser.do", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("id=1");
        }
    </script>
    <body>
    <p id="test">Hello World!</p>
    <button type="button" onclick="selectUser()">onclick test</button>
    </body>
    </html>
    

    运行一下就好了。有BUG自己修,反正我没有

    相关文章

      网友评论

          本文标题:Java IntelliJ搭建SSM

          本文链接:https://www.haomeiwen.com/subject/kbtnlftx.html