在Spring MVC中获取上下文

时间:2014-01-27 08:23:28

标签: java spring spring-mvc

我已经开始使用Spring并在网上经历了多个教程。我试图使用Spring MVC将名称,年龄记录插入数据库。在尝试实现这一目标时,我已经停止尝试为我的DAO定义一个bean。我是否需要在其中定义我的application-servlet.xml并以某种方式通过getBean获取它,或者我是否创建一个新的xml来定义bean并尝试使用应用程序上下文。另外,我是否定义了一个新的应用程序上下文,或者如果Dispatcher servlet以某种方式已经实现了它,我会以某种方式获取它。

这是我的web.xml

<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" `enter code here`
    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">

    <display-name>Spring MVC Form Handling</display-name>

    <servlet>
        <servlet-name>SpringDB</servlet-name>
        <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>SpringDB</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
         <param-value>/WEB-INF/SpringDB-servlet.xml</param-value>
    </context-param>

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


</web-app>

这是我的SpringDB.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   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-3.0.xsd">

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

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

  <bean id="dataSource" 
      class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://172.22.201.142:3306/"/>
      <property name="username" value="tcm_user"/>
      <property name="password" value="tcm_pwd"/>
   </bean>

  <bean id="studentJDBCTemplate" 
      class="com.tutorialspoint.StudentJDBCTemplate">
      <property name="dataSource"  ref="dataSource" />    
   </bean>

</beans>

这是我的第一个问题,我很抱歉任何错误,我会编辑任何错误或添加信息。感谢

3 个答案:

答案 0 :(得分:0)

首先你不需要包括              contextConfigLocation的          /WEB-INF/SpringDB-servlet.xml     

由于调度程序servlet会自动加载此xml 您可以创建一个新的xml,也可以在/WEB-INF/SpringDB-servlet.xml中定义它。 要在新的xml中定义它,如“DAOBeans.xml”,请使用下面的配置并在其中定义bean

<context-param>
    <param-name>contextConfigLocation</param-name>
     <param-value>/WEB-INF/DAOBeans.xml</param-value>
</context-param>

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

答案 1 :(得分:0)

有关详细信息,请参阅我的github repo 你好伙计,我非常喜欢spring-web-mvc,我会把它作为我的主要调度员框架 与springhibernate集成后,此SSH框架将非常强大且易于您开发Web应用程序。

spring是一个bean容器和工厂模式,用于维护后端应用程序中的所有实例和bean。

hibernate是一个ORM框架用于解除讨厌和基本的SQL springmvc是一个调度程序框架,如struts,但我认为springmvc因其方便性而优于struts

弹簧

要实现这些目标,首先需要在spring

中注册web.xml
   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

在Spring中,您可以使用基于xml的配置或基于annotation的配置。我个人更喜欢annotation,因为它更容易 对于DAO bean,您可以在applicationContext.xml

中使用包扫描
<context:component-scan base-package="root-package-name"/>

然后,您应该将applicationContext.xml放入类路径中,并将<context-param>描述为配置spring container

休眠

接下来,您需要配置hibernate。注意hibernate需要在applicationContext.xml而不是web.xml进行配置 实际上你可以使用其他ORM框架。我只是以你为例给你。
所有实体都可以通过以下方式自动扫描:

<bean name="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>rugal.center.core.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.format_sql">false</prop>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.connection.autocommit">false</prop>
        </props>
    </property>
</bean>

难道不容易吗?

弹簧的Web-MVC

最后重要的是springmvc。您需要在web.xml

中注册
<servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

在此之后,您需要在springmvc-sevlet.xml下的WEB-INF文件夹,该文件夹用于配置URL映射,响应规则等。
springmvc中的所有controller都可以通过以下方式自动扫描:

<mvc:annotation-driven >
<context:component-scan base-package="rugal.**.controller">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

答案 2 :(得分:0)

祝贺从Spring开始:)

我发现使用注释配置和spring-tool-suite(IDE)是最简单的。这样,当项目变大时,您不必在XML文件中搜索bean,而只需要与.java文件相关联。 (我更喜欢)。

下面是一个简单的剪切/粘贴示例,为您提供一些指示。这就是我通过DAO层使用hibernate来将简单的pojos持久化到数据库的方式。此示例使用MSSQL基础

为了启用@-annotaion driven configuration。在 applicationcontext.xml

中使用以下代码
<context:annotation-config/>
<context:component-scan base-package="com.***.***.wfmforecastfetcher.*"/>

HibernateConfig.java - config

import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

@Bean
public DataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    ds.setUsername("USERNAME");
    ds.setPassword("PASSWORD");
    ds.setUrl("jdbc:sqlserver://URL-TO-DATABSE\\DATABASENAME:PORT;databaseName=DATABASENAME");
    return ds;
}

