首頁 > 軟體

Hierbate 3.3+Spring 3.1 +SpringMVC+Myeclipse 10整合框架搭建

2020-06-16 17:26:43

一.環境設定

1.myeclipse 10
2.springmvc (Spring web)
3.spring3.1(Spring core)
4.Hibernate 3.3(3.3+支援註解功能,3.3-不支援註解功能)
5.jackson-Core-1.9

二.建立Java Web專案

三.相關包匯入(Spring包)

使用myeclipse整合環境自動匯入相關包

四.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name></display-name>
    <!-- 上下文組態檔 -->
    <context-param>
        <description>spring config</description>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <description>spring listerner</description>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 設定spring mvc的相關內容,此處的servlet-name任意,但必須有<your servlet-name>-servlet.xml與之對應 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 設定對應以.do結尾的請求 -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 設定過濾器,同時把所有的請求都轉為utf-8編碼 -->
    <filter>
        <filter-name>Spring character encoding filter</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>
    </filter>
    <filter-mapping>
        <filter-name>Spring character encoding filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 設定專案主頁 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

五.使用myeclipse中hibernate檢視設定資料庫檔案

六.匯入Hibernate相關包並使用myeclipse自動生成相關檔案dao、bean、spring組態檔

這裡寫圖片描述

<!--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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">


    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver">
        </property>
        <property name="url" value="jdbc:mysql://192.168.136.96:3306/clubmanager">
        </property>
        <property name="username" value="root"></property>
        <property name="password" value="sdust"></property>
    </bean>
    <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.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>com/clubmanager/bean/Member.hbm.xml</value>
                <value>com/clubmanager/bean/Part.hbm.xml</value>
                <value>com/clubmanager/bean/Power.hbm.xml</value>
                <value>com/clubmanager/bean/College.hbm.xml</value>
                <value>com/clubmanager/bean/User.hbm.xml</value>
                <value>com/clubmanager/bean/News.hbm.xml</value>
                <value>com/clubmanager/bean/Club.hbm.xml</value>
            </list>
        </property>

    </bean>
    <bean id="MemberDAO" class="com.clubmanager.dao.MemberDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="PartDAO" class="com.clubmanager.dao.PartDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="PowerDAO" class="com.clubmanager.dao.PowerDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="CollegeDAO" class="com.clubmanager.dao.CollegeDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="UserDAO" class="com.clubmanager.dao.UserDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="NewsDAO" class="com.clubmanager.dao.NewsDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
    <bean id="ClubDAO" class="com.clubmanager.dao.ClubDAO">
        <property name="sessionFactory">
            <ref bean="sessionFactory" />
        </property>
    </bean>
</beans>

七.Spring-servlet.xml檔案設定

<!--spring-servlet.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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.xsd   
      http://www.springframework.org/schema/mvc   
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:resources location="/image/" mapping="/image/**" />
    <mvc:resources location="/css/" mapping="/css/**" />
    <mvc:resources location="/js/" mapping="/js/**" />
    <!-- 對定義包中的所有類進行掃描,以完成Bean建立和自動依賴注入的功能 -->
    <context:component-scan base-package="com.clubmanager.admin.controller"></context:component-scan>
    <context:component-scan base-package="com.clubmanager.admin.service"></context:component-scan>
    <context:component-scan base-package="com.clubmanager.info.controller"></context:component-scan>
    <context:component-scan base-package="com.clubmanager.info.service"></context:component-scan>
    <context:component-scan base-package="com.clubmanager.bean"></context:component-scan>
    <context:component-scan base-package="com.clubmanager.dao"></context:component-scan>

    <!-- 啟動spring mvc的註解功能,完成請求和註解POJO的對映 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <!-- 設定資訊轉換,將用@responsebody註解的返回值轉換為json返回前台,編碼為utf-8 -->
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>application/json;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>
</beans>

八.controller層、Service層設定

//controller
package com.clubmanager.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.clubmanager.admin.service.ClubService;


@Controller
@RequestMapping("/admin")
public class ClubController {

    @Autowired
    @Qualifier("ClubService")
    private ClubService clubservice;

