一篇文章搞定Maven安裝到建立maven版Spring MVC專案及配置
配置maven
本地安裝
新建變數名為MAVEN_HOME,值為maven安裝目錄的系統變數
在系統變數名為Path的值中新增“%MAVEN_HOME%\bin;”
cmd命令列輸入mvn -v 檢視是否安裝成功
修改maven配置檔案
apache-maven-3.5.4\conf\settings.xml
配置本地倉庫地址
配置遠端倉庫地址
<mirrors> <mirror> <id>nexus-aliyun</id> <name>nexus-aliyun</name> <url>http://maven.aliyun.com/nexus/content/groups/public</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors>
eclipse的配置
Window...preferences...Maven...User Settings
新增剛才配置的settings.xml檔案到User Settings,點選Update Settings,Apply and Close
建立專案
new...project...maven project
選擇Workspace
選擇maven-archetype-webapp 1.0
配置專案名稱,版本,包名等資訊。
Group Id:專案物件在倉庫中定位 Artifact Id:專案資料夾目錄的名稱 Version:專案版本號 Package:專案source檔案下的包名
修改workspace下對應專案.settings資料夾下的org.eclipse.wst.common.project.facet.core.xml檔案
jst.web版本修改為3.0
jre版本根據實際情況修改
pom.xml檔案配置
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tencent.wechat</groupId> <artifactId>wechat</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>uruleserver Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <!-- spring版本號 --> <spring.version>5.0.9.RELEASE</spring.version> <!-- mybatis版本號 --> <mybatis.version>3.4.6</mybatis.version> </properties> <dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.3.1</version> <scope>test</scope> </dependency> <!-- spring核心包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</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-oxm</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-jdbc</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-aop</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-test</artifactId> <version>${spring.version}</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.2</version> </dependency> <!-- 匯入java ee jar 包 --> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> </dependency> <!-- 匯入Mysql資料庫連結jar包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.12</version> </dependency> <!-- 匯入dbcp的jar包,用來在applicationContext.xml中配置資料庫 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-dbcp2</artifactId> <version>2.5.0</version> </dependency> <!-- JSTL標籤類 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- 日誌檔案管理包 --> <!-- log start --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> <version>2.11.1</version> </dependency> <!-- 格式化物件,方便輸出日誌 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.49</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.8.0-beta2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.8.0-beta2</version> </dependency> <!-- log end --> <!-- 映入JSON --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.6</version> </dependency> <!-- 上傳元件包 --> <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.6</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency> </dependencies> <build> <finalName>uruleserver</finalName> </build> </project>
其他配置檔案
在src/main/resources資料夾下建立以下四個檔案
注:jdbc.properties中資料庫url、username、password請按實際填寫。spring-mvc.xml和spring-mybatis.xml中涉及的對應包名請按實際填寫。log4j.properties無需修改。
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: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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 -->
<context:component-scan base-package="com.uruleserver.controller" />
<mvc:annotation-driven>
<mvc:message-converters>
<!-- <ref bean="stringHttpMessageConverter"/> -->
<ref bean="mappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
<!--避免IE執行AJAX時,返回JSON出現下載檔案 -->
<bean id="mappingJackson2HttpMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 定義跳轉的檔案的前後綴 ,檢視模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 -->
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 預設編碼 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 檔案大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 記憶體中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
<!-- 配置攔截器 -->
<!-- <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/user/userHome"/>
<bean class="com.ydtime.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/product/toProduct"/>
<bean class="com.ydtime.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors> -->
</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: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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自動掃描 -->
<context:component-scan base-package="com.uruleserver" />
<!-- 如需其他配置檔案請在此引入 -->
<!-- <import resource="classpath:context.xml"/> -->
<!-- 引入配置檔案 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
destroy-method="close">
<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="${initialSize}"/>
<!-- 連線池最大數量 -->
<property name="maxTotal" value="${maxTotal}"/>
<!-- 連線池最大空閒 -->
<property name="maxIdle" value="${maxIdle}"/>
<!-- 連線池最小空閒 -->
<property name="minIdle" value="${minIdle}"/>
<!-- 獲取連線最大等待時間 -->
<property name="maxWaitMillis" value="${maxWaitMillis}"/>
<!-- 指明連線是否被空閒連接回收器(如果有)進行檢驗 -->
<property name="testWhileIdle" value="true"/>
<!-- 執行一次空閒連接回收器的時間間隔(60秒)-->
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}"/>
<!-- 驗證時使用的SQL語句 -->
<property name="validationQuery" value="SELECT 1"/>
<!-- 借出連線時不要測試,否則很影響效能 -->
<property name="testOnBorrow" value="false"/>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置對映檔案 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自動掃描mapping.xml檔案 -->
<property name="mapperLocations" value="classpath:com/uruleserver/mapping/*.xml"></property>
</bean>
<!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.uruleserver.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://172.21.68.157:3306/wechat
jdbc.username=root
jdbc.password=password
#定義初始連線數
initialSize=0
#定義最大連線數
maxTotal=20
#定義最大空閒
maxIdle=20
#定義最小空閒
minIdle=1
#定義最長等待時間
maxWaitMillis=60000
#空閒回收期執行週期(60秒)
timeBetweenEvictionRunsMillis=60000
log4j.properties
#定義LOG輸出級別
log4j.rootLogger=INFO,Console,File
#定義日誌輸出目的地為控制檯
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以靈活地指定日誌輸出格式,下面一行是指定具體的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#檔案大小到達指定尺寸的時候產生一個新的檔案
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定輸出目錄
log4j.appender.File.File = logs/ssm.log
#定義檔案最大大小
log4j.appender.File.MaxFileSize = 10MB
# 輸出所以日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<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>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- <servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/view/*</url-pattern>
</servlet-mapping> -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
建立專案程式碼
controller/ControllerDemo.java
package com.uruleserver.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.uruleserver.domain.User;
import com.uruleserver.service.UserService;
@Controller
@RequestMapping("/demo")
public class ControllerDemo {
@Resource
private UserService userService;
@RequestMapping("/index")
public String index(HttpServletRequest request, Model model) {
return "demo";
}
@RequestMapping("/userTest")
public String userTest(HttpServletRequest request, Model model) {
User user = this.userService.getUserById(1);
System.out.println("name:"+user.getUserName());
return "demo";
}
}
dao/UserDao.java
package com.uruleserver.dao;
import com.uruleserver.domain.User;
public interface UserDao {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updatePassword(User record);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
domain/User.java
package com.uruleserver.domain;
public class User {
private Integer id;
private String userName;
private String phone;
private String email;
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 == null ? null : userName.trim();
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone == null ? null : phone.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
}
impl/UserServiceImpl.java
package com.uruleserver.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.uruleserver.dao.UserDao;
import com.uruleserver.domain.User;
import com.uruleserver.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public User getUserById(int userId) {
return userDao.selectByPrimaryKey(userId);
}
public void insertUser(User user) {
userDao.insert(user);
}
public void updateUserPassword(User user) {
userDao.updatePassword(user);
}
public void updateUser(User user) {
userDao.updateByPrimaryKeySelective(user);
}
}
mapping/UserMapper.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.uruleserver.dao.UserDao" >
<resultMap id="BaseResultMap" type="com.uruleserver.domain.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, phone, email, password
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.uruleserver.domain.User" >
insert into user (id, user_name,
phone, email, password)
values (#{id,jdbcType=INTEGER}, #{user_name,jdbcType=VARCHAR},
#{phone,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.uruleserver.domain.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="userName != null" >
user_name,
</if>
<if test="phone != null" >
phone,
</if>
<if test="email != null" >
email,
</if>
<if test="password != null" >
password
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{user_name,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
#{phone,jdbcType=VARCHAR},
</if>
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="password != null" >
#{password,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updatePassword" parameterType="com.uruleserver.domain.User" >
update user
set password = #{password,jdbcType=VARCHAR}
where phone = #{phone,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.uruleserver.domain.User" >
update user
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="phone != null" >
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.uruleserver.domain.User" >
update user
set user_name = #{userName,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
src/main/webapp/WEB-INF/view/demo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Demo</title>
</head>
<body>
<h1>This is SpringMVC Demo</h1>
</body>
</html>
在資料庫中建立一張名為user的表
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_name` VARCHAR(50) NULL DEFAULT NULL,
`phone` VARCHAR(11) NOT NULL DEFAULT '',
`email` VARCHAR(50) NULL DEFAULT '',
`password` VARCHAR(50) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=2
;
插入一條資料
INSERT INTO `user` (`id`, `user_name`, `phone`, `email`, `password`) VALUES
(1, 'Mike', '12345678999', '[email protected]', '123456');
測試專案
專案原始碼