spring mvc + mybaties+ mysql搭建--2016版

来源:互联网 发布:h3c配置vlan多个端口 编辑:程序博客网 时间:2024/06/05 00:24

为了熟悉spring mvc和mybatis框架的搭建。自己决定,亲手从0开始搭建。


1:新建一个webproject ,这个不用多说。会eclipse的都会建的。


2:找到搭建项目所需要的包(这里有个原则,一开始并不是很清楚知道要用哪些包,但心里大概要清楚spring的常用包,比如srping-core,spring-beans,spring-aop,spring-tx,spring-contenxt,spring-context-support,spring-jdbc,spring-test,spring-web,spring-webmvc,还有既然有mysql。那就需要mysql-connector-java.既然用到mybties了,那就需要mybaties-spring...log日志相关的olf4j。等等, 还有,如果缺少哪个包,项目启动会报错,这个只有根椐错误来填补缺少的jar包,我这次搭建也遇到缺少jar包的情况好几次,根椐错误来下载缺少的包就可以,下载jar包有个很好的网站http://search.maven.org/,如果你目前所在公司的项目有这些常用包,就直接拿来用吧,省的下载了,我其实就是直接拿来用的大笑,下面我贴下我这次搭建用到的包。



3:新建好的项目结构如下图




4:新建springmvc-servlet文件。

<pre name="code" class="html"><?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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util"xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.chain.controller" /><!-- 启动对@AspectJ注解的支持 --><!-- <aop:aspectj-autoproxy proxy-target-class="true" /> --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><beanclass="org.springframework.http.converter.StringHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/plain;charset=UTF-8</value><value>application/json;charset=UTF-8</value></list></property></bean><beanclass="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean></list></property></bean><!-- 只能用于springMVC,用于配置springMVC的注解驱动 @RequestMapping, @Controller, although support for those is the default behaviour), as well as adding support for declrative validation via @Valid and message body marshalling with @RequestBody/ResponseBody.--><mvc:annotation-driven /><bean id="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix"><value>/WEB-INF/jsp/</value></property><property name="suffix"><value>.jsp</value></property></bean></beans>


5:新建srping的配置文件application.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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util"xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.chain.service" />   <!-- 引入配置文件 -->      <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="location" value="classpath:properties/jdbc.properties" />      </bean>  </beans>

6:新建jdbc.proptertis配置文件

jdbc.url=jdbc\:mysql\://localhost\:3306/ksfulife?useUnicode\=true&characterEncoding\=UTF-8&allowMultiQueries\=true
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
dataSource.initialSize=10
dataSource.maxIdle=20
dataSource.minIdle=5
dataSource.maxActive=50
dataSource.logAbandoned=true
dataSource.removeAbandoned=true
dataSource.removeAbandonedTimeout=180
dataSource.maxWait=2000


