Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在springmvc中获取上下文_Java_Spring_Spring Mvc - Fatal编程技术网

Java 在springmvc中获取上下文

Java 在springmvc中获取上下文,java,spring,spring-mvc,Java,Spring,Spring Mvc,我已经开始使用Spring,并在网上阅读了多个教程。我正在尝试使用SpringMVC向数据库中插入一个名称、年龄记录。在尝试实现这一点的同时,我已经停止了为我的DAO定义bean的尝试。我是否需要在其中定义application-servlet.xml并通过getBean获得它,或者我是否需要创建一个新的xml来定义bean并尝试使用应用程序上下文。另外,如果DispatcherServlet已经创建了一个新的应用程序上下文,我应该定义一个新的应用程序上下文,还是以某种方式获得它 这是我的web

我已经开始使用Spring,并在网上阅读了多个教程。我正在尝试使用SpringMVC向数据库中插入一个名称、年龄记录。在尝试实现这一点的同时,我已经停止了为我的DAO定义bean的尝试。我是否需要在其中定义application-servlet.xml并通过getBean获得它,或者我是否需要创建一个新的xml来定义bean并尝试使用应用程序上下文。另外,如果DispatcherServlet已经创建了一个新的应用程序上下文,我应该定义一个新的应用程序上下文,还是以某种方式获得它

这是我的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>

springmvc表单处理
SpringDB
org.springframework.web.servlet.DispatcherServlet
1.
SpringDB
/
上下文配置位置
/WEB-INF/SpringDB-servlet.xml
org.springframework.web.context.ContextLoaderListener
这是我的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>


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

首先,您不需要包括 上下文配置位置 /WEB-INF/SpringDB-servlet.xml

因为dispatcher 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>

上下文配置位置
/WEB-INF/DAOBeans.xml
org.springframework.web.context.ContextLoaderListener

有关更多详细信息,请参阅我的github。
你好,伙计,我非常喜欢
springwebmvc
,我会将它用作我的主要调度程序框架。
spring
hibernate
集成,这个
SSH
框架将非常强大,并且对于您开发web应用程序来说非常简单

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

hibernate
是一个ORM框架,用于将您从讨厌的基本SQL中解放出来。
springmvc
是一个类似于
struts
的调度框架,但我认为
springmvc
struts
好得多,因为它很方便

春天 要实现它们,首先需要在
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>
<context:component-scan base-package="root-package-name"/>
<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>
然后,您应该将
applicationContext.xml
放入类路径中,如配置
spring容器所示

冬眠 接下来,您需要配置
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-INF
文件夹下使用
springmvc sevlet.xml
,用于配置URL映射、响应规则等。
springmvc中的所有
控制器
都可以通过以下方式自动扫描:

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

祝贺你从春天开始:)

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

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

要启用
@-注释驱动配置
。在应用程序上下文.xml中使用以下代码

<context:annotation-config/>
<context:component-scan base-package="com.***.***.wfmforecastfetcher.*"/>
ForecastDAOImpl.java-hibernate
如果我在SpringDB-servlet.xml中定义它,那么如何访问它?我无法理解上下文层次结构,不想创建多个应用程序上下文。很可能此链接将帮助您理解applicationcontext.xml和application-servlet.xml。谢谢,此链接消除了一些疑问。你能给我一个相同示例的链接吗?另外,我如何检索DispatcherServlet的上下文或更高级别的应用程序上下文,以便使用getBean()方法?但为什么您希望在创建用于加载bean的xml文件并在上下文加载器参数中提及它们后,容器会自动为您实例化servlet上下文对象bean。是的,我现在理解了这个概念,谢谢您的回复
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());
}

}
@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);

}
}
@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;
}

}