zoukankan      html  css  js  c++  java
  • IDEA+maven搭建前后端分离ssm环境

    第一次搭建ssm前后端分离环境的时候遇到了很多坑,一天下来我充分体验到什么叫做面向配置编程了。

    第一步:使用IDEA构建maven项目,并配置Tomcat

    这里我就不细说了,搭建之后如下图
    

    第二步:在pom.xml中导入相关依赖

    <groupId>com.hsy.sms</groupId>
      <artifactId>u_sms</artifactId>
      <version>1.0-SNAPSHOT</version>
      <packaging>war</packaging>
    
      <!-- 用来设置版本号 -->
      <properties>
        <srping.version>4.2.4.RELEASE</srping.version>
        <mybatis.version>3.2.8</mybatis.version>
        <slf4j.version>1.7.12</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
        <druid.version>1.0.9</druid.version>
      </properties>
      <!-- 用到的jar包 -->
      <dependencies>
        <!-- 单元测试 -->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
          <scope>test</scope>
        </dependency>
    
        <!-- spring框架包 -->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-oxm</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-expression</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-orm</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>${srping.version}</version>
        </dependency>
        <!-- spring框架包 -->
        <!-- mybatis框架包 -->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.2</version>
        </dependency>
        <!-- mybatis框架包 -->
        <!-- 数据库驱动 -->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.35</version>
        </dependency>
        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
          <groupId>commons-dbcp</groupId>
          <artifactId>commons-dbcp</artifactId>
          <version>1.4</version>
        </dependency>
        <!-- jstl标签类 -->
        <dependency>
          <groupId>jstl</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
        </dependency>
        <!-- log -->
        <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>${log4j.version}</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>
        <!-- 连接池 -->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>${druid.version}</version>
        </dependency>
    
          <!--加入对json转换-->
        <!-- JSON: jackson -->
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.5.0</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.5.0</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.5.0</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.jr</groupId>
          <artifactId>jackson-jr-all</artifactId>
          <version>2.5.0</version>
        </dependency>
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.46</version>
        </dependency>
      </dependencies>
    
      <build>
        <!-- java编译插件,如果maven的设置里配置好jdk版本就不用 -->
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.2</version>
            <configuration>
              <source>1.8</source>
              <target>1.8</target>
              <encoding>UTF-8</encoding>
            </configuration>
          </plugin>
        </plugins>
    
        <!--打包配置文件-->
          <resources>
              <resource>
                  <directory>srcmain
    esources</directory>
                  <includes>
                      <include>**/*.properties</include>
                      <include>**/*.xml</include>
                      <include>**/*.tld</include>
                  </includes>
                  <filtering>false</filtering>
              </resource>
              <resource>
                  <directory>srcmainjava</directory>
                  <excludes>
                      <exclude>**/*.java</exclude>
                  </excludes>
              </resource>
          </resources>
      </build>
    
    

    第二步:配置框架底层的配置文件

    1、创建log4j.properties

    # Global logging configuration
    log4j.rootLogger=DEBUG, stdout
    # Console output...
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
    
    

    2、创建jdbc.properties

    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/u_sms?characterEncoding=utf-8
    jdbc.username=root
    jdbc.password=root
    #定义初始连接数
    initialSize=0    
    #定义最大连接数
    maxActive=20    
    #定义最大空闲
    maxIdle=20    
    #定义最小空闲
    minIdle=1    
    #定义最长等待时间
    maxWait=60000
    

    3、创建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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    	<!-- 加载properties文件 -->
    	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    		<property name="location" value="classpath:jdbc.properties"/>
    	</bean>
    
    	<!-- 配置数据源 -->
    	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    		<property name="driverClassName" value="${jdbc.driver}"/>
    		<property name="url" value="${jdbc.url}"/>
    		<property name="username" value="${jdbc.username}"/>
    		<property name="password" value="${jdbc.password}"/>
    	</bean>
    
    	<!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<property name="dataSource" ref="dataSource"/>
    		<!-- 扫描model包 -->
    		<property name="typeAliasesPackage" value="com.hsy.sms.entity"/>
    		<!-- 扫描sql配置文件:mapper需要的xml文件-->
    		<property name="mapperLocations" value="classpath:mapper/*.xml"/>
    	</bean>
    
    	<!-- Mapper动态代理开发,扫描dao接口包-->
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<!-- 注入sqlSessionFactory -->
    		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    		<!-- 给出需要扫描Dao接口包 -->
    		<property name="basePackage" value="com.hsy.sms.mapper"/>
    	</bean>
    
    	<!-- 事务管理 -->
    	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<!--数据库连接池-->
    		<property name="dataSource" ref="dataSource"/>
    	</bean>
    </beans>
    
    

    4、创建springmvc.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"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
    	<!-- 配置@controller扫描包 -->
    	<context:component-scan base-package="com.hsy.sms" />
    
    	 <!--使用Annotation自动注册Bean,扫描@Controller和@ControllerAdvice-->
    	<context:component-scan base-package="com.hsy.sms.handler" use-default-filters="false">
    		<!-- base-package 如果多个,用“,”分隔 -->
    		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    		<!--控制器增强,使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常-->
    		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
    	</context:component-scan>
    	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
    	<mvc:annotation-driven />
    
    
    	<!-- 输出对象转JSON支持 -->
    	<bean
    			class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    		<property name="messageConverters">
    			<list>
    				<bean
    						class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
    					<property name="supportedMediaTypes">
    						<list>
    							<value>text/html;charset=UTF-8</value>
    							<value>text/plain;charset=UTF-8</value>
    							<value>application/json;charset=UTF-8</value>
    						</list>
    					</property>
    				</bean>
    			</list>
    		</property>
    	</bean>
    
    	<!-- 配置视图解析器 -->
    	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix" value="/WEB-INF/jsp/"/>
    		<property name="suffix" value=".jsp"/>
    	</bean>
    </beans>
    

    5、配置web.xml文件

    <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">
    
    
      <!-- 注册ServletContext监听器,创建容器对象,并且将ApplicationContext对象放到Application域中 -->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
    
      <!-- 指定spring核心配置文件 -->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
      </context-param>
    
      <!-- 解决乱码的过滤器 -->
      <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
     
      <!-- 配置前端控制器 -->
      <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
        <!-- 指定配置文件位置和名称 如果不设置,默认找/WEB-INF/<servlet-name>-servlet.xml -->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:spring/springmvc.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>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
    </web-app>
    

    5、在mapper中创建UserMapper.xml文件

    在创建映射文件之前,先将先决条件搭建好

    这里用User举个栗子
    
    package com.hsy.sms.entity;
    public class User {
        private Integer uid;
        private String uname;
        private String pwd_id;
        private Integer groupid;
    ///setter/getter
    }
    
    数据库如下
    

    创建Usermapper.java
    
    package com.hsy.sms.mapper;
    import com.hsy.sms.entity.User;
    public interface UserMapper {
        /**
         * 通过id获取用户基本信息
         * @param uid
         * @return
         */
        User getUserById(Integer uid);
    }
    
    <mapper namespace="com.hsy.sms.mapper.UserMapper">
    	<select id="getUserById" parameterType="int" resultType="com.hsy.sms.entity.User">
    		SELECT
    		  `uid`,
    		  `uname`,
    		  `pwd_id`,
    		  `groupid`
    		FROM `t_test`
    		WHERE
    		uid = #{uid}
    	</select>
    </mapper>
    
        创建完成目录结构如下
    ![](https://img2018.cnblogs.com/blog/1426931/201910/1426931-20191018215416492-1749701699.png)
    

    第三步:编辑java代码测试

    1、创建UserService

    package com.hsy.sms.service;
    import com.hsy.sms.entity.User;
    import org.springframework.stereotype.Service;
    @Service
    public interface UserService {
        /**
         * 通过id获取用户基本信息
         * @param uid
         * @return
         */
        User getUserById(Integer uid);
    }
    

    2、创建UserServiceImpl实现类

    package com.hsy.sms.service.impl;
    
    import com.hsy.sms.mapper.UserMapper;
    import com.hsy.sms.entity.User;
    import com.hsy.sms.service.UserService;
    import org.springframework.stereotype.Service;
    
    import javax.annotation.Resource;
    
    @Service("userService")
    public class UserServiceImpl implements UserService {
    
        @Resource
        private UserMapper userDao;
    
        @Override
        public User getUserById(Integer uid) {
            return userDao.getUserById(uid);
        }
    }
    

    3、创建UserController编写login接口

    package com.hsy.sms.controller;
    
    import com.hsy.sms.entity.User;
    import com.hsy.sms.service.UserService;
    import com.hsy.sms.util.JSON;
    import com.hsy.sms.util.OutputJson;
    import com.hsy.sms.util.ReturnFormat;
    import com.sun.javafx.collections.MappingChange;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        @Autowired
        private UserService userService;
    
        @RequestMapping(value = "/login", method = RequestMethod.POST,consumes="application/x-www-form-urlencoded")
        @ResponseBody
        public Object selectUser(@RequestParam(value="uid") int uid, @RequestParam(value="password") String pwd_id) throws Exception {
            //根据用户的uid获取用户
            User user = userService.getUserById(uid);
            if(user != null $$ user.getPwd_id().equals(pwd_id)){
                return user;
    
            }
            return "";
        }
    }
    
    使用ajax测试成功
    

  • 相关阅读:
    java 泛型
    数据结构与算法分析java——线性表1
    常见链表题
    网络面试题集锦
    java 网络流 TCP/UDP
    java文件
    java IO流——字节流
    java IO流——字符流
    java集合框架——工具类
    java集合框架——Map
  • 原文地址:https://www.cnblogs.com/shaoyu/p/11701189.html
Copyright © 2011-2022 走看看