设为首页 收藏本站
查看: 873|回复: 0

[经验分享] SpringMVC MyBatis PostgreSQL整合

[复制链接]

尚未签到

发表于 2016-11-21 08:52:26 | 显示全部楼层 |阅读模式
  继续记录学习过程欧~~
  昨天不小心把辛辛苦苦做的SpringMVC MyBatis PostgreSQL代码给删除掉了,哎~想undo,结果不允许
  不过塞公失马焉知非福
  今天再来一遍就是了,就当是巩固了,不过确实把一些遗留的问题给解决了。
  昨天首先遇到的一个问题就是,由于配置文件路径不对,导致Web应用程序初始化错误,导致无法加载,
  我还傻乎乎的通过浏览器访问,结果心灰意冷,因为以前都是初始化没有问题,真正访问程序的时候出问题,
  此种情况还会在eclipse里面显示出错误信息再进行定位。但是现在什么错误信息都没有,直接访问不了了,就让人很担心,
  后来调查发现,在启动tomcat服务器的时候,如果Web应用程序加载有问题,会出现错误信息,比如哪个配置文件无法读取之类的错误。
  着实让我看到了生的希望,把问题给排除了。
  OK,进入正题。
  首先肯定是要创建动态web工程,加入web.xml,配置如下:



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <context-param>   
        <param-name>contextConfigLocation</param-name>   
        <param-value>WEB-INF/classes/config/applicationContext.xml</param-value>   
    </context-param>   

    <listener>
        <listener-class>my.MyContextLoaderListener</listener-class>
    </listener>
    <!--
    <listener>   
      <listener-class>   
           org.springframework.web.context.ContextLoaderListener   
      </listener-class>   
    </listener>   
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <!-- 拦截所有以do结尾的请求 -->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>
  下面这段代码是为了创建全局的ApplicationContext用的。



    <context-param>   
        <param-name>contextConfigLocation</param-name>   
        <param-value>WEB-INF/classes/config/applicationContext.xml</param-value>   
    </context-param>   
    <listener>
        <listener-class>my.MyContextLoaderListener</listener-class>
    </listener>
  MyContextLoaderListener从ContextLoaderListener继承。



import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class MyContextLoaderListener extends ContextLoaderListener{
    @Override
    public void contextInitialized(ServletContextEvent event){
        super.contextInitialized(event);
        ServletContext context = event.getServletContext();
         //获取web环境下的ApplicationContext
        ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        //将ApplicationContext,set到ContextUtil的静态变量context
        ContextUtil.setContext(ctx);
    }      
}
  创建ContextUtil



package my;
import org.springframework.context.ApplicationContext;
public class ContextUtil {
    private static ApplicationContext context;
    public static ApplicationContext getContext() {
        return context;
    }
    public static void setContext(ApplicationContext aContext) {
        context = aContext;
    }
}
  这样在需要的时候,就可以像下面这样访问代码,而不需要通过request等得到ServletContext再去获取了。



        //ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
        ApplicationContext ctx=ContextUtil.getContext();
        UserMapper maper=(UserMapper)ctx.getBean(UserMapper.class);
        User user = maper.getUser("fff");
  下面来配置SpringMVC的配置文件dispatcherServlet-servlet.xml,我的理解是这样,呵呵



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <!-- 定义映射 -->
    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="helloWorld.do">helloWorldAction</prop>
            </props>
        </property>
    </bean>
    <!-- 定义视图 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass">
            <value>org.springframework.web.servlet.view.InternalResourceView</value>
        </property>
    </bean>
    <!-- 定义控制器 -->
    <bean id="helloWorldAction" class="com.jp.action.HelloWorldAction">
        <property name="helloWorld">
            <value>Good Luck!</value>
        </property>
        <property name="viewPage">
            <value>/index.jsp</value>
        </property>
    </bean>
</beans>
  我的理解就是把helloWorld.do映射到helloWorldAction里面去,再定义一下显示的方法。



package com.jp.action;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import my.ContextUtil;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import bean.User;
import Mapper.UserMapper;

public class HelloWorldAction implements Controller{
    private Logger logger=Logger.getLogger(this.getClass().getName());
    private String helloWorld;
    private String viewPage;
public String getHelloWorld() {
        return helloWorld;
    }
    public void setHelloWorld(String helloWorld) {
        this.helloWorld = helloWorld;
    }
    public String getViewPage() {
        return viewPage;
    }
    public void setViewPage(String viewPage) {
        this.viewPage = viewPage;
    }

    public ModelAndView handleRequest(HttpServletRequest req,
            HttpServletResponse res) throws Exception {
        // TODO Auto-generated method stub
        //ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
        ApplicationContext ctx=ContextUtil.getContext();
        UserMapper maper=(UserMapper)ctx.getBean(UserMapper.class);
        User user = maper.getUser("fff");
        Map model=new HashMap();
        model.put("helloWorld",user.getName());
        return new ModelAndView(getViewPage(),model);     
    }
}
  这里在取显示数据的地方,是由映射器接口UserMapper,通过MyBatis连接PostgreSQL取得的。
  但这个映射器接口UserMapper是通过Spring的注入生成。
  来看看applicationContext.xml文件里是怎么注入UserMapper的。



<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="org.postgresql.Driver">
       </property>
       <property name="url"
           value="jdbc:postgresql:testdb">
       </property>
       <property name="username" value="postgres"></property>
       <property name="password" value="nirvana7"></property>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="myDataSource"/>
       <property name="configLocation" value="WEB-INF/classes/config/mybatis-config.xml"/>
    </bean>
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="Mapper"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="myDataSource"/>
    </bean>
</beans>
      
  org.mybatis.spring.mapper.MapperScannerConfigurer会扫描Mapper的package,然后生成接口,可以参照前篇文章来了解。
  到这里主要流程都已经搞定了,很多麻烦的地方在于配置文件的路径问题,很是让人烦恼啊。
  代码上传上去。
  SpringMVCMyBatisAgain.zip
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-303206-1-1.html 上篇帖子: PostgreSQL配置优化 下篇帖子: postgresql之vacuum
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表