How to build a project with the idea SSM

table of Contents

Foreword
software environment
to create the project
database file
configuration file
pom.xml
log4j.properties
jdbc.properties
applicationContext.xml
the Spring-mvc.xml
the web.xml
run the project
to write code
Foreword

Recently whim, want to learn the source code under SpringMVC, he intended to use the idea to build a simple version of SSM maven case, that is SpringMVC + Spring + MyBatis + Maven, Spring because before you create some small demo, related software environment has been completed structures, thought to build an entry-level SSM project should not be difficult, who wanted the process encountered many strange problems created from the beginning to the successful operation it took me a whole afternoon (my nap ah ~ ~ ~ ·), the final success of the project up and running when I took a deep breath, to the future not on anything like the toss, is hereby set up to write this article about the recording process.

Software Environment

The first ready to build basic environmental project

Intellij IDEA:2018.1.1

JDK:1.8

Maven:3.6.0

Tomcat: 7.0 and above

Download and install the software, make the relevant environment configuration JDK, Maven and Tomcat in the idea of ​​software settings, in this area a lot of information online, this article is not introduced.

Create a project

After build a good environment, open the idea, click on the New - Project

Maven find a bar, because you want to build SpringMvc project, so select a template webapp

After fill GroupId and ArtifactId, step by step, next, to complete the final finish

Once created, you can see the directory structure of the project is

In addition to the configuration of dependencies pom.xml, as well as a directory folder src, src's main directory provides a webapp folder, there is a WEB-INF folder webapp folder, the file is placed in the front page, and web.xml file.

In addition to the directory structure templates provided, in order to be able to run behind the project is successful, we need to add some folder, so that the directory structure of the project becomes this:

Database files

First of all, the first ready database file, and initialize a record

The DROP TABLE the IF EXISTS user;
the CREATE TABLE user(
idint (. 11) the NOT NULL the AUTO_INCREMENT the COMMENT 'user ID',
emailVARCHAR (255) the NOT NULL the COMMENT 'user mailbox',
usernameVARCHAR (255) the NOT NULL the COMMENT 'Nickname',
roleVARCHAR (255) the NOT NULL COMMENT 'user',
mobileVARCHAR (50) the DEFAULT '' the COMMENT 'phone number',
a PRIMARY KEY ( id)
) = the InnoDB the AUTO_INCREMENT = ENGINE the DEFAULT the CHARSET = UTF-2. 8;


– Records of user


The INTO the INSERT userthe VALUES ( '. 1', '[email protected]', 'XJT', 'the root', '15,678,635,432');
Profile

pom.xml

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

<groupId>com.xjt</groupId>
<artifactId>mvcDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>mvcDemo Maven Webapp</name>

<!-- 用来设置版本号 -->
<properties>
    <srping.version>4.0.2.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>
</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>
</build>
Note: The following four configuration files are placed in the resources folder

log4j.properties

# Log output level
log4j.rootLogger = debug, stdout, D, E

# Set the log output to stdout console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
# log output to the console mode, the default is System.out
log4j.appender.stdout.Target = System.out
# Set flexible layout
log4j.appender.stdout.layout = Org.apache.log4j.PatternLayout
# flexibly define the output format
log4j.appender.stdout.layout.ConversionPattern =% d {yyyy-mM -dd HH: mm: ss, SSS} - [% P] Method: [% C (% RMS)] -% m% n-
the jdbc.properties

= com.mysql.jdbc.Driver Driver
url = jdbc: MySQL: // localhost: 3306 / = utf8 & useSSL the Test characterEncoding = false?
User Name # database
username = root
password # database, do not like me, do not set
password =
# define the initial number of connections
initialSize = 0
# define the maximum number of connections
for maxActive = 20 is
# define the maximum idle
maxIdle = 20 is
# defines the minimum free
minIdle. 1 =
# define the maximum waiting time
maxWait = 60000
the applicationContext.xml

This is the core profile Spring, Spring binding Mybatis includes configuration information and data sources

<?xml version="1.0" encoding="UTF-8"?>

<!-- 加载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="${driver}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/>
    <property name="password" value="${password}"/>
</bean>

<!-- mybatis和spring完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!-- 扫描model包 -->
    <property name="typeAliasesPackage" value="com.xjt.model"/>
    <!-- 扫描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.xjt.dao"/>
