springmvc spring mybatis 整合

在这个文档中只会有错误或者是解答

一、Web程序加载时错误

1.1java.lang.reflect.InvocationTargetException

 

=====web.xml中的web-app中加入 metadata-complete="true"

网页上的解释:

web.xml文件中使用<metadata-complete>元素通知Web容器是否要寻找注解,如果你将<metadata-complete>设为false,或者在文件中不指定<metadata-complete>元素,那么在部署期间,容器必须扫描注解和Web分片,为Web应用程序构建有效的元数据。如果将<metadata-complete>设为true,将由部署描述符为Web应用程序提供所有的配置信息

自我理解:

这个属性是用来判断在部署项目时是否扫描注解,web 分片;外附网址:

http://www.docin.com/p-212708636.html

1.2 Cannot resolve reference to bean 'sqlSessionFactory' while setting bean property 'sqlSessionFactory';nested exception is org.springframework.beans.factory.BeanCreationException:

调试 了一下发现是mybatis.xml中的配置文件出错了。没有加mybatis dtd

1.3 org.apache.jasper.JasperException: Unable to compile class for JSP:

 

我原本项目的jre1.8 的版本,但是tomcat7.0 的版本,后来看了网上的教程说,出现这样的错误可能是版本号不一样,所以我将tomcat 服务器的版本换成了8.0的,清理后再用

Tomcat8.0 开启项目进网页果然不报错了。

 

1.4java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener

开启服务器报错:应该是缺少了上面的一个包,后来可以了,清理与开启

 

 

1.5 springmvc web中找不到静态的资源

原来在springmvc中 会自动拦截所有的请求,所以你需要单独配置这些静态的请求,springmvc才会去放过它。

<mvc:annotation-driven></mvc:annotation-driven>

<mvc:resources location="/images/" mapping="/images/**" cache-period="31556926"/> 

<mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  

<mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>

<mvc:resources location="/html/" mapping="/**"/>

 

 

1.6 加载jsp页面找不到路径:description The requested resource is not available.

 

找到的问题:原来是有一个Controller 中配置的Dao接口没有在springBean中配置,可能就到至那个控制器出错了,然后就会提示请求错误。

 

 

1.7

java.lang.IllegalArgumentException: Parameter Maps collection does not contain value for com.hu.Dao.CardDao.card

 

应该是mybatis映射的mapper.xml 中的参数类型不正确。--已解决

 

1.8 com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException

 

 

1.9

java.lang.NoClassDefFoundError: Lcom/hu/Dao/NewsDao;

 

加载错误,清理后再开没问题了。

2.0 java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener

据我了解,是某个包没有加载出来,或者缺少某个包

 

2.1 Caused by: java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

 

还没完,我把HTML页面中有js的代码去了,css中可能后json 中代码去了,就不报classnotfoundException 这个错误了,但是有新的错误出现了,下面我们来看一下:

 

2.2 bean注入失败

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'capsuleController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ll.server.CapsuleServer com.ll.mvc.CapsuleController.cs; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter] for bean with name 'mappingJacksonHttpMessageConverter' defined in class path resource [config/spring-mvc.xml]; nested exception is java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

 

据我看,出现这样的情况大概就是,spring-mvc.xmlspring-mybatis.xml中的配置问题

<!-- 避免IE执行ajax 时,返回JSoN出现下载文件 -->

<!-- spring 4.1.0 中是使用的这个类,spring3.0会是不同的包

 org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

  -->

2.3

java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

好像是spring中的applicationContext.xml 没有找到,在web.xml中没有配置到,

<context-param>

<param-name>contextConfigLocation</param-name> <param-value>/config/spring-mybatis.xml,classpath*:spring-mvc.xml</param-value>

</context-param>

这个值没有写好,你信吗,希望以后的我会知道。,然后报了下面的这个错误。

然后我知道了,

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:config/spring-*.xml</param-value>

</context-param>

这么写才是正确的,但是下面又报错了。

 

2.4 org.springframework.beans.factory.BeanDefinitionStoreException  IOException 

parsing XML document from ServletContext resource [/config/spring-mybatis.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/config/spring-mybatis.xml]

 

 

