今天重拾博客,开始新的学习之旅。
今天配置了一下SpringMVC+Hibernate,并实现jason数据与前台的交互。
一、entity类:
实体类为hibernate逆向产生
package org.schoolcrm.hb.enties;
import java.sql.Date;
import java.util.HashSet;
import java.util.Set;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
/**
* Student entity. @author MyEclipse Persistence Tools
*/
@JsonIgnoreProperties(value={"classinfo","studentcard"})
//陷阱1
public class Student implements java.io.Serializable {
// Fields
/**
*
*/
private static final long serialVersionUID = 1L;
private String stid;
private Classinfo classinfo;
private String stname;
private Date stbirthday;
private String stsex;
private Studentcard studentcard;
//private Subjectinfo subjectinfo;
// Constructors
public Student(){
}
public String getStid() {
return this.stid;
}
public void setStid(String stid) {
this.stid = stid;
}
public Classinfo getClassinfo() {
return this.classinfo;
}
public void setClassinfo(Classinfo classinfo) {
this.classinfo = classinfo;
}
public String getStname() {
return this.stname;
}
public void setStname(String stname) {
this.stname = stname;
}
public Date getStbirthday() {
return this.stbirthday;
}
public void setStbirthday(Date stbirthday) {
this.stbirthday = stbirthday;
}
public String getStsex() {
return this.stsex;
}
@Override
public String toString() {
return "Student [stid=" + stid + ", stname=" + stname + ", stbirthday="
+ stbirthday + ", stsex=" + stsex + "]";
}
public void setStsex(String stsex) {
this.stsex = stsex;
}
public Studentcard getStudentcard() {
return studentcard;
}
public void setStudentcard(Studentcard studentcard) {
this.studentcard = studentcard;
}
}
2、hbm.xml
注意配置中的一对一,一对多关系
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="org.schoolcrm.hb.enties.Student" table="STUDENT" schema="SCOTT">
<id name="stid" type="java.lang.String">
<column name="STID" />
<generator class="assigned" />
</id>
<many-to-one name="classinfo" class="org.schoolcrm.hb.enties.Classinfo" fetch="select" lazy="false" >
<column name="CLID" />
</many-to-one>
<property name="stname" type="java.lang.String">
<column name="STNAME" />
</property>
<property name="stbirthday" type="java.sql.Date">
<column name="STBIRTHDAY" />
</property>
<property name="stsex" type="java.lang.String">
<column name="STSEX" length="10" />
</property>
<!-- 学生与学生正的一对一关系还未配置 -->
<one-to-one name="studentcard" ></one-to-one>
</class>
</hibernate-mapping>
二、Controller类
package org.schoolcrm.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.schoolcrm.exception.ServiceException;
import org.schoolcrm.hb.enties.Student;
import org.schoolcrm.service.StudentServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/StudentController")
public class StudentController {
private int currentPage=1;
private int pageSize;
@Autowired
private StudentServiceImp studentServiceImp;
@RequestMapping("/getAllStudents.do")
@ResponseBody
public Map<String,Object> getUsers(String currentPage){
String errorMessage ="aaaa";
this.currentPage=Integer.parseInt(currentPage);
if(currentPage!=null)
System.out.println(currentPage+"11111111111111");
HashMap<String,Object> map=new HashMap<String,Object>();
List<Student> students=new ArrayList<Student>();
try {
students=studentServiceImp.listStudent( this.currentPage,10);
} catch (ServiceException e) {
errorMessage=e.getMessage();
}
map.put("students",students );
map.put("message", errorMessage);
return map;
}
}
三、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"
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">
<display-name>school_crm</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:spring-*.xml
</param-value>
</context-param>
<filter>
<description>字符集过滤器</description>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<description>字符集编码</description>
<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>
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<description>Introspector缓存清除监听器</description>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<description>request监听器</description>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- <servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>-->
<!-- <servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>-->
<servlet>
<description>spring mvc servlet</description>
<servlet-name>springMvc2</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>spring mvc 配置文件</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc2</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>springMvc2</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
2、applicationContext.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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"
>
<!-- SpringMVC注解配置 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 支持注解 -->
<context:annotation-config></context:annotation-config>
<!-- 自动扫描装配 -->
<context:component-scan base-package="org.schoolcrm"></context:component-scan>
<!-- 开启自动装配 -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClassName}" />
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="100" />
<!--连接池中保留的最小连接数。-->
<property name="minPoolSize" value="1" />
<!--初始化时获取的连接数,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="10" />
<!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="30" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="5" />
<!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
<property name="maxStatements" value="0" />
<!--每60秒检查所有连接池中的空闲连接。Default: 0 -->
<property name="idleConnectionTestPeriod" value="60" />
<!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 -->
<property name="acquireRetryAttempts" value="30" />
<!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效
保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试
获取连接失败后该数据源将申明已断开并永久关闭。Default: false-->
<property name="breakAfterAcquireFailure" value="true" />
<!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的
时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
等方法来提升连接测试的性能。Default: false -->
<property name="testConnectionOnCheckout" value="false" />
</bean>
<!-- 设置property文件的位置 -->
<context:property-placeholder location="classpath:dataSource.properties"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>org/schoolcrm/hb/enties/Student.hbm.xml</value>
<value>
org/schoolcrm/hb/enties/Studentcard.hbm.xml
</value>
<value>org/schoolcrm/hb/enties/Teacher.hbm.xml</value>
<value>
org/schoolcrm/hb/enties/StudentOfSubject.hbm.xml
</value>
<value>
org/schoolcrm/hb/enties/Subjectinfo.hbm.xml
</value>
<value>org/schoolcrm/hb/enties/Classinfo.hbm.xml</value>
</list>
</property>
</bean>
</beans>
3、springMVC 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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"
>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
</bean>
<!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:order="3">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="contentType" value="text/html" />
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 系统错误转发配置[并记录错误日志] -->
<!-- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="error/exception"></property>
<property name="exceptionAttribute" value="ex"></property>
<property name="exceptionMappings">
<props>
<prop key="com.llff.common.exception.AuthenticationException">error/authException</prop>
</props>
</property>
</bean>
-->
</beans>
四、javascrip代码
function loadUsers(currentPage){
//获取要去页面数
var go_page = $.trim($("#go_page").val());
if(go_page!=""){
currentPage=go_page;
}
//获取查询参数
var likeUserName = $.trim($("#userName").val()) ;
while(likeUserName.indexOf("'") != -1) {
likeUserName = likeUserName.replace("'","");
$("#userName").val(likeUserName);
}
$("#user_list").html("");
var scurrentPage="rttrew";
alert(scurrentPage);
$.ajax({
url:"StudentController/getAllStudents.do",
type:"post",
dataType:"json",
data:{"currentPage":currentPage},
success:function(data){
$("#user_list").html("");
var html = "";
$.each(data.students,function(i,item){
var userId = item.stid;
var userName = item.stname;
var stbirthday = item.stbirthday;
var stsex = item.stsex;
html = "<tr>"
+"<td>"+userName+"</td>"
+"<td>"+userId+"</td>"
+"<td>"+stbirthday+"</td>"
+"<td>"+stsex+"</td>"
+"<td id='caozuo_"+i+"'></td></tr>";
$("#user_list").append(html);
上面配置都是经过参考配置的,其中几个地方需要注意
1、通过hibernate生成的实体类作物model会有一对一或者一对多的情况,在序列化时会若xml中互相配置了一对一则会出现序列化为jason时循环的情况
加上@JsonIgnoreProperties(value={"classinfo","studentcard"}) 注解可以避免循环序列号。