900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > eclipse maven 搭建 SSM(Spring+SpringMVC+MyBatis)开发环境 和 MyBatis 自动生成的 maven 插件配置

eclipse maven 搭建 SSM(Spring+SpringMVC+MyBatis)开发环境 和 MyBatis 自动生成的 maven 插件配置

时间:2018-11-01 05:24:48

相关推荐

eclipse maven 搭建 SSM(Spring+SpringMVC+MyBatis)开发环境 和 MyBatis 自动生成的 maven 插件配置

最近研究java web开发,首先需要配置好开发环境,查阅网上各位大神的文章后搭建完成,记录下来作为备忘。

1、安装Maven

Maven下载地址:/download.cgi

在eclipse window选项中选择Preference可以配置Maven。

具体可以参考如下步骤。

在Installations新建一项配置maven的安装目录:

国内Maven repository下载比较慢,可以配置conf\settings.xml新增repository镜像:

<mirrors><!-- mirror| Specifies a repository mirror site to use instead of a given repository. The repository that| this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used| for inheritance and direct lookup purposes, and must be unique across the set of mirrors.|<mirror><id>mirrorId</id><mirrorOf>repositoryId</mirrorOf><name>Human Readable Name for this Mirror.</name><url>/repo/path</url></mirror>--><mirror><id>alimaven</id><name>aliyun maven</name><url>/nexus/content/groups/public/</url><mirrorOf>central</mirrorOf> </mirror><mirror><id>repo1</id><name>repo1 maven</name><url>/maven2/</url><mirrorOf>central</mirrorOf> </mirror></mirrors>

2、建立maven web项目

在eclipse中新建Project ->Maven->Maven Project:

选择Workspace,这里我使用默认的Workspace:

选择maven-archetype-webapp:

定义Group Id和Artifact Id,Package为Group Id+Artifact Id:

右键点击项目选择Properties,首先修改Java Build Path:

选中左边Project Facet点击Convert faceted from...

如图所示依次选中各项:

选中左边新出现的Deployment Assembly,配置和下图类似:

选中左边Web Project Setting,确保Context root与项目名一致:

maven web项目建立完成,结构如下图:

3、搭建SSM环境

1、pom.xml配置项目依赖包

具体配置如下,可以作为参考,其中配置了maven 的 mybatis generator 插件后面可以用来自动生成DAO Entity 和 数据库映射xml。

<project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.hanwest.webapp</groupId><artifactId>ssmweb</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>ssmweb Maven Webapp</name><url></url><properties><!-- spring版本号 --><spring.version>4.0.2.RELEASE</spring.version><!-- mybatis版本号 --><mybatis.version>3.2.6</mybatis.version><!-- log4j日志文件管理包版本 --><slf4j.version>1.7.7</slf4j.version><log4j.version>1.2.17</log4j.version><mybatis.generator.version>1.3.5</mybatis.generator.version></properties><dependencies><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><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.2.2</version></dependency><!-- 导入java ee jar 包 --><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version></dependency><!-- 导入Mysql数据库链接jar包 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.30</version></dependency><!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 --><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.2.2</version></dependency><!-- JSTL标签类 --><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!-- 日志文件管理包 --><!-- log start --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><!-- 格式化对象,方便输出日志 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.41</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><!-- log end --><!-- 映入JSON --><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency><!-- 上传组件包 --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version></dependency><dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.9</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>${mybatis.generator.version}</version></dependency></dependencies><build><finalName>ssmweb</finalName><plugins><!-- mybatis generator maven插件 --><plugin><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-maven-plugin</artifactId><version>${mybatis.generator.version}</version><configuration><configurationFile>src/main/resources/generatorConfig.xml</configurationFile><verbose>true</verbose><overwrite>true</overwrite></configuration><!-- executions> <execution> <id>Generate MyBatis Artifacts</id> <goals> <goal>generate</goal> </goals> </execution> </executions --><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.30</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>${mybatis.generator.version}</version></dependency></dependencies></plugin></plugins></build></project>