2.5 E:\WorkSpace\java001\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SPRINGMVCTEST\WEB-INF\classes\config\spring-config.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 39; 文件提前结束。

这个xml中没有写dtd

2.6

org.springframework.beans.factory.BeanCreationException: 

Error creating bean with name 'capsuleController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.ll.server.CapsuleServer com.ll.mvc.CapsuleController.cs; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'capsulserverimpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.ll.dao.ICapsule com.ll.server.impl.CapsuleServerImpl.capsuledao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ll.dao.ICapsule] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

 

2.7 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'capsuleServer' is defined

下面这个故事,是引用某个大神的博客的内容,我觉得很有用就复制了,谢谢

有个工程师,在项目工程里加了些页面和ServiceDao之类,然后启动web工程,Spring一直报错说找不到autowired定义的service接口的实现bean的定义,然后来求助我来帮忙解决。

   我理所当然的按照常规步骤123...检查他的代码是否存在问题:

 

第一步,检查service接口是否确实有实现类并且@Service标注了,这个是初学者让出现问题,检查结果确实没问题Pass

 

 

第二布,因为其service定义在新的package里,遂检查其spring配置里,component-scan是否新增加了扫描package,检查结果确实没问题Pass

 

 

第三步,怀疑Eclipse开发环境里,运行tomcat的时候,没有publish成功,确认workspace里是自动build,并且clean & Rebuild,在clean tomcat server,问题依旧。

 

 

第四步,还是怀疑Eclipse开发环境里,运行tomcat的时候,没有publish成功,遂检查workspace的的.metadata/.plugins/org.eclipse.wst.server.core里所发布的内容,检查结果确实class已经publish过去没问题,Pass

 

 

第五步,检查Web工程里的Deployment Assembly,配置正确没问题,Pass

 

   逐步检查下来,常规的错误貌似都没有犯,但怎么clean,再启动依然报错,找到Service接口,Ctrl+T,确实找到实现类,并且@Service标注。问题查到这里就有点奇怪了,这样问题以前貌似没碰到过。

    有问题不能不解决,继续琢磨,Ctrl+GService所有引用,发现有两个地方被使用@Autowared注入,然后,然后,然后,点其中一个引用的地方,Ctrl+T找其实现类,很神奇的发现,光标就跳到引用这个service的类本身上。OMGFinally,原来该Service的实现Bean在引用自身Service,结果循环引用导致无法实例化Bean而报出这个错误。对于一个中高级工程师来说,犯这个错误,我只能一顿痛扁,挣一顿免费晚餐,你,是否也曾经犯过这个傻呢......

后来还是错了,最后只能将这个controller 的注入给注释掉了,注释完后,又报错:在spring-mybatis.xml 的配置中创建bean sqlSessionFactory错误,没有mapperLations这个属性,我真的是日了,报了两天没有解决的错误,竟然是这个:下面才是正确的,写在下面用来警示自己。

<property name="mapperLocations" value="classpath:com/ll/mapping/*.xml"></property>

这个错误告诉我一个道理,做人不能太自大,耽误两天时间又让我少活两天。

开了服务器没有报错了,终于可以开始写项目了。苍天抱我不要出错呀。

 

2.8java.lang.NoClassDefFoundError:org/apache/commons/pool/impl/GenericObjectPool

据说是没有在项目中加入包 commons-pool-1.3.jar 

2.9 java.sql.SQLException: No suitable driver

Jdbc.properties 配置文件,的URL 写错了,正确的为:

username=root

pwd=sa123

url=jdbc:mysql://127.0.0.1:3306/pro??useUnicode=true&characterEncoding=utf8

driver=com.mysql.jdbc.Driver

 

3.0:

### Error updating database.  Cause: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException:

没啥问题,重开就好了。

3.1:对于springmvc中的静态资源的配置,解释如下

<mvc:default-servlet-handler/>

<mvc:annotation-driven/>

上面的这两种配置方式只是在DispatcherServlet的请求处理路径为“/”的情况下使用,如果你配置的是*.do或*.pay等方式则不需要上面这样的配置,因为*.do或*.pay只处理以它结尾的请求,对静态资源文件不会做任何处理。

 

 

 ①. 两种标签都没有的时候,框架默认注册的有AnnotationMethodHandlerAdapter这个bean,所以能够处理@RequestMapping这个注解。

