当前位置: 代码迷 >> 综合 >> idea+maven+springmvc+mybatis项目创建
  详细解决方案

idea+maven+springmvc+mybatis项目创建

热度:79   发布时间:2024-03-10 02:13:22

项目目录结构如下

一、利用maven骨架建立一个webapp

1、打开idea15,选择file-->new--->project

2、点击project,弹出如下界面,选择maven点击next

 

3、输入GroupId和ArtifactId,可(groupId:分组id,值一般是项目的包名;artifactId:模块名,建议使用"项目名-模块名称”)随意填写,主要是确定项目的唯一性。

 

4、输入项目名和存储位置点击finish

 

 

配置项目为web项目

 

1、选择项目名右击,点击Add Framework Support

 

 

2、弹出如下对话框,选择java EE的Web Application,接着再选择Create web.xml。点击OK

 

 

3、会看到我们的项目已经变成java web项目。

 

各个配置文件

(一)、maven pom文件的配置

<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId><artifactId>springmvc-maven</artifactId><version>1.0-SNAPSHOT</version><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><spring.version>4.3.4.RELEASE</spring.version></properties><dependencies><!-- 添加junit支持 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- 添加sevlet支持 --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><!-- 添加jsp支持 --><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.1</version></dependency><!-- 添加jstl支持 --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.1.2</version></dependency><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</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-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>${spring.version}</version></dependency><!--spring test支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><!--spring mvc支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><!--spring 事务管理支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring.version}</version></dependency><!--spring jdbc操作支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><!--spring aop编程支持--><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${spring.version}</version></dependency><!-- 添加mybatis支持 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.0</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><!--  jdbc驱动包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.19</version></dependency><!-- 添加阿里巴巴连接池Druid支持 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.16</version></dependency><!-- 添加log4j日志 --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>1.7.7</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>1.7.7</version></dependency><!-- apache共公包 --><dependency><groupId>commons-logging</groupId><artifactId>commons-logging</artifactId><version>1.2</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.2.2</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.1.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.1.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.1.0</version></dependency></dependencies><build><finalName>ssm-template</finalName></build></project>

更新完pom.xml文件后,idea应该会自动下载相应的jar包(可能需要vpn),如果没有自动下载的话,可以点击“Reimport All Maven Projects”按钮进行项目的重新载入。如图所示。

 

(二)、配置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">
<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mybatis.xml,</param-value>
</context-param>
<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener><!--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: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></web-app>

 

(三)、配置  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:aop="http://www.springframework.org/schema/aop"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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"><!--配置扫描--><context:component-scan base-package="com.cn"></context:component-scan><!--&lt;!&ndash; 支持RESTful访问静态资源 &ndash;&gt;--><mvc:default-servlet-handler/><!-- 开启RequestMapping注解 --><mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.StringHttpMessageConverter"/><bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/></mvc:message-converters></mvc:annotation-driven><!-- 对模型视图名称的解析,即在模型视图名称添加前后缀(如果最后一个还是表示文件夹,则最后的斜杠不要漏了) 使用JSP--> <!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- --><bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/view/"/><!--设置JSP文件的目录位置--><property name="suffix" value=".jsp"/></bean><!--文件上传--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--设置上传最大尺寸为10MB--><property name="maxUploadSizePerFile" value="10485760"/><property name="defaultEncoding" value="UTF-8"/><property name="resolveLazily" value="true"/></bean></beans>