7:新建spring与mybaties配置文件 spring-resource.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:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:util="http://www.springframework.org/schema/util"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">    <!-- 数据库连接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"><property name="driverClass" value="${jdbc.driver}"></property><property name="jdbcUrl" value="${jdbc.url}"></property><property name="user" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property><property name="maxPoolSize" value="10"></property>        <property name="minPoolSize" value="10"></property>        <property name="initialPoolSize" value="10"></property>        <property name="maxIdleTime" value="20"></property>        <property name="acquireIncrement" value="5"></property>        <property name="idleConnectionTestPeriod" value="60"></property>        <property name="preferredTestQuery" value="select 1"></property></bean><!-- spring与mybaties --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"     p:dataSource-ref="dataSource" p:configLocation="classpath:config/mybatis-config.xml" p:mapperLocations="classpath:mapping/*.xml"/> <!-- mapping文件,里面定义了dao.和相关方法的sql实现 --><!-- 自动扫描了所有的XxxxMapper.java,这样就不用一个一个手动配置Mpper的映射了,只要Mapper接口类和Mapper映射文件对应起来就可以了。 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.chain.dao" /><property name="sqlSessionFactoryBeanName"  value="sqlSessionFactory" /></bean><!-- 事务管理器 该类在spring-jdbc-3.2.4.RELEASE.jar包下--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 使用annotation注解方式配置事务 -->       <!-- <tx:annotation-driven proxy-target-class="true" transaction-manager="transactionManager" /> -->        <!-- 声明式事务 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>        <!-- -所有方法启用事务 -->            <tx:method name="*" propagation="REQUIRED" />        </tx:attributes>    </tx:advice>        <aop:config expose-proxy="true">        <!-- 只对业务逻辑层实施事务 注意*和“com.chain.service”这里之间需要一个空格-->        <aop:pointcut id="txPointcut" expression="execution(*  com.chain.service.*.*(..))" />        <!-- Advisor定义,切入点和通知分别为txPointcut、txAdvice -->        <aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>    </aop:config></beans>


8.新建login-mapping.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.chain.dao.ILoginDao"><select id="login" parameterType="com.chain.dto.OperatorDto" resultType="com.chain.dto.OperatorDto">select operate_code as operateCode ,md5_password as password from op_operatorwhere operate_code = #{operateCode} and md5_password = #{password}</select></mapper>



9:新建mybaties配置文件mybatis-config.xml

<?xml version="1.0" encoding="GBK"?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><!-- 基础设置 --><settings><!-- changes from the defaults,全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 --><setting name="lazyLoadingEnabled" value="false" /></settings><!-- 自定义类型转换器 --><!-- <typeHandlers><typeHandler javaType="Boolean" jdbcType="CHAR" handler="com.sfpay.product.dao.BooleanTypeHandler" /></typeHandlers> --><!-- SQL映射文件 --><mappers><!-- <mapper resource="mapping/login-mapping.xml" /> --></mappers></configuration>

10

编辑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_2_5.xsd"id="WebApp_ID" version="2.5"><display-name>spmvc</display-name><!-- 加载spring配置文件,mabaties数据库配置文件,多个文件用分号隔开 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:/applicaiton.xml;                classpath*:resource/spring-resource.xml   </param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 加载springmvc配置文件。默认文件名-servlet.xml.我这里自定义的文件名跟默认名一样,也可以改一个名字 --><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/springmvc-servlet.xml            </param-value></init-param><init-param><param-name>dispatchOptionsRequest</param-name><param-value>true</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!-- 字符集过滤器 --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>

11:新建LoginController.java

package com.chain.controller;import javax.annotation.Resource;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import com.chain.dto.OperatorDto;import com.chain.service.ILoginService;/** *@author chenlijiang2016年3月23日上午9:35:30 */@Controllerpublic class LoginController {private Logger logger = LoggerFactory.getLogger(this.getClass());@Resourceprivate ILoginService loginService; 
<span style="white-space:pre"></span>//这里为了方便浏览器测试,把方法置为get方式的。@RequestMapping(value="/login/login", method=RequestMethod.GET,produces="applicaiton/json")public String login(@RequestParam String username,@RequestParam String password) {logger.info("登陆开始.........................");OperatorDto operatorDto = new OperatorDto();operatorDto.setOperateCode(username);operatorDto.setPassword(password);String resultStr = loginService.login(operatorDto);if ("success".equals(resultStr)) {return "success";} else {return "faliled";}}}

12,新建service.   ILoginSerce

package com.chain.service;import com.chain.dto.OperatorDto;public interface ILoginService {public String login(OperatorDto operatorDto);}

13.新建loginServiceImpl

package com.chain.service;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.chain.dao.ILoginDao;import com.chain.dto.OperatorDto;@Service("loginService")public class LoginServiceImpl implements ILoginService {@Resource ILoginDao loginDao;public String login(OperatorDto operatorDto) {OperatorDto operatorDto2 = new OperatorDto(); operatorDto2 = loginDao.login(operatorDto);if (operatorDto2!=null) {return "success";}return "failed";}}

14 .新建LloginDao

package com.chain.dao;import com.chain.dto.OperatorDto;public interface ILoginDao {public OperatorDto login(OperatorDto operatorDto);}

15.新建参数封装实体类LoginDto

package com.chain.dto;public class OperatorDto {private String operateCode;private String password;public String getOperateCode() {return operateCode;}public void setOperateCode(String operateCode) {this.operateCode = operateCode;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

16.完成以上,还差数据库的建立和表的建立,读者可自行建立数据库和表结构,然后修改下jdbc.properties配置就行了。

17.在WEB-INF/jsp下建立 success.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><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"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    Hello.框架搭建成功!恭喜您哦。! <br>  </body></html>


18.建立failed.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>My JSP 'index.jsp' starting page</title><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"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>   登陆失败,请重新登陆! <br>  </body></html>




19.启动项目浏览器输入localhost:8080/spmvc/login/login.do?username=chen&password=7dc588f54dd051de2b1deac570d5c8a2




0 0
原创粉丝点击