②. 但是只配置了<mvc:default-servlet-handler/>时所注册的两个bean都不能处理@RequestMapping注解,因此无法找到相应的Controller,进而无法进行访问路径的映射,

           ③. 两种标签都有的时候,<mvc:annotation-driven/>会注册一个RequestMappingHandlerAdapter的bean,这个bean能够处理@RequestMapping这个注解。

静态文件的路径就是这个默认的文件夹的路径。

我的程序可以运行了,可以返回json数据了,下面就来看一看我写的代码吧。

1.1控制器代码:

package com.ll.mvc;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.List;

 

import javax.annotation.Resource;

import javax.servlet.http.HttpServletResponse;

 

import org.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

 

import com.alibaba.fastjson.JSONObject;

import com.ll.server.CapsuleServer;

import com.ll.vo.Capsule;

 

@Controller

public class CapsuleController {

@Resource(name="capsuleService",shareable=true)

CapsuleServer cs;

@RequestMapping("/add")

public String add(@ModelAttribute Capsule capsule , Model model){

System.out.println(capsule.toString());

if(capsule!=null&&capsule.getExplains()!=null&&capsule.getTypeId()!=null&&capsule.getType()!=null){

if(cs.add(capsule)){

model.addAttribute("capsule",capsule);

}

return "index";

}

return "../../index";

}

@RequestMapping("/select")

public void select(@ModelAttribute String id,HttpServletResponse response){

response.setContentType("json/html;charset=utf-8");

PrintWriter out ;

try {

out = response.getWriter();

List<Capsule> l = cs.select();

JSONObject jo = new JSONObject();

jo.put("l", l);

out.print(jo.toString());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

 

1.2 前端代码:核心代码

<a href="javascript:οnclick=tj()">提交</a>

<script type="text/javascript">

function tj(){

alert("hello");

$.ajax({

url:"select",

type:"post",

dataType:"json",

success:function(msg){

alert("success:"+msg.l);

var ar = new Array();

ar = eval(msg.l);

alert(ar.length);

for(var i = 0 ; i<ar.length;i++ ){

alert(ar[i].id);

}

},

error:function(msg){

alert("error:"+msg.l);

}

})

}

</script>

<div id="ok"></div>

1.3看一看我配置的xml文件

1.3.1 spring-mybatis.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:context="http://www.springframework.org/schema/context"  

    xsi:schemaLocation="http://www.springframework.org/schema/beans    

                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    

                        http://www.springframework.org/schema/context    

                        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<!--自动扫描 -->

<context:annotation-config base-package="com.ll"></context:annotation-config>

<!--  引入配置文件-->

<bean id="propertyConfigurer"

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="locations" value="classpath:config/jdbc.properties"></property>

</bean>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

destroy-method="close">

<!-- destroy-method=close: 当数据库连接不使用的时候,就把该连接重新放到数据池中,方便下次使用调用 -->

<property name="driverClassName" value="${driver}"></property>

<property name="url" value="${url}"></property>

<property name="password" value="${pwd}"></property>

<property name="username" value="${username}"></property>

</bean>

<!-- spring 和mybatis完美整合,不需要mybatis的配置映射文件 -->

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>

<!-- 自动扫描 mapping.xml文件-->

<property name="mapperLocations" value="classpath:com/ll/mapping/*.xml"></property>

</bean>

<!-- DAO 接口所在的包名,spring会自动查找其下的类 -->

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >

<property name="basePackage" value="com.ll.dao"></property>

<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

</bean>

<!-- bean (事务管理) transanction manager ,use  -->

<bean id="transactionManager" 

class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

<property name="dataSource" ref="dataSource"></property>

</bean>

</beans>

 

1.3.2 spring-mvc.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: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-3.1.xsd    

                        http://www.springframework.org/schema/context    

                        http://www.springframework.org/schema/context/spring-context-3.1.xsd    

                        http://www.springframework.org/schema/mvc    

                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  

 

<!-- 3.自动扫描该包,使springmvc认可下的@controller注解的类控制器  -->

<context:component-scan base-package="com.ll.mvc"></context:component-scan>

<!-- 4.使用 mvc:annotation-driven 加载注解映射器和注解适配器配置-->

<mvc:annotation-driven></mvc:annotation-driven>

<!--   -->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/jsp/"></property>

<property name="suffix" value=".jsp"></property>

</bean>

 

<!-- 避免IE执行ajax 时,返回JSoN出现下载文件 -->

<!-- spring 4.1.0 中是使用的这个类,spring3.0会是不同的包

 org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

  -->

<bean id="mappingJacksonHttpMessageConverter"

class=" org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

<property name="supportedMediaTypes">

<list>

<value>text/html;charset=UTF-8</value>

</list>

</property>

</bean>

<!-- 1.开启SpringMVC注解模式 -->

    <!-- 简化配置:

        (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter

        (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持

    -->

<mvc:annotation-driven/>

    <!-- 2.静态资源默认servlet配置

        (1)加入对静态资源的处理:js,gif,png

        (2)允许使用"/"做整体映射

     -->

    <mvc:default-servlet-handler/>

</beans>

 

1.3.3 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_3_0.xsd"

id="WebApp_ID" version="3.0">

<display-name>SPRINGMVCTEST</display-name>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:config/spring-*.xml</param-value>

</context-param>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>springmvc</servlet-name>

<servlet-class>com.ll.test.TestDispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:config/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>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

</web-app>

1.4最后看一看我项目结构:

就这样发了,还不行,还是将我所有的代码一一的写出来;

1. Dao接口:

package com.ll.dao;

 

import java.util.List;

 

import org.springframework.stereotype.Service;

 

import com.ll.vo.Capsule;

 

/**

 * 胶囊dao接口

 * @author LaoLi

 *

 */

 

public interface ICapsule {

 

public List<Capsule> select();

public boolean add(Capsule capsule);

}

 

 

映射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.ll.dao.ICapsule">

   <insert id="add" parameterType="com.ll.vo.Capsule">

   insert into capsule values(null,#{explains},#{type},#{typeId});

   </insert>

   <select id="select" resultType="com.ll.vo.Capsule">

   select * from capsule;

   </select>

  </mapper>

 

2. 服务层:CapsuleServer.java

package com.ll.server;

 

import java.util.List;

 

import org.springframework.stereotype.Service;

 

import com.ll.vo.Capsule;

public interface CapsuleServer {

 

public List<Capsule> select();

public boolean add(Capsule capsule);

}

 

 

服务层实现类:CapsuleServerImpl.java

package com.ll.server.impl;

 

import java.util.List;

 

import javax.annotation.Resource;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.ll.dao.ICapsule;

import com.ll.server.CapsuleServer;

import com.ll.vo.Capsule;

@Service("capsuleService")

public class CapsuleServerImpl implements CapsuleServer {

 

@Resource

private ICapsule capsuledao;

@Override

public List<Capsule> select() {

return capsuledao.select();

}

 

@Override

public boolean add(Capsule capsule) {

return capsuledao.add(capsule);

}

 

}

 

 

3. 控制层:CapsuleController.java

上面写过了

 

4. 实体类:Capsule.java

package com.ll.vo;

/**

 * 胶囊。航天舱

 * @author LaoLi

 *

 */

public class Capsule {

 

private Integer id;

private String type;

private String explains;

private Integer typeId;

@Override

public String toString() {

return "Capsule [id=" + id + ", type=" + type + ", explains=" + explains + ", typeId=" + typeId + "]";

}

public Capsule(Integer id, String type, String explains, Integer typeId) {

this.id = id;

this.type = type;

this.explains = explains;

this.typeId = typeId;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getType() {

return type;

}

public void setType(String type) {

this.type = type;

}

public String getExplains() {

return explains;

}

public void setExplains(String explains) {

this.explains = explains;

}

public Integer getTypeId() {

return typeId;

}

public void setTypeId(Integer typeId) {

this.typeId = typeId;

}

public Capsule(){

}

}

 

 

5. Jdbc.properties

username=root

pwd=sa123

url=jdbc:mysql://127.0.0.1:3306/pro??useUnicode=true&characterEncoding=utf8

driver=com.mysql.jdbc.Driver

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值