@Bean
public SessionFactory sessionFactory() {
    LocalSessionFactoryBean factoryBean = null;
    try {
        factoryBean = new LocalSessionFactoryBean();
        Properties pp = new Properties();
        pp.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
        pp.setProperty("hibernate.hbm2ddl.auto", "update");
        pp.setProperty("hibernate.show_sql", "true");
        pp.setProperty("hibernate.jdbc.batch_size", "100");

        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan(new String[] { "com.***.***.wfmforecastfetcher.model" });
        factoryBean.setHibernateProperties(pp);
        factoryBean.afterPropertiesSet();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return factoryBean.getObject();
}

@Bean
public HibernateTransactionManager transactionManager() {
    return new HibernateTransactionManager(sessionFactory());
}

}

ForecastDAOImpl.java - hibernate

@Repository("forecastDAO")
public class ForecastDAOImpl implements ForecastDAO {

@Autowired
private SessionFactory sessionFactory;

public void deleteForecast(Forecast forecast) {

    sessionFactory.getCurrentSession().delete(forecast);

}

public void deleteForecasts(List<Forecast> forecasts) {
    for (Forecast frc : forecasts) {
        sessionFactory.getCurrentSession().delete(frc);
    }

}

public void persistForecast(Forecast forecast) {
    sessionFactory.getCurrentSession().persist(forecast);
}

@SuppressWarnings("unchecked")
public List<Forecast> getAllForecast() {

    List<Forecast> forecasts =     sessionFactory.getCurrentSession().createCriteria(Forecast.class).list();

    return forecasts;
}

public Forecast getForecastById(int id) {

    return (Forecast) sessionFactory.getCurrentSession().get(Forecast.class, id);

}

public void persistForecast(ArrayList<Forecast> forecasts) {

    StatelessSession session = sessionFactory.openStatelessSession();
    Transaction tx = session.beginTransaction();
    int i = 0;
    for (Forecast each : forecasts) {
        session.insert(each);

    }

    tx.commit();
    session.close();

}

public void deleteAllForecasts() {
    String hql = "delete from WFM_FORECAST";
    Query query = sessionFactory.getCurrentSession().createQuery(hql);

}
}

Forecast.java - pojo

@Entity(name = "WFM_FORECAST")
public class Forecast {

private int activityId;
private double averageHandlingTime;
private int businessUnitId;
private Date dateTime;

@Id
@GeneratedValue(generator = "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Index(name = "idIndex")
private int id;

private double interactionVolume;
private int siteId;

public Forecast() {
    // Default Constructor for Hibernate
}

public Forecast(int activityId, double averageHandlingTime, int buId, Date dateTime, double interactionVolume,
        int siteId) {
    this.dateTime = dateTime;
    this.businessUnitId = buId;
    this.siteId = siteId;
    this.activityId = activityId;
    this.setInteractionVolume(interactionVolume);
    this.setAverageHandlingTime(averageHandlingTime);
}

/**
 * @return the activityId
 */
public int getActivityId() {
    return activityId;
}

/**
 * @return the averageHandlingTime
 */
public double getAverageHandlingTime() {
    return averageHandlingTime;
}

/**
 * @return the businessUnitId
 */
public int getBusinessUnitId() {
    return businessUnitId;
}

/**
 * @return the dateTime
 */
public Date getDateTime() {
    return dateTime;
}

/**
 * @return the id
 */

public int getId() {
    return id;
}

/**
 * @return the interactionVolume
 */
public double getInteractionVolume() {
    return interactionVolume;
}

/**
 * @return the siteId
 */
public int getSiteId() {
    return siteId;
}

/**
 * @param activityId
 *            the activityId to set
 */
public void setActivityId(int activityId) {
    this.activityId = activityId;
}

/**
 * @param averageHandlingTime
 *            the averageHandlingTime to set
 */
public void setAverageHandlingTime(double averageHandlingTime) {
    this.averageHandlingTime = averageHandlingTime;
}

/**
 * @param businessUnitId
 *            the businessUnitId to set
 */
public void setBusinessUnitId(int businessUnitId) {
    this.businessUnitId = businessUnitId;
}

/**
 * @param dateTime
 *            the dateTime to set
 */
public void setDateTime(Date dateTime) {
    this.dateTime = dateTime;
}

/**
 * @param id
 *            the id to set
 */
public void setId(int id) {
    this.id = id;
}

/**
 * @param interactionVolume
 *            the interactionVolume to set
 */
public void setInteractionVolume(double interactionVolume) {
    this.interactionVolume = interactionVolume;
}

/**
 * @param siteId
 *            the siteId to set
 */
public void setSiteId(int siteId) {
    this.siteId = siteId;
}

}