    @ResponseBody
    @RequestMapping(value="/addclub.do",method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView addClub(@RequestParam Integer partid,@RequestParam String clubname,@RequestParam String teacher,
            @RequestParam String clubmanager,@RequestParam String describe,@RequestParam String buildtime){
        System.out.println("enter addclub controller!");
        Map<String,Object> result =new HashMap<String,Object>();
        try {
            System.out.println(partid+clubname+clubmanager+teacher+buildtime+"0"+describe);
            this.clubservice.addClub(partid, clubname, clubmanager, teacher, buildtime+" 00:00:00", "0", describe);
            result.put("result","success");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            result.put("result","error");
            result.put("msg", e.toString());
            e.printStackTrace();
        }
        return  new ModelAndView(new MappingJacksonJsonView(),result);
    }

    @ResponseBody
    @RequestMapping(value="/getclublist.do",method={RequestMethod.GET,RequestMethod.POST})
    public ModelAndView getClubList(){
        Map<String,Object> result = new HashMap<String,Object>();
          List l;
        try {
            l = this.clubservice.getClubList();
            result.put("msg",l);
            result.put("result","success");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            result.put("result","error");
            result.put("msg",e.toString());
            e.printStackTrace();
        }

        return new ModelAndView(new MappingJacksonJsonView(),result);
    }

}

//service interface
package com.clubmanager.admin.service;

import java.util.List;

public interface ClubService {
    public boolean addClub(Integer partid,String clubname,String charger,String teacher,String buildtime,String status,String describe) throws Exception;
    public List getClubList() throws Exception;
}

// Service 實現
package com.clubmanager.admin.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.print.attribute.HashAttributeSet;

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

import com.clubmanager.bean.Club;
import com.clubmanager.bean.Part;
import com.clubmanager.dao.ClubDAO;
import com.clubmanager.dao.PartDAO;


@Service("ClubService")
public class ClubServiceImpl implements ClubService{

    @Autowired
    @Resource(name="PartDAO")
    private PartDAO partdao;
    @Autowired
    @Resource(name="ClubDAO")
    private ClubDAO clubdao;
    public boolean addClub(Integer partid, String clubname, String charger,
            String teacher, String buildtime, String status, String describe)
            throws Exception {
        // TODO Auto-generated method stub
        Part p=this.partdao.findById(partid);
        Club c= new Club(p, clubname, charger, teacher,Timestamp.valueOf(buildtime), Integer.parseInt(status), describe,new HashSet());
        this.clubdao.save(c);
        return false;
    }
    public List getClubList() throws Exception{
        List result =  new ArrayList<Object>();

        List<Club> ca=this.clubdao.findAll();
        for(Club c : ca){
            Map m =new HashMap<String,Object>();
            m.put("id", c.getClubid().toString());
            m.put("name", c.getName());
            m.put("charger", c.getCharger());
            m.put("teacher", c.getChargeteacher());
            m.put("regtime", c.getRegtime().toString());
            m.put("status", c.getStatus().toString());
            result.add(m);
        }
        return result;

    }

}

九.注意

controller裡面的函數返回JSON形式資料時,注意不要使用錯誤的包,這裡使用的是Jacson-core包裡面相關函數;

SpringMVC+MyBatis整合設定  http://www.linuxidc.com/Linux/2016-09/135212.htm

SpringMVC總結篇  http://www.linuxidc.com/Linux/2016-06/132659.htm

Spring+SpringMVC企業快速開發架構搭建  http://www.linuxidc.com/Linux/2015-09/122942.htm

SpringMVC的亂碼處理  http://www.linuxidc.com/Linux/2015-07/120542.htm

Spring MVC+Spring3+Hibernate4開發環境搭建 http://www.linuxidc.com/Linux/2013-07/87119.htm

Spring MVC整合Freemarker基於註解方式 http://www.linuxidc.com/Linux/2013-02/79660.htm

基於註解的Spring MVC簡單介紹 http://www.linuxidc.com/Linux/2012-02/54896.htm

SpringMVC詳細範例實戰教學 http://www.linuxidc.com/Linux/2015-06/118461.htm

Spring MVC 框架搭建及詳解 http://www.linuxidc.com/Linux/2012-01/52740.htm

SpringMVC 例外處理  http://www.linuxidc.com/Linux/2015-06/119049.htm

SpringMVC框架入門設定 IDEA下搭建Maven專案 http://www.linuxidc.com/Linux/2016-09/134918.htm

本文永久更新連結地址http://www.linuxidc.com/Linux/2016-12/137885.htm


IT145.com E-mail:sddin#qq.com