使用maven已经有一段时间了,但项目是别人搭建好的,因此一直想着自己要学习搭建一下。网上找了些资料后,结合自己实验,花了点时间就搞好,老样子,写在博客上,免得日后忘记。
博文中的代码:链接:http://pan.baidu.com/s/1o8tqIMI 密码:m3si
1.安装maven和配置
1、下载maven.apache.org/download.html,下载apache-maven-3.1.1-bin.zip,**-src.zip为Maven的源码
2、配置环境变量,打开系统环境变量新建一个M2_HOME将解压后的Maven存放路径放在此,然后在path路径下加
入史%M2_HOME%\bin路径
3、检测是否配置成功,打开命令行输入echo %M2_HOME%查看M2_HOME指向的Maven存放安装目录是否正
确,输入mvn -v查看是否能找到正确的mvn执行脚本
4、以后升级的话将M2_HOME的路径换为最新的安装目录就行
5、Maven实践:初次安装完后输入mvn help:system的命令,此时会打印出所有的Java系统属性和环境变量,然后
Maven会执行一个真正的任务将相应的所需的构件下载到本地仓库中包括pom和jar文件,然后用户在
C:\Users\Administrator\.m2下就能看到本地仓库了
6、用户需要复制M2_HOME/conf/setting.xml文件到C:/Users/Administrator/.m2/setting.xml,这样用户每次升
级后就不要在次修改setting.xml文件了
2.MyEclipse配置Maven
1、在本地创建一个文件夹MavenRepository,并在MavenRepository文件夹下创建文件夹repo。
2、进入Maven解压后的文件夹,进入conf文件夹,将settings.xml文件复制到上一步创建的MavenRepository文件
夹下
3、打开MavenRepository文件夹下的settings.xml文件,找到localRepository标签,此时是被注释掉的,我们解除
注释,然后配置步骤1中的repo路径,如E:\MavenRepository\repo
4、在MyEclipse中的Perferences进行如下配置,添加自己的Maven
5、User Settings设置为之前修改过的setting.xml
6、File->New->others,搜索maven,如果看到有Maven Project则代表配置成功。
3.MyEclipse使用maven创建web项目
1、创建一个maven项目
2、按照上面教程,即可创建出一个Maven项目,项目结构如下图
3、将JRE版本设置为1.7,可使用默认的或者自己导入
4、此时index.jsp会报以下错误
在pom.xml文件的dependencies节点下添加如下代码即可,添加完后,会下载对应的jar包
5、右键项目,选择Properties,进行如下配置
4.搭建Spring+SpringMVC+Mybatis框架
1、Maven引入项目用到的jar包,修改pom.xml后保存会自动下载,存放在之前配置的本地仓库中,即:
E:\MavenRepository\repo文件夹
pom.xml
2、在src/main/resources下添加如下配置文件
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: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:annotation-config />
-
-
- <context:component-scan base-package="com.chillax" />
-
-
- <import resource="spring-dao.xml"/>
-
-
- <import resource="spring-db.xml"/>
-
-
- <import resource="spring-tx.xml"/>
-
- beans>
jdbc.properties,有多人反映直接复制时,第一行的driver最后面多了个空格,请注意
- driver=com.mysql.jdbc.Driver
- url=jdbc:mysql://127.0.0.1:3306/maventest
- username=root
- password=root
- #定义初始连接数
- initialSize=0
- #定义最大连接数
- maxActive=20
- #定义最大空闲
- maxIdle=20
- #定义最小空闲
- minIdle=1
- #定义最长等待时间
- maxWait=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
spring-dao.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">
-
-
-
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
-
- <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.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="${driver}" />
- <property name="url" value="${url}" />
- <property name="username" value="${username}" />
- <property name="password" value="${password}" />
-
- <property name="initialSize" value="${initialSize}">property>
-
- <property name="maxActive" value="${maxActive}">property>
-
- <property name="maxIdle" value="${maxIdle}">property>
-
- <property name="minIdle" value="${minIdle}">property>
-
- <property name="maxWait" value="${maxWait}">property>
- bean>
-
-
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
- <property name="dataSource" ref="dataSource" />
-
- <property name="mapperLocations" value="classpath:com/chillax/mapper/*.xml">property>
- bean>
-
- beans>
spring-tx.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">
-
-
- <bean id="transactionManager"
- class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
- <property name="dataSource" ref="dataSource" />
- bean>
-
- beans>
3、在WEB-INF文件夹下添加/修改以下配置文件
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">
-
-
- <bean id="mappingJacksonHttpMessageConverter"
- class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
- <property name="supportedMediaTypes">
- <list>
- <value>text/html;charset=UTF-8value>
- list>
- property>
- bean>
-
-
- <mvc:annotation-driven />
- <mvc:default-servlet-handler/>
-
-
- <context:component-scan base-package="com.chillax.controller" />
-
-
- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
- <property name="messageConverters">
- <list>
- <ref bean="mappingJacksonHttpMessageConverter" />
- list>
- property>
- bean>
-
-
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
-
- <property name="prefix" value="/WEB-INF/jsp/" />
- <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>
-
- beans>
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 Applicationdisplay-name>
-
- <welcome-file-list>
- <welcome-file>/index.jspwelcome-file>
- welcome-file-list>
-
-
- <context-param>
- <param-name>contextConfigLocationparam-name>
- <param-value>classpath:applicationContext.xmlparam-value>
- context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
- listener>
-
-
- <filter>
- <filter-name>encodingFilterfilter-name>
- <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
- <async-supported>trueasync-supported>
- <init-param>
- <param-name>encodingparam-name>
- <param-value>UTF-8param-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>encodingFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
-
-
- <servlet>
- <servlet-name>SpringMVCservlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
- <init-param>
- <param-name>contextConfigLocationparam-name>
- <param-value>/WEB-INF/spring-mvc.xmlparam-value>
- init-param>
- <load-on-startup>1load-on-startup>
- <async-supported>trueasync-supported>
- servlet>
- <servlet-mapping>
- <servlet-name>SpringMVCservlet-name>
- <url-pattern>/url-pattern>
- servlet-mapping>
-
- web-app>
4、在src/main/java下添加如下包和类
UserController.java
- package com.chillax.controller;
-
- import java.util.List;
-
- 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.chillax.dto.User;
- import com.chillax.service.IUserService;
-
- @Controller
- @RequestMapping("/user")
- public class UserController {
- @Resource
- private IUserService userService;
-
- @RequestMapping("/userList")
- public String userList(HttpServletRequest request,Model model){
- List uList = userService.getAllUser();
- model.addAttribute("uList", uList);
- return "userList";
- }
-
- @RequestMapping("/showUser")
- public String showUser(HttpServletRequest request,Model model){
- int userId = Integer.parseInt(request.getParameter("id"));
- User user = userService.getUserById(userId);
- model.addAttribute("user", user);
- return "showUser";
- }
-
- @RequestMapping("/addUserUI")
- public String addUserUI(){
- return "addUser";
- }
-
- @RequestMapping("/addUser")
- public String addUser(HttpServletRequest request,Model model){
- User user = new User();
- user.setName(String.valueOf(request.getParameter("name")));
- user.setPassword(String.valueOf(request.getParameter("password")));
- user.setAge(Integer.parseInt(String.valueOf(request.getParameter("age"))));
- userService.addUser(user);
- return "redirect:/user/userList";
- }
- }
IUserDao.java
- package com.chillax.dao;
-
- import java.util.List;
- import java.util.Map;
-
- import com.chillax.dto.User;
-
- public interface IUserDao {
-
- public User queryByPrimaryKey(Integer id);
-
- public List queryUserByBatch(Map params);
-
- public void insertUser(User user);
-
- public void insertUserByBatch(List list);
-
- public void deleteByPrimaryKey(Integer id);
-
- public void delteUserByBatch(Map params);
-
- public void updateByPrimaryKey(Integer id);
-
- public List getAllUser();
-
- }
User.java
- package com.chillax.dto;
-
- public class User {
- private Integer id;
-
- private String name;
-
- private String password;
-
- private Integer age;
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password == null ? null : password.trim();
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- this.age = age;
- }
- }
UserMapper.xml
- xml version="1.0" encoding="UTF-8" ?>
- >
- <mapper namespace="com.chillax.dao.IUserDao" >
- <resultMap id="BaseResultMap" type="com.chillax.dto.User">
- <result column="id" property="id" jdbcType="INTEGER" />
- <result column="name" property="name" jdbcType="VARCHAR" />
- <result column="password" property="password" jdbcType="VARCHAR" />
- <result column="age" property="age" jdbcType="INTEGER" />
- resultMap>
-
- <sql id="Base_Column_List">
- id, name, password, age
- sql>
-
-
- <select id="queryByPrimaryKey" resultMap="BaseResultMap"
- parameterType="java.lang.Integer">
- select
- <include refid="Base_Column_List" />
- from user
- where id = #{id,jdbcType=INTEGER}
- select>
-
-
- <select id="getAllUser" resultMap="BaseResultMap">
- select
- <include refid="Base_Column_List" />
- from user
- select>
-
-
- <select id="queryUserByBatch" resultMap="BaseResultMap"
- parameterType="java.util.Map">
- select
- <include refid="Base_Column_List" />
- from user
- where id in
- <foreach collection="idList" item="userId" index="index" open="(" separator="," close=")">
- #{userId,jdbcType=DECIMAL}
- foreach>
- select>
-
-
- <insert id="insertUser" parameterType="com.chillax.dto.User">
- insert into user
- <trim prefix="(" suffix=")" suffixOverrides="," >
- <if test="id != null" >
- id,
- if>
- <if test="name != null" >
- name,
- if>
- <if test="password != null" >
- password,
- if>
- <if test="age != null" >
- age,
- if>
- trim>
- <trim prefix="values (" suffix=")" suffixOverrides="," >
- <if test="id != null" >
- #{id,jdbcType=INTEGER},
- if>
- <if test="name != null" >
- #{name,jdbcType=VARCHAR},
- if>
- <if test="password != null" >
- #{password,jdbcType=VARCHAR},
- if>
- <if test="age != null" >
- #{age,jdbcType=INTEGER},
- if>
- trim>
- insert>
-
-
- <insert id="insertUserByBatch" parameterType="java.util.List" >
- insert into USER
- (ID,
- NAME,
- PASSWORD,
- AGE)
- select A.* from
- (
- <foreach collection="list" item="user" index="index" separator="union">
- select
- #{user.id,jdbcType=INTEGER},
- #{user.name,jdbcType=VARCHAR},
- #{user.password,jdbcType=VARCHAR},
- #{user.age,jdbcType=INTEGER}
- from dual
- foreach>
- ) A
- insert>
-
-
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
- delete from user
- where id = #{id,jdbcType=INTEGER}
- delete>
-
-
- <delete id="deleteUserByBatch" parameterType="java.util.Map" >
- delete from user
- where id IN
- <foreach item="ids" collection="iList" open="(" separator="," close=")">
- #{ids,jdbcType=DECIMAL}
- foreach>
- delete>
-
-
- <update id="updateByPrimaryKey" parameterType="com.chillax.dto.User" >
- update user
- <set >
- <if test="name != null" >
- name = #{name,jdbcType=VARCHAR},
- if>
- <if test="password != null" >
- password = #{password,jdbcType=VARCHAR},
- if>
- <if test="age != null" >
- age = #{age,jdbcType=INTEGER},
- if>
- set>
- where id = #{id,jdbcType=INTEGER}
- update>
-
- mapper>
IUserService.java
- package com.chillax.service;
-
- import java.util.List;
-
- import com.chillax.dto.User;
-
- public interface IUserService {
-
- public User getUserById(int userId);
-
- public void insertUser(User user);
-
- public void addUser(User user);
-
- public List getAllUser();
- }
UserServiceImpl.java
- package com.chillax.service.Impl;
-
- import java.util.List;
-
- import javax.annotation.Resource;
-
- import org.springframework.stereotype.Service;
-
- import com.chillax.dao.IUserDao;
- import com.chillax.dto.User;
- import com.chillax.service.IUserService;
-
- @Service("userService")
- public class UserServiceImpl implements IUserService {
- @Resource
- private IUserDao userDao;
-
- public User getUserById(int userId) {
- return userDao.queryByPrimaryKey(userId);
- }
-
- public void insertUser(User user) {
- userDao.insertUser(user);
- }
-
- public void addUser(User user) {
- userDao.insertUser(user);
- }
-
- @Override
- public List getAllUser() {
- return userDao.getAllUser();
- }
-
- }
5、在WEB-INF文件夹下创建jsp文件夹,并添加userList.jsp,showUser.jsp、addUser.jsp
userList.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- >
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'showUser.jsp' starting pagetitle>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
- head>
-
- <body>
- <c:forEach items="${uList }" var="u">
- 用户名称:${u.name}
- 用户年龄:${u.age }
- <br/>
- c:forEach>
- body>
- html>
addUser.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- >
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'addUser.jsp' starting pagetitle>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
- head>
-
- <body>
- <form id="addUser" action="user/addUser" method="post">
- userName: <input id="name" name="name" /><br/>
- password: <input id="password" name="password" /><br/>
- age: <input id="age" name="age"/><br/>
- <input type="submit" value="添加新用户"/>
- form>
- body>
- html>
showUser.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- >
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'showUser.jsp' starting pagetitle>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
-
-
- head>
-
- <body>
- ${user.name }<br>
- body>
- html>
- DROP TABLE IF EXISTS `user`;
-
- CREATE TABLE `user` (
- `id` int(12) NOT NULL AUTO_INCREMENT,
- `name` varchar(50) NOT NULL,
- `password` varchar(50) NOT NULL,
- `age` int(9) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;
-
-
- insert into `user`(`id`,`name`,`password`,`age`) values (1,'admin','admin',22);
7、整个项目文件结构图
8、部署发布项目,进行测试
至此,框架搭建完成
。
5.常见问题
问题1:pom.xml文件里的代码到哪里找?
解答:http://www.mvnrepository.com/
问题2:新建MAVEN项目过程中,出现下图错误?
解决:在MyEclipse的安装目录找到myeclipse.ini,将分配的内存加大
问题3:新建完工程后出现以下错误?
解答:在pom.xml添加以下代码即可,添加完代码就会自动下载好jar包
问题4:修改pom.xml时出现以下错误?
解答:这是由于jar包没有正确下载导致的,找到错误的jar包位置,将文件夹里的文件删掉,将pom.xml里该jar包的配置代码删除后再重新写上,让MAVEN重新下载jar包即可。
问题5:出现以下错误?
解答:
问题6:出现以下错误?
解答:将项目的jre版本换成1.7或者以上的版本即可