SpringMVC+MyBatis分页(最新)
目前主流的web mvc框架,除了struts这个主力 外,还有spring mvc,主要是由于spring mvc配置比较简单,使用起来也十分明了,非常灵活,与spring 集成较好,对restful api的支持也比struts要好。
mybatis是ibatis的升级版,作为hibernate的老对手,它 是一个可以自定义sql、存储过程和高级映射的持久层框架。
与hibernate的主要区别就是mybatis是半自动化的,而hibernate是全自动的,所以当应用需求越来越复杂的时候,自动化的sql显得比较笨拙。
由于前段时间接了个项目要用springmvc做,所以我抱着练手的态度,又玩起了整合框架的游戏。经常搭框架的人应该都清楚,框架搭建的核心就是配置文件。所以我主要贴下几个配置文件的代码。还是那句话,我都是写好配置文件之后,运行报错再加jar。这里列一下我用的jar包(应该是最少的):
备注:上图有一些额外的jar,比如我用的数据库连接池是阿里巴巴的druid、日志框架式logback,所以引入了相关jar。关于这两个框架的使用和配置都是非常简单的,所以这里就不细说。
1.整合springmvc
springmybatis-servlet.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: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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 启用spring mvc 注解--> <mvc:annotation-driven> </mvc:annotation-driven> <!-- 自动扫描的包名 ,使spring支持自动检测组件,如注解的controller--> <context:component-scan base-package="com.alibaba.controller" /> <context:component-scan base-package="com.alibaba.service"/> <!-- 视图解析器:定义跳转的文件的前后缀 --> <bean id="viewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix" value="/web-inf/jsp/" /> <property name="suffix" value=".jsp" /> <!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --> </bean> <!--配置拦截器, 多个拦截器,顺序执行 --> <mvc:interceptors> <mvc:interceptor> <!-- 匹配的是url路径 --> <mvc:mapping path="/" /> <mvc:mapping path="/user/**" /> <mvc:mapping path="/test/**" /> <bean class="com.alibaba.interceptor.commoninterceptor"></bean> </mvc:interceptor> <!-- 当设置多个拦截器时,先按顺序调用prehandle方法,然后逆序调用每个拦截器的posthandle和aftercompletion方法 --> </mvc:interceptors> </beans>
2.整合mybatis
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:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:context="http://www.springframework.org/schema/context" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 该包下的类支持注解,表示会被当作{@code mybatis mapper}处理 配置了之后表示可以自动引入mapper类--> <mybatis:scan base-package="com.alibaba.dao"/> <!--引入属性文件 --> <context:property-placeholder location="classpath:configuration.properties"/> <!--数据库连接--> <bean id="datasource" class="com.alibaba.druid.pool.druiddatasource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialsize"><value>1</value></property> <property name="maxactive"><value>5</value></property> <property name="minidle"><value>1</value></property> <!-- 配置获取连接等待超时的时间 --> <property name="maxwait"><value>60000</value></property> <!-- 配置监控统计拦截的filters --> <property name="filters"><value>stat</value></property> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timebetweenevictionrunsmillis"><value>60000</value></property> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minevictableidletimemillis"><value>300000</value></property> <!-- <property name="validationquery"><value>select 'x'</value></property> <property name="testwhileidle"><value>true</value></property> <property name="testonborrow"><value>false</value></property> <property name="testonreturn"><value>false</value></property> <property name="poolpreparedstatements"><value>true</value></property> <property name="maxopenpreparedstatements"><value>20</value></property> --> </bean> <!-- mybatis配置 --> <bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean"> <property name="datasource" ref="datasource" /> </bean> </beans>
3.web.xml整合springmvc和mybatis
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- 该servlet为tomcat,jetty等容器提供,将静态资源映射从/改为/static/目录,如原来访问 http://localhost/foo.css ,现在http://localhost/static/foo.css --> <!-- 不拦截静态文件 --> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/js/*</url-pattern> <url-pattern>/css/*</url-pattern> <url-pattern>/images/*</url-pattern> <url-pattern>/fonts/*</url-pattern> </servlet-mapping> <!-- 配置字符集 --> <filter> <filter-name>encodingfilter</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>encodingfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 初始化 dispatcherservlet时,该框架在 web应用程序web-inf目录中寻找一个名为[servlet-名称]-servlet.xml的文件, 并在那里定义相关的beans,重写在全局中定义的任何beans --> <servlet> <servlet-name>springmybatis</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmybatis</servlet-name> <!-- 所有的的请求,都会被dispatcherservlet处理 --> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextconfiglocation</param-name> <param-value>/web-inf/config/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- druid web 监控 --> <servlet> <servlet-name>druidstatview</servlet-name> <servlet-class>com.alibaba.druid.support.http.statviewservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>druidstatview</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/error/404.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/500.jsp</location> </error-page> </web-app>
4.logback.xml日志配置
<?xml version="1.0" encoding="utf-8"?> <configuration> <appender name="stdout" class="ch.qos.logback.core.consoleappender"> <encoder> <pattern>%d{hh:mm:ss.sss} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <logger name="test.logbacktest" level="trace"/> <logger name="com.alibaba.controller.testcontroller" level="trace"/> <logger name="org.springframework.web.servlet.dispatcherservlet" level="debug" /> <logger name="druid.sql" level="info" /><!-- 如果spring-config里面没有配置slf4j,就不会显示sql日志,logback只是slf4j的一个实现 --> <root level="debug"> <appender-ref ref="stdout" /> </root> </configuration>
5.configuration.properties配置
jdbc.url=jdbc\:mysql\://localhost\:3306/druid?useunicode\=true&characterencoding\=utf-8&zerodatetimebehavior\=converttonull jdbc.username=root jdbc.password=123456
6.测试搭建是否成功,后台代码
首先是登录,用了加密,可以去掉
package com.alibaba.controller; import javax.annotation.resource; import javax.servlet.http.httpservletrequest; import org.apache.commons.codec.digest.digestutils; 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.alibaba.model.user; import com.alibaba.service.userservice; import com.alibaba.util.requestutil; /** * @author tfj * 2014-7-26 */ @controller public class systemcontroller { private final logger log = loggerfactory.getlogger(systemcontroller.class); @resource private userservice userservice; @requestmapping(value = "/",method = requestmethod.get) public string home() { log.info("返回首页!"); return "index"; } @requestmapping(value = "/test/hello",method = requestmethod.get) public string testhello() { log.info("执行了testhello方法!"); return "testhello"; } @requestmapping(value = "/login",method = requestmethod.post) public string testlogin(httpservletrequest request,@requestparam string username, @requestparam string password) { log.info("执行了testlogin方法!"); user user = userservice.finduserbyname(username); if(user!=null){ if(user.getpassword().equals(digestutils.md5hex(password))){ request.getsession().setattribute("userid", user.getid()); request.getsession().setattribute("user", username); return "redirect:" + requestutil.retrievesavedrequest();//跳转至访问页面 }else{ log.info("密码错误"); request.getsession().setattribute("message", "用户名密码错误,请重新登录"); return "login"; } }else{ log.info("用户名不存在"); request.getsession().setattribute("message", "用户名不存在,请重新登录"); return "login"; } } }
关于service和model就不写了,写一下mybatis的mapper类映射
<?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.alibaba.dao.usermapper"> <select id="finduserbyname" resulttype="com.alibaba.model.user"> select id, username , password from sysuser where username = #{username} </select> </mapper>
7.前台jsp主要是登录和登录成功的页面,就不写了
贴一下截图:
到此,springmvc+mybatis整合成功。后续复杂的功能待添加
注意事项
1.框架中关于druid和logback的配置都是从官网上copy下来的,所以都是最基本的,读者可以忽略,也可以换成读者熟悉的数据库组件和日志框架,如c3p0和log4j。
2.代码里加入了权限管理,即访问前需登录,登录后跳转至待访问页面,关于springmvc的权限管理请看:
3.本文是从我的测试代码里剥离出来的最简单的也是最基本的代码,有些没剥离干净的地方还请见谅。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。