修改配置后保存,就会开始自动下载各种依赖的jar包。

2、配置mybatis

在src/main/resources中新建jdbc配置文件jdbc.properties(注意配置文件转为UTF-8并且行尾不能有空格)

driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/testssmdbusername=rootpassword=#定义初始连接数initialSize=0#定义最大连接数maxActive=20#定义最大空闲maxIdle=20#定义最小空闲minIdle=1#定义最长等待时间maxWait=60000

在src/main/resources中新建mybatis配置文件spring-mybatis.xml(注意包名改为当前项目的包名)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-3.1.xsd /schema/context /schema/context/spring-context-3.1.xsd /schema/mvc /schema/mvc/spring-mvc-4.0.xsd"><!-- 自动扫描 --><context:component-scan base-package="cn.hanwest.webapp.ssmweb" /><!-- 引入配置文件 --><bean id="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location" value="classpath:jdbc.properties" /></bean><bean id="dataSource" class="mons.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><!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><!-- 自动扫描mapping.xml文件 --><property name="mapperLocations" value="classpath:cn/hanwest/webapp/ssmweb/mapping/*.xml"></property></bean><!-- DAO接口所在包名,Spring会自动查找其下的类 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="cn.hanwest.webapp.testssmweb.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>

3、使用maven mybatis generator自动生成DAO Entity 和 mapper xml

在mysql中建表

CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(255) DEFAULT NULL,`nickname` varchar(255) DEFAULT NULL,`password` varchar(255) DEFAULT NULL,`create_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,`phone` varchar(127) DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8

在src/main/resources中新建配置文件generatorConfig.xml(注意包名改为当前项目的包名以及修改xml中的jdbc配置)

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC "-////DTD MyBatis Generator Configuration 1.0//EN""/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><!--数据库驱动 --><context id="DB2Tables" targetRuntime="MyBatis3"><commentGenerator><property name="suppressDate" value="true" /><property name="suppressAllComments" value="true" /></commentGenerator><!--数据库链接地址账号密码 --><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://127.0.0.1:3306/testssmdb" userId="root"password=""></jdbcConnection><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!--生成Model类存放位置 --><javaModelGenerator targetPackage="cn.hanwest.webapp.ssmweb.entity"targetProject="src/main/java"><property name="enableSubPackages" value="true" /><property name="trimStrings" value="true" /></javaModelGenerator><!--生成映射文件存放位置 --><sqlMapGenerator targetPackage="cn.hanwest.webapp.ssmweb.mapping"targetProject="src/main/java"><property name="enableSubPackages" value="true" /></sqlMapGenerator><!--生成Dao类存放位置 --><javaClientGenerator type="XMLMAPPER"targetPackage="cn.hanwest.webapp.ssmweb.dao" targetProject="src/main/java"><property name="enableSubPackages" value="true" /></javaClientGenerator><!--生成对应表及类名 --><table tableName="user" domainObjectName="User"enableCountByExample="false" enableUpdateByExample="false"enableDeleteByExample="false" enableSelectByExample="false"selectByExampleQueryId="false"></table></context></generatorConfiguration>

建立和配置文件中响应的包名,结构与下图类似

右键点击项目选择Run As Maven Build...(注意有...)

在出现的窗口中Goals:输入mybatis-generator:generate -X 点击Run执行

执行完成后可以看到Console中有类似的log并且在相应的包中会生成java文件

自动生成成功。

4、配置spring mvc

分别建立controller、servcie类

UserController.java

package cn.hanwest.webapp.ssmweb.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 org.springframework.web.bind.annotation.RequestMethod;import cn.hanwest.webapp.ssmweb.entity.User;import cn.hanwest.webapp.ssmweb.service.UserService;@Controller@RequestMapping("/user")public class UserController {@Resourceprivate UserService userService;@RequestMapping("/profile")public String profile(HttpServletRequest request, Model model) {String idStr = request.getParameter("id");if(null != idStr && "".equals(idStr.trim())){int userId = Integer.valueOf(idStr);User user = this.userService.getUserById(userId);model.addAttribute("user", user);return "User/profile";} else {return "index";}}@RequestMapping("/register")public String register(HttpServletRequest request, Model model) {return "User/register";}@RequestMapping(value="/register", method=RequestMethod.POST)public String doRegister(HttpServletRequest request, Model model) {String username = request.getParameter("username");String nickname = request.getParameter("nickname");String password = request.getParameter("password");String phone = request.getParameter("phone");User user = new User();user.setUsername(username);user.setPassword(password);user.setPhone(phone);user.setNickname(nickname);int id = userService.addUser(user);return String.format("User/profile?id=%d", id);}}

UserService.java

package cn.hanwest.webapp.ssmweb.service;import cn.hanwest.webapp.ssmweb.entity.User;public interface UserService {public User getUserById(int userId);public int addUser(User user);}

UserServiceImpl.java

package cn.hanwest.webapp.ssmweb.service.impl;import javax.annotation.Resource;import org.springframework.stereotype.Service;import cn.hanwest.webapp.ssmweb.dao.UserMapper;import cn.hanwest.webapp.ssmweb.entity.User;import cn.hanwest.webapp.ssmweb.service.UserService;@Service("userService")public class UserServiceImpl implements UserService{@Resource private UserMapper userDao; @Overridepublic User getUserById(int userId) {// TODO Auto-generated method stubreturn userDao.selectByPrimaryKey(userId);}@Overridepublic int addUser(User user) {// TODO Auto-generated method stubreturn userDao.insertSelective(user);}}

在src/main/webapp/WEB-INF中建立视图文件

profile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>测试</title></head><body>${user.userName}</body></html>

register.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>注册</title></head><body><form action="" method="POST"><input name="username" type="text" value="hanx" /><br /><input name="nickname" type="text" value="hanx" /><br /><input name="password" type="password" value="hanx" /><br /><input name="phone" type="text" value="hanx" /><br /><input type="submit" value="submit" /></form></body></html>

在src/main/resources中新建配置文件spring-mvc.xml(注意包名改为当前项目的包名)

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:mvc="/schema/mvc"xsi:schemaLocation="/schema/beans /schema/beans/spring-beans-3.1.xsd /schema/context /schema/context/spring-context-3.1.xsd /schema/mvc /schema/mvc/spring-mvc-4.0.xsd"><!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 --><context:component-scan base-package="cn.hanwest.webapp.ssmweb.controller" /><!-- 注册HandlerMapper、HandlerAdapter两个映射类 --><mvc:annotation-driven /><!-- 访问静态资源 --><mvc:default-servlet-handler /><!--避免IE执行AJAX时,返回JSON出现下载文件 --><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value></list></property></bean><!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 --></list></property></bean><!-- 定义跳转的文件的前后缀 ,视图模式配置 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /><!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 --><property name="prefix" value="/WEB-INF/" /><property name="suffix" value=".jsp" /></bean><!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --><bean id="multipartResolver"class="org.springframework.monsMultipartResolver"><!-- 默认编码 --><property name="defaultEncoding" value="utf-8" /><!-- 文件大小最大值 --><property name="maxUploadSize" value="10485760000" /><!-- 内存中的最大值 --><property name="maxInMemorySize" value="40960" /></bean></beans>

修改src/main/webapp/WEB-INF中的web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance"xmlns="/xml/ns/javaee"xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_0.xsd"version="3.0"><display-name>Archetype Created Web Application</display-name><!-- Spring和mybatis的配置文件 --><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><!-- Spring监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 防止Spring内存溢出监听器 --><listener><listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class></listener><!-- Spring MVC servlet --><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><!-- 此处可以可以配置成*.do,对应struts的后缀习惯 --><url-pattern>/</url-pattern></servlet-mapping><welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list></web-app>

右键点击项目Run As -》Run on Server输入user/register访问成功说明框架配置基本完成,如有问题请排查。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。