</bean>

<!-- 事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!--数据库连接池-->
    <property name="dataSource" ref="dataSource"/>
</bean>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- 扫描注解,这样com.xjt包下的文件都能被扫描 -->
<context:component-scan base-package="com.xjt"/>

<!-- 开启SpringMVC注解模式 -->
<mvc:annotation-driven/>

<!-- 静态资源默认servlet配置 -->
<mvc:default-servlet-handler/>

<!-- 配置返回视图的路径,以及识别后缀是jsp文件 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/jsp/"/>
    <property name="suffix" value=".jsp"/>
</bean>
web.xml

The file is not in resources, but the webapp's WEB-INF folder, document reads as follows:

MVCD

index.jsp org.springframework.web.context.ContextLoaderListener contextConfigLocation classpath:applicationContext.xml CharacterEncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding utf-8
<init-param>
  <param-name>forceEncoding</param-name>
  <param-value>true</param-value>
</init-param>
CharacterEncodingFilter /* springmvc org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring-mvc.xml 1 true springmvc / 运行项目

After you write a good profile above, in fact, we can try to start the project before the project starts first content applicationContext.xml have a comment, and then you can create a runtime environment.

Click on the upper right corner of the idea Edit Configurations ...

Select Tomcat Server - Local,

Start information edited the project, including project name, jdk version, tomcat and port

Select Deployment, add Atifact, choose the second, otherwise it will run Tomcat error

After saving, start the project, after successfully entered your browser to http: // localhost: 8080, returned the following results:

This is what index.jsp file, is to start because index.jsp page, so the result is returned after the start of the project is the content of the start page

Hello World!

Write code

Project run up, the configuration of our front-end controller is successful, the next step is to test the ability to access the database. First, the basic class files to create and write good code.

Entity classes: User.java

package com.xjt.model;

public class User {
private long id;
private String email;
private String mobile;
private String username;
private String role;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getMobile() {
    return mobile;
}

public void setMobile(String mobile) {
    this.mobile = mobile;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getRole() {
    return role;
}

public void setRole(String role) {
    this.role = role;
}

}
Dao Bunken: IUserDao

package com.xjt.dao;

import com.xjt.model.User;

public interface IUserDao {

User selectUser(long id);

}
Mapper file: UserDao.xml

Located resources - mapper folder

<?xml version="1.0" encoding="UTF-8"?>
<select id="selectUser" resultType="User" parameterType="long">
    SELECT * FROM user WHERE id = #{id}
</select>
service interfaces: IUserService

package com.xjt.service;

import com.xjt.model.User;

public interface IUserService {

public User selectUser(long userId);

}
UserServiceImpl

package com.xjt.service.impl;

import com.xjt.dao.IUserDao;
import com.xjt.model.User;
import com.xjt.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service(“userService”)
public class UserServiceImpl implements IUserService {

@Resource
private IUserDao userDao;

public User selectUser(long userId) {
    return userDao.selectUser(userId);
}

}
The Controller file: UserController

package com.xjt.controller;

import com.xjt.model.User;
import com.xjt.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/user")
public class UserController {

@Autowired
private IUserService userService;

@RequestMapping("/select")
public ModelAndView selectUser() throws Exception {
    ModelAndView mv = new ModelAndView();
    User user = userService.selectUser(1);
    mv.addObject("user", user);
    mv.setViewName("user");
    return mv;
}

}
The UserController defines a method selectUser, User id of the read information 1 and returns user.jsp page, the access path is /user/select,user.jsp located under the WEB-INF jsp folder, as follows:

<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

user ID: $ {} requestScope.user.id
In Email: requestScope.user.email} $ {
username: $ {} requestScope.user.username
Role: $ {} requestScope.user.role
Mobile: $ {} requestScope.user.mobile
after all the preparation is completed, withdraw the comment symbol applicationContext.xml file, and then open the project, after successfully entered your browser to http: // localhost: 8080 / user / select

Page successfully returned User information, explanation, we successfully gain access to the contents of the database.

At this point, you're done SSM building project, in order to facilitate learning, I placed source on github, and needy students can download their own, address: https://github.com/Taoxj/mvcDemo

Guess you like

Origin blog.csdn.net/qq_41081222/article/details/93733711