(四)、配置  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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!--加载jdbc.properties--><context:property-placeholder location="classpath:jdbc.properties"/><!--配置druid连接池--><bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><!-- 基本属性 url、user、password --><property name="driverClassName" value="${jdbc.driver}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /><!-- 配置初始化大小、最小、最大 --><property name="initialSize" value="${jdbc.initialSize}" /><property name="minIdle" value="${jdbc.minIdle}" /><property name="maxActive" value="${jdbc.maxActive}" /><!-- 配置获取连接等待超时的时间 --><property name="maxWait" value="${jdbc.maxWait}" /><!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --><property name="timeBetweenEvictionRunsMillis" value="60000" /><!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --><property name="minEvictableIdleTimeMillis" value="300000" /><property name="validationQuery" value="SELECT 'x'" /><property name="testWhileIdle" value="true" /><property name="testOnBorrow" value="false" /><property name="testOnReturn" value="false" /><!-- 打开PSCache,并且指定每个连接上PSCache的大小 --><property name="poolPreparedStatements" value="true" /><property name="maxPoolPreparedStatementPerConnectionSize" value="20" /><!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 --><property name="filters" value="stat" /></bean><!--sqlSessionFactory--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--数据库连接池--><property name="dataSource" ref="dataSource"/><!--加载mybatis全局配置文件--><property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/><!--mapper.xml所在位置--><property name="mapperLocations" value="classpath*:mappers/*Mapper.xml" /><!--指定需要使用别名的PO类所在的包--><property name="typeAliasesPackage" value="com.cn.entity" /></bean><!--mapper扫描器--><bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.cn.dao"/><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/></bean><!-- 对mybatis操作数据事务控制,spring使用jdbc的事务控制类 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 数据源dataSource在spring-mybatis.xml中配置了 --><property name="dataSource" ref="dataSource"/></bean></beans>

(五)、配置  mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 配置全局属性 --><settings><!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 --><setting name="useGeneratedKeys" value="true"/><!-- 使用列别名替换列名 默认:true --><setting name="useColumnLabel" value="true"/><!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} --><setting name="mapUnderscoreToCamelCase" value="true"/></settings>
</configuration>

(六)、配置  jdbc.properties/log4j.properties文件

### 设置###
log4j.rootLogger=debug,stdout,D,E
### 输出信息到控制抬 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n
### 输出DEBUG 级别以上的日志到=E://logs/log.log ###
log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.D.File = E://logs/log.log
log4j.appender.D.Append=true
log4j.appender.D.Threshold=DEBUG
log4j.appender.D.layout=org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
### 输出ERROR 级别以上的日志到=E://logs/error.log ###
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.E.File =E://logs/error.log
log4j.appender.E.Append=true
log4j.appender.E.Threshold=ERROR
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc_maven?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Hongkong 
jdbc.username=root
jdbc.password=rootjdbc.minPoolSize=5
jdbc.maxPoolSize=20
#初始化大小
jdbc.initialSize=1
#最小
jdbc.minIdle=1
#最大
jdbc.maxActive=20
#获取连接等待超时的时间
jdbc.maxWait=60000

基本的代码编写就完成了。

Java类看代码

CalculatorController类
package com.cn.controller;
import com.cn.entity.User;
import com.cn.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;import java.text.SimpleDateFormat;/*** @Classname CalculatorController* @Description TODO* @Date 2020/10/29  23:41* @Created by laijunfeng*/
@Controller
public class CalculatorController {private static final Logger LOGGER = LoggerFactory.getLogger(CalculatorController.class);@Autowiredprivate UserService userService;@RequestMapping(value = "/calcLoginPage")public String calcLoginPage() {System.out.println("calcLoginPage时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));LOGGER.info("》》》》》》info《《《《《《《《《");LOGGER.debug("》》》》》》debug《《《《《《《《《");LOGGER.warn("》》》》》》warn《《《《《《《《《");LOGGER.error("》》》》》》error《《《《《《《《《");List<User> userList = userService.queryUserList();for(User user : userList){LOGGER.info("id:{}", user.getId());LOGGER.info("username:{}",user.getUsername());LOGGER.info("password:{}",user.getPassword());}return  "index";}}

UserMapper类
package com.cn.dao;import com.cn.entity.User;
import org.springframework.stereotype.Repository;import java.util.List;@Repository
public interface UserMapper {List<User> queryUserList();}
User类
package com.cn.entity;public class User {private Integer id;private String username;private String password;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}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;}}
UserService类
package com.cn.service;import com.cn.entity.User;import java.util.List;public interface UserService {List<User> queryUserList();}
UserServiceImpl类
package com.cn.service.impl;import com.cn.dao.UserMapper;
import com.cn.entity.User;
import com.cn.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.util.List;@Transactional
@Service
public class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper;@Overridepublic List<User> queryUserList() {System.out.println("UserServiceImpl==================");return userMapper.queryUserList();}}

 

四、配置tomcat服务器

1、进入配置页面

 

2、如上图操作,点击Edit弹出如下界面

 

 3、点击加号,找到tomcat,再点击Local,到如下界面

 

 

 

4、选择Deployment,点击加号在选择Artifact如下图

 

 5、再点击上图中的绿色小笔,进入下图的页面,双击jar包,将其添加到lib中

 

 

jar包全部添加完毕,点击OK完成tomcat配置

五、运行项目

点击run即可

 

访问地址

 

运行结果

 

 

  相关解决方案