动机
使用maven已经有一段时间了,但项目是别人搭建好的,因此一直想着自己要学习搭建一下。网上找了些资料后,结合自己实验,花了点时间就搞好,老样子,写在博客上,免得日后忘记。
本文链接:/v123411739/article/details/50742885
博文中的MyEclipse链接:/s/1pMhiygz 密码:mqmc
博文中的完整项目代码:关注微信公众号发送“SSM”即可获得。
注:文末有直接导入项目的方法。
1.安装maven和配置(此步骤并非必须,可以根据情况选择)
进入官网下载中心/download.cgi,下载apache-maven-3.5.2-bin.zip,**-src.zip为Maven的源码配置环境变量,打开系统环境变量新建一个M2_HOME将解压后的Maven存放路径放在此,然后在path路径加入%M2_HOME%\bin路径检测是否配置成功,打开命令行输入echo %M2_HOME%查看M2_HOME指向的Maven存放安装目录是否正确,输入mvn -v查看是否能找到正确的mvn执行脚本以后升级的话将M2_HOME的路径换为最新的安装目录就行Maven实践:初次安装完后输入mvn help:system的命令,此时会打印出所有的Java系统属性和环境变量,然后Maven会执行一个真正的任务将相应的所需的构件下载到本地仓库中包括pom和jar文件,然后用户在C:\Users\Administrator\.m2下就能看到本地仓库了用户需要复制M2_HOME/conf/setting.xml文件到C:/Users/Administrator/.m2/setting.xml,这样用户每次升级后就不要在次修改setting.xml文件了2.MyEclipse配置Maven
在本地创建一个文件夹MavenRepository,并在MavenRepository文件夹下创建文件夹repository。进入Maven解压后的文件夹,进入conf文件夹,将settings.xml文件复制到上一步创建的MavenRepository文件夹下打开MavenRepository文件夹下的settings.xml文件,找到localRepository标签,此时是被注释掉的,我们解除注释,然后配置步骤1中的repository路径,如<localRepository>F:\m2\repository</localRepository>在MyEclipse中的Perferences进行如下配置,添加自己的MavenUser Settings设置为之前修改过的setting.xmlFile->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后保存会自动下载,存放在之前配置的本地仓库中,即:F:\m2\repository文件夹
pom.xml
[html]view plaincopy
<projectxmlns="/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>com.chillax</groupId><artifactId>Maven_Project</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>Maven_ProjectMavenWebapp</name><url></url><!--用来设置版本号--><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></properties><!--用到的jar包--><dependencies><!--单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><!--表示开发的时候引入,发布的时候不会加载此包--><scope>test</scope></dependency><!--javaee包--><dependency><groupId>javax</groupId><artifactId>javaee-api</artifactId><version>7.0</version></dependency><!--spring框架包start--><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><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${srping.version}</version></dependency><!--spring框架包end--><!--mybatis框架包start--><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框架包end--><!--数据库驱动--><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><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><!--logstart--><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><!--logEND--><!--Json--><!--格式化对象,方便输出日志--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.6</version></dependency><dependency><groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.9.13</version></dependency><!--上传组件包start--><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.10</version></dependency><!--上传组件包end--><!--AL相关添加--><dependency><groupId>net.sourceforge.jexcelapi</groupId><artifactId>jxl</artifactId><version>2.6</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.9</version></dependency><!--AL相关添加--></dependencies><build><finalName>Maven_Project</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.3.2</version><configuration><source>1.7</source><target>1.7</target></configuration></plugin></plugins></build></project>
2、在src/main/resources下添加如下配置文件
applicationContext.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="/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:annotation-config/><!--自动扫描--><context:component-scanbase-package="com.chillax"/><!--导入DAO配置--><importresource="spring-dao.xml"/><!--导入数据库配置--><importresource="spring-db.xml"/><!--导入数据库配置--><importresource="spring-tx.xml"/></beans>
jdbc.properties,有多人反映直接复制时,第一行的driver最后面多了个空格,请注意
[html]view plaincopy
driver=com.mysql.jdbc.Driverurl=jdbc:mysql://127.0.0.1:3306/maventestusername=rootpassword=root#定义初始连接数initialSize=0#定义最大连接数maxActive=20#定义最大空闲maxIdle=20#定义最小空闲minIdle=1#定义最长等待时间maxWait=60000
log4j.properties
[html]view plaincopy
#定义LOG输出级别log4j.rootLogger=INFO,Console,File#定义日志输出目的地为控制台log4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.Target=System.out#可以灵活地指定日志输出格式,下面一行是指定具体的格式log4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.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=ALLlog4j.appender.File.layout=org.apache.log4j.PatternLayoutlog4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-ddHH\:mm\:ss}][%c]%m%n
spring-dao.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="/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"><!--DAO接口所在包名,Spring会自动查找其下的类--><beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--basePackage指定要扫描的包,在此包之下的映射器都会被搜索到。可指定多个包,包与包之间用逗号或分号分隔--><propertyname="basePackage"value="com.chillax.dao"/><propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"></property></bean></beans>
spring-db.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="/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"><!--引入配置文件--><beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><propertyname="location"value="classpath:jdbc.properties"/></bean><beanid="dataSource"class="mons.dbcp.BasicDataSource"destroy-method="close"><propertyname="driverClassName"value="${driver}"/><propertyname="url"value="${url}"/><propertyname="username"value="${username}"/><propertyname="password"value="${password}"/><!--初始化连接大小--><propertyname="initialSize"value="${initialSize}"></property><!--连接池最大数量--><propertyname="maxActive"value="${maxActive}"></property><!--连接池最大空闲--><propertyname="maxIdle"value="${maxIdle}"></property><!--连接池最小空闲--><propertyname="minIdle"value="${minIdle}"></property><!--获取连接最大等待时间--><propertyname="maxWait"value="${maxWait}"></property></bean><!--spring和MyBatis完美整合,不需要mybatis的配置映射文件--><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"/><!--自动扫描mapping.xml文件--><propertyname="mapperLocations"value="classpath:com/chillax/mapper/*.xml"></property></bean></beans>
spring-tx.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:p="/schema/p"xmlns:context="/schema/context"xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"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/aop/schema/aop/spring-aop-3.1.xsd/schema/tx/schema/tx/spring-tx-3.1.xsd"><!--(事务管理)transactionmanager,useJtaTransactionManagerforglobaltx--><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="dataSource"/></bean><!--配置参与事务的类--><aop:config><aop:pointcutid="allServiceMethod"expression="execution(*com.chillax.service.*.*(..))"/><aop:advisorpointcut-ref="allServiceMethod"advice-ref="TxAdvice"/></aop:config><!--使用声明方式配置事务--><tx:adviceid="TxAdvice"transaction-manager="transactionManager"><tx:attributes><tx:methodname="*"propagation="REQUIRED"rollback-for="java.lang.Exception"/></tx:attributes></tx:advice></beans>
3、在WEB-INF文件夹下添加/修改以下配置文件
spring-mvc.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="/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"><!--添加注解驱动--><mvc:annotation-driven/><mvc:default-servlet-handler/><!--设置使用注解的类所在的包--><context:component-scanbase-package="com.chillax.controller"/><!--定义跳转的文件的前后缀,视图模式配置--><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><!--这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个可用的url地址--><propertyname="prefix"value="/WEB-INF/jsp/"/><propertyname="suffix"value=".jsp"/></bean><!--SpringMVC上传文件时,需要配置MultipartResolver处理器--><beanid="multipartResolver"class="org.springframework.monsMultipartResolver"><!--默认编码--><propertyname="defaultEncoding"value="utf-8"/><!--文件大小最大值--><propertyname="maxUploadSize"value="10485760000"/><!--内存中的最大值--><propertyname="maxInMemorySize"value="40960"/></bean></beans>
web.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><web-appxmlns: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>ArchetypeCreatedWebApplication</display-name><welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list><!--加载springbean--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--编码过滤器--><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><!--SpringMVCservlet--><servlet><servlet-name>SpringMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/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></web-app>
4、在src/main/java下添加如下包和类
UserController.java
[java]view plaincopy
packagecom.chillax.controller;importjava.util.List;importjavax.annotation.Resource;importjavax.servlet.http.HttpServletRequest;importorg.springframework.stereotype.Controller;importorg.springframework.ui.Model;importorg.springframework.web.bind.annotation.RequestMapping;importcom.chillax.dto.User;importcom.chillax.service.IUserService;@Controller@RequestMapping("/user")publicclassUserController{@ResourceprivateIUserServiceuserService;@RequestMapping("/userList")publicStringuserList(HttpServletRequestrequest,Modelmodel){List<User>uList=userService.getAllUser();model.addAttribute("uList",uList);return"userList";}@RequestMapping("/showUser")publicStringshowUser(HttpServletRequestrequest,Modelmodel){intuserId=Integer.parseInt(request.getParameter("id"));Useruser=userService.getUserById(userId);model.addAttribute("user",user);return"showUser";}@RequestMapping("/addUserUI")publicStringaddUserUI(){return"addUser";}@RequestMapping("/addUser")publicStringaddUser(HttpServletRequestrequest,Modelmodel){Useruser=newUser();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
[java]view plaincopy
packagecom.chillax.dao;importjava.util.List;importjava.util.Map;importcom.chillax.dto.User;publicinterfaceIUserDao{publicUserqueryByPrimaryKey(Integerid);publicList<User>getAllUser();publicvoidinsertUser(Useruser);publicvoidinsertUserByBatch(List<User>list);publicvoiddeleteByPrimaryKey(Integerid);publicvoiddelteUserByBatch(Map<String,Object>params);publicvoidupdateByPrimaryKey(Useruser);}
User.java
[java]view plaincopy
packagecom.chillax.dto;publicclassUser{privateIntegerid;privateStringname;privateStringpassword;privateIntegerage;publicIntegergetId(){returnid;}publicvoidsetId(Integerid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicStringgetPassword(){returnpassword;}publicvoidsetPassword(Stringpassword){this.password=password==null?null:password.trim();}publicIntegergetAge(){returnage;}publicvoidsetAge(Integerage){this.age=age;}}
UserMapper.xml
[html]view plaincopy
<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-////DTDMapper3.0//EN""/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.chillax.dao.IUserDao"><resultMapid="BaseResultMap"type="com.chillax.dto.User"><resultcolumn="id"property="id"jdbcType="INTEGER"/><resultcolumn="name"property="name"jdbcType="VARCHAR"/><resultcolumn="password"property="password"jdbcType="VARCHAR"/><resultcolumn="age"property="age"jdbcType="INTEGER"/></resultMap><sqlid="Base_Column_List">id,name,password,age</sql><!--查询用户--><selectid="queryByPrimaryKey"resultMap="BaseResultMap"parameterType="java.lang.Integer">select<includerefid="Base_Column_List"/>fromuserwhereid=#{id,jdbcType=INTEGER}</select><!--查询用户--><selectid="getAllUser"resultMap="BaseResultMap">select<includerefid="Base_Column_List"/>fromuser</select><!--插入用户--><insertid="insertUser"parameterType="com.chillax.dto.User">insertintouser<trimprefix="("suffix=")"suffixOverrides=","><iftest="id!=null">id,</if><iftest="name!=null">name,</if><iftest="password!=null">password,</if><iftest="age!=null">age,</if></trim><trimprefix="values("suffix=")"suffixOverrides=","><iftest="id!=null">#{id,jdbcType=INTEGER},</if><iftest="name!=null">#{name,jdbcType=VARCHAR},</if><iftest="password!=null">#{password,jdbcType=VARCHAR},</if><iftest="age!=null">#{age,jdbcType=INTEGER},</if></trim></insert><!--批量插入用户--><insertid="insertUserByBatch"parameterType="java.util.List">insertintoUSER(ID,NAME,PASSWORD,AGE)selectA.*from(<foreachcollection="list"item="user"index="index"separator="union">select#{user.id,jdbcType=INTEGER},#{user.name,jdbcType=VARCHAR},#{user.password,jdbcType=VARCHAR},#{user.age,jdbcType=INTEGER}fromdual</foreach>)A</insert><!--删除用户--><deleteid="deleteByPrimaryKey"parameterType="java.lang.Integer">deletefromuserwhereid=#{id,jdbcType=INTEGER}</delete><!--批量删除用户--><deleteid="deleteUserByBatch"parameterType="java.util.Map">deletefromuserwhereidIN<foreachitem="ids"collection="iList"open="("separator=","close=")">#{ids,jdbcType=DECIMAL}</foreach></delete><!--更新用户--><updateid="updateByPrimaryKey"parameterType="com.chillax.dto.User">updateuser<set><iftest="name!=null">name=#{name,jdbcType=VARCHAR},</if><iftest="password!=null">password=#{password,jdbcType=VARCHAR},</if><iftest="age!=null">age=#{age,jdbcType=INTEGER},</if></set>whereid=#{id,jdbcType=INTEGER}</update></mapper>
IUserService.java
[java]view plaincopy
packagecom.chillax.service;importjava.util.List;importcom.chillax.dto.User;publicinterfaceIUserService{publicUsergetUserById(intuserId);publicvoidinsertUser(Useruser);publicvoidaddUser(Useruser);publicList<User>getAllUser();}
UserServiceImpl.java
[java]view plaincopy
packagecom.chillax.service.Impl;importjava.util.List;importjavax.annotation.Resource;importorg.springframework.stereotype.Service;importcom.chillax.dao.IUserDao;importcom.chillax.dto.User;importcom.chillax.service.IUserService;@Service("userService")publicclassUserServiceImplimplementsIUserService{@ResourceprivateIUserDaouserDao;publicUsergetUserById(intuserId){returnuserDao.queryByPrimaryKey(userId);}publicvoidinsertUser(Useruser){userDao.insertUser(user);}publicvoidaddUser(Useruser){userDao.insertUser(user);}@OverridepublicList<User>getAllUser(){returnuserDao.getAllUser();}}
5、在WEB-INF文件夹下创建jsp文件夹,并添加userList.jsp,showUser.jsp、addUser.jsp
userList.jsp
[html]view plaincopy
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%><%@taglibprefix="c"uri="/jsp/jstl/core"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>MyJSP'showUser.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--<linkrel="stylesheet"type="text/css"href="styles.css">--></head><body><c:forEachitems="${uList}"var="u">用户名称:${u.name}用户年龄:${u.age}<br/></c:forEach></body></html>
addUser.jsp
[html]view plaincopy
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>MyJSP'addUser.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--<linkrel="stylesheet"type="text/css"href="styles.css">--></head><body><formid="addUser"action="user/addUser"method="post">userName:<inputid="name"name="name"/><br/>password:<inputid="password"name="password"/><br/>age:<inputid="age"name="age"/><br/><inputtype="submit"value="添加新用户"/></form></body></html>
showUser.jsp
[html]view plaincopy
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%><%Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"><html><head><basehref="<%=basePath%>"><title>MyJSP'showUser.jsp'startingpage</title><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache"><metahttp-equiv="expires"content="0"><metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"><metahttp-equiv="description"content="Thisismypage"><!--<linkrel="stylesheet"type="text/css"href="styles.css">--></head><body>${user.name}<br></body></html>
6、创建数据库,并创建表
[sql]view plaincopy
createdatabasemaventest;usemaventest;CREATETABLE`user`(`id`int(12)NOTNULLAUTO_INCREMENT,`name`varchar(50)NOTNULL,`password`varchar(50)NOTNULL,`age`int(9)NOTNULL,PRIMARYKEY(`id`))ENGINE=InnoDBAUTO_INCREMENT=12DEFAULTCHARSET=utf8;insertinto`user`(`id`,`name`,`password`,`age`)values(1,'admin','admin',22);
7、整个项目文件结构图
8、部署发布项目,进行测试
至此,框架搭建完成。
5.常见问题
问题1:pom.xml文件里的代码到哪里找?
解答:/
问题2:新建MAVEN项目过程中,出现下图错误?
解决:在MyEclipse的安装目录找到myeclipse.ini,将分配的堆内存加大
问题3:新建完工程后出现以下错误?
解答:在pom.xml添加以下代码即可,添加完代码就会自动下载好jar包
问题4:修改pom.xml时出现以下错误?
解答:这是由于jar包没有正确下载导致的,找到错误的jar包位置,将文件夹里的文件删掉,将pom.xml里该jar包的配置代码删除后再重新写上,让MAVEN重新下载jar包即可。
问题5:出现以下错误?
解答:
问题6:出现以下错误?
解答:将项目的jre版本换成1.7或者以上的版本即可
问题7:出现以下错误,并且已经确定jre是1.7版本或者以上版本。
解答:在pom.xml文件的<build></build>的标签中加入以下代码,然后Update Project(参照问题5)
[java]view plaincopy
<build><finalName>Maven_Project</finalName><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>2.3.2</version><configuration><source>1.7</source><target>1.7</target></configuration></plugin></plugins></build>
问题8:访问报错
解答:请确认地址中的项目,跟项目中的WebContext-root地址一致。
问题9:直接导入代码报错
解答:如果想直接导入代码需要先做文章开头的1和2两步,即用一个自己的新的仓库来存储jar包,不然容易跟已有的仓库配置冲突,导致jar包无法下载或下载不全。下图是我导入的过程,下载jar的过程比较慢,并且下载完了还报错,但是报错并不影响项目的正确运行。
—————END—————
如果觉得《SSM框架详细整合教程(Spring+SpringMVC+MyBatis)》对你有帮助,请点赞、收藏,并留下你的观点哦!