亲宝软件园·资讯

展开

maven搭建ssm的web项目 基于maven搭建一个ssm的web项目的详细图文教程

阿鑫你要努力啊 人气:0
想了解基于maven搭建一个ssm的web项目的详细图文教程的相关内容吗,阿鑫你要努力啊在本文为您仔细讲解maven搭建ssm的web项目的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:maven搭建ssm的web项目,maven搭建web项目,下面大家一起来学习吧。

1:使用idea建立一个web项目

选择web项目

2:引入pom依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.frame</groupId>
 <artifactId>ssm</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring.framework.version>5.2.8.RELEASE</spring.framework.version>
  <aspectj.version>1.8.13</aspectj.version>
  <jackson.version>2.9.1</jackson.version>
  <logback.version>1.2.3</logback.version>
 </properties>

 <dependencies>
  <!-- 添加 commons 依赖包 -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
  </dependency>
  <dependency>
   <groupId>commons-io</groupId>
   <artifactId>commons-io</artifactId>
   <version>2.5</version>
  </dependency>
  <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.6</version>
  </dependency>

  <!-- 添加 spring 依赖包 -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aspects</artifactId>
   <version>${spring.framework.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>${spring.framework.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
   <version>${spring.framework.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.framework.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context-support</artifactId>
   <version>${spring.framework.version}</version>
  </dependency>

  <!-- 添加 aspectJ 依赖包 -->
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>${aspectj.version}</version>
  </dependency>
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjrt</artifactId>
   <version>${aspectj.version}</version>
  </dependency>

  <!-- 添加 mybatis 依赖包 -->
  <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>3.5.5</version>
  </dependency>
  <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>1.3.1</version>
  </dependency>

  <!-- 添加 druid 依赖包 -->
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.1.9</version>
  </dependency>

  <!-- 添加 mysql 驱动 -->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
  </dependency>

  <!-- 添加 jackson 依赖包 -->
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.11.1</version>
  </dependency>

  <!-- 添加 servlet 依赖包 -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <!-- 添加 jstl 依赖包 -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>

  <!-- 添加 logback 依赖包 -->
  <dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version>${logback.version}</version>
  </dependency>

  <dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.12</version>
   <scope>provided</scope>
  </dependency>

  <!-- log -->
  <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
  <dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.1.11</version>
 </dependency>
 <dependency>
  <groupId>org.logback-extensions</groupId>
  <artifactId>logback-ext-spring</artifactId>
  <version>0.1.1</version>
 </dependency>
 <dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>jcl-over-slf4j</artifactId>
  <version>1.7.25</version>
 </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
  </plugins>
 </build>

</project>

3: 在src/main新建java和resource文件夹

1:将java文件夹marked directory as source root
2:将resource新建resource文件夹

4:在resource新建以下文件

在这里插入图片描述

5:spring配置文件applicationContent.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" xmlns:aop="http://www.springframework.org/schema/aop"
    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-4.3.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

  <!-- 自动扫描指定目录,将控制器加载到bean -->
  <context:component-scan base-package="com.ssm.demo" />

  <context:property-placeholder location="classpath:conf/*.properties"/>
  <!-- 配置 druid 数据源 -->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <!-- 基本属性 url、user、password、driverClass -->
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
  </bean>
  <!-- 配置 sessionFactory -->
  <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations">
      <list>
        <value>classpath:mapper/*Mapper.xml</value>
      </list>
    </property>
  </bean>
  <!-- 配置 sqlSessionTemplate 持久化模板 -->
  <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg ref="sqlSessionFactory" />
  </bean>

  <!-- 配置事物管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource" />
  </bean>
  <!-- 配置事物传播行为 -->
  <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
      <tx:method name="get*" read-only="true" />
      <tx:method name="find*" read-only="true" />
      <tx:method name="select*" read-only="true" />
      <tx:method name="*" propagation="REQUIRED" />
    </tx:attributes>
  </tx:advice>
  <!-- 配置事物切入点 -->
  <aop:config>
    <aop:pointcut expression="execution(* com.ssm.demo.service.*.*(..))" id="pointCut" />
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut" />
  </aop:config>
  <!-- 开始声明式事务(事物注解) -->
  <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

6:springMVC配置文件

<?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"
    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-4.3.xsd">

  <!-- 配置视图解析器 -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/jsp/" />
    <property name="suffix" value=".jsp" />
    <!-- 可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 -->
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  </bean>

  <!-- 返回json 需导入 jackson-annotations.jar,jackson-core.jar,jackson-databind.jar -->
  <!-- 通过处理器映射DefaultAnnotationHandlerMapping来开启支持@Controller注解 -->
  <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
  <!-- 通过处理器适配器AnnotationMethodHandlerAdapter来开启支持@RequestMapping注解 -->
  <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
      <list>
        <!-- 配置返回字符串编码 -->
        <bean
            class="org.springframework.http.converter.StringHttpMessageConverter">
          <property name="supportedMediaTypes">
            <list>
              <value>text/html; charset=UTF-8</value>
              <value>application/json;charset=UTF-8</value>
            </list>
          </property>
        </bean>
        <!-- 配置 json 转换器 -->
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
          <property name="supportedMediaTypes">
            <list>
              <value>text/html; charset=UTF-8</value>
              <value>application/json;charset=UTF-8</value>
            </list>
          </property>
        </bean>
      </list>
    </property>
  </bean>

</beans>

7:jdbc.properties配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.username=axin
jdbc.password=19950925

8:log4j.properties配置文件

log4j.rootLogger=DEBUG,stdout
log4j.logger.com.mchange.v2 = INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

9:logback.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- 尽量别用绝对路径,如果带参数不同容器路径解释可能不同,以下配置参数在pom.xml里 -->
  <property name="log.root.level" value="info" /> <!-- 日志级别 -->
  <property name="log.other.level" value="info" /> <!-- 其他日志级别 -->
  <property name="log.base" value="e:/log" /> <!-- 日志路径,这里是相对路径,web项目eclipse下会输出到eclipse的安装目录下,如果部署到linux上的tomcat下,会输出到tomcat/bin目录 下 -->
  <property name="log.moduleName" value="ssm.log" /> <!-- 模块名称, 影响日志配置名,日志文件名 -->
  <property name="log.max.size" value="100MB" /> <!-- 日志文件大小,超过这个大小将被压缩 -->

  <!--控制台输出 -->
  <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <Pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</Pattern>
    </encoder>
  </appender>

  <!-- 用来保存输出所有级别的日志 -->
  <appender name="file.all" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${log.base}/${log.moduleName}.log</File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果
      是web项目会保存到Tomcat的bin目录 下 -->
    <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。 -->
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <FileNamePattern>${log.base}/archive/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip
      </FileNamePattern>
      <!-- 文件输出日志 (文件大小策略进行文件输出,超过指定大小对文件备份) -->
      <timeBasedFileNamingAndTriggeringPolicy
          class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>${log.max.size}</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
    <!-- 日志输出的文件的格式 -->
    <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method\(\):%L -%msg%n</pattern>
    </layout>
  </appender>

  <!-- 这也是用来保存输出所有级别的日志 -->
  <appender name="file.all.other" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${log.base}/${log.moduleName}_other.log</File>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <FileNamePattern>${log.base}/archive/${log.moduleName}_other_%d{yyyy-MM-dd}.%i.log.zip
      </FileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy
          class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>${log.max.size}</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
    <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L -%msg%n</pattern>
    </layout>
  </appender>

  <!-- 只用保存输出error级别的日志 -->
  <appender name="file.error"
       class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${log.base}/${log.moduleName}_err.log</File>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <FileNamePattern>${log.base}/archive/${log.moduleName}_err_%d{yyyy-MM-dd}.%i.log.zip
      </FileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy
          class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>${log.max.size}</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
    <layout class="ch.qos.logback.classic.PatternLayout">
      <pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{56}.%method\(\):%L - %msg%n</pattern>
    </layout>
    <!-- 下面为配置只输出error级别的日志 -->
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
      <level>ERROR</level>
      <onMatch>ACCEPT</onMatch>
      <onMismatch>DENY</onMismatch>
    </filter>
  </appender>

  <!-- 不丢失日志.默认的,如果队列的80%已满,则会丢弃TRACT、DEBUG、INFO级别的日志 -->
  <!-- 更改默认的队列的深度,该值会影响性能.默认值为256 -->
  <!-- 添加附加的appender,最多只能添加一个 -->
  <appender name="file.async" class="ch.qos.logback.classic.AsyncAppender">
    <discardingThreshold>0</discardingThreshold>
    <queueSize>256</queueSize>
    <includeCallerData>true</includeCallerData>
    <appender-ref ref="file.all" />
  </appender>

  <appender name="file.async.other" class="ch.qos.logback.classic.AsyncAppender">
    <discardingThreshold>0</discardingThreshold>
    <queueSize>256</queueSize>
    <includeCallerData>true</includeCallerData>
    <appender-ref ref="file.all.other" />
  </appender>

  <!-- 为某个包下的所有类的指定Appender 这里也可以指定类名称例如:com.aa.bb.ClassName -->
  <logger name="com.yyt" additivity="false">
    <level value="${log.root.level}" />
    <appender-ref ref="stdout" />
    <appender-ref ref="file.async" /><!-- 即com.li包下级别为 ${log.root.level}的才会使用file.async来打印 -->
    <appender-ref ref="file.error" />
  </logger>
  <logger name="org.apache.ibatis" level="DEBUG">
    <appender-ref ref="STDOUT"/>
  </logger>

  <logger name="java.sql" level="debug">
    <appender-ref ref="STDOUT"/>
  </logger>
  <!-- root将级别为${log.root.level}及大于${log.root.level}的日志信息交给已经配置好的名为“Console”的appender处理,“Console”appender将信息打印到Console,其它同理 -->
  <root level="${log.root.level}">
    <appender-ref ref="stdout" /> <!-- 标识这个appender将会添加到这个logger -->
    <appender-ref ref="file.async.other" />
    <appender-ref ref="file.error" />
  </root>
</configuration>

10 mappera.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.frame.mapper.DemoMapper">
  <resultMap type="com.ssm.demo.entity.User" id="userResultMap">
    <!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
    <!-- property:主键在pojo中的属性名 -->
    <!-- column:主键在数据库中的列名 -->
    <id property="id" column="id" />
    <!-- 定义普通属性 -->
    <result property="name" column="name" />
  </resultMap>
  <select id="getTest" resultMap="userResultMap">
    SELECT '1' id, 'guoxin' name from dual
  </select>

</mapper>

配置webapp下的文件 web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     id="WebApp_ID" version="3.1">
 <display-name>ssm</display-name>

 <!-- 过滤器解决中文乱码问题、强制编码 UTF-8 -->
 <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>forceRequestEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>characterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- 配置 springMVC 基本配置 -->
 <servlet>
  <servlet-name>springMVC</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:conf/spring-mvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>springMVC</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

 <!-- 配置 spring 监听器 -->
 <!-- needed for ContextLoaderListener -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:conf/applicationContext.xml</param-value>
 </context-param>
 <!-- Bootstraps the root web application context before servlet initialization -->
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <context-param>
  <param-name>logbackConfigLocation</param-name>
  <param-value>classpath:log/logback.xml</param-value>
 </context-param>
 <listener>
  <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
 </listener>


 <!-- 配置欢迎页 -->
 <welcome-file-list>
  <welcome-file>jsp/index.jsp</welcome-file>
 </welcome-file-list>

</web-app>

hello.jsp

<html>
<body>
<h2>Hello axin! ${aaa}</h2>
</body>
</html>

java案例

文件如图

DemoController.java

package com.ssm.demo.controller;


import com.ssm.demo.entity.User;
import com.ssm.demo.service.DemoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
public class DemoController {

  @Resource
  private DemoService demoService;

  private static final Logger LOG = LoggerFactory.getLogger(DemoController.class);

  @RequestMapping("/hello")
  public User hello() {
    LOG.info("输出日志");
    User test = demoService.test();
    return test;
  }
}

User.java

package com.ssm.demo.entity;

import lombok.*;

@ToString
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class User {
  private int id;
  private String name;
}

DemoService.java

package com.ssm.demo.service;

import com.ssm.demo.entity.User;

public interface DemoService {
    User test();
}

DemoServiceImpl.java

package com.ssm.demo.service.impl;


import com.ssm.demo.entity.User;
import com.ssm.demo.service.DemoService;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



@Service("demoService")
public class DemoServiceImpl implements DemoService {

  @Autowired
  private SqlSessionTemplate sqlSessionTemplate;

  // mybatis sql模板的命名空间
  private static final String NAMESPACE = "com.frame.mapper.DemoMapper";

  @Override
  public User test() {
    return (User)sqlSessionTemplate.selectOne(NAMESPACE + ".getTest");
  }
}

配置tomcat

配置tomcat

选择tomcat Server

配置好tomcat参数

配置好项目的application context,即访问路径

ssm为访问路径

启动tomcat

选择run或者debug都行

访问

输入:http://localhost:8080/ssm/

默认界面 index.jsp

输入:http://localhost:8080/ssm/hello

输出了我们返回的bean

总结

加载全部内容

相关教程
猜你喜欢
用户评论