【问题标题】:how to load springconfiguration xml inside web.xml?如何在 web.xml 中加载 spring 配置 xml?
【发布时间】:2017-07-08 18:54:29
【问题描述】:

如何使用 web.xml 加载 bean 并将 bean 从我的 applicaationContext 注入到我的控制器中。我试图在 web.xml 中添加上下文参数和加载 applicationContext.xml 但它不起作用..当我放 mahasiswa DispatcherServlet中的bean,它可以工作..

我的控制器:

@Autowired private Mahasiswa mhs;

@RequestMapping("/")
public String Home(){
    mhs.tampilkan();
    return "index";
}

我的马哈西斯瓦:

private String nama;

public String getNama() {
    return nama;
}

public void setNama(String nama) {
    this.nama = nama;
}

public void tampilkan(){
    System.out.println(this.nama);
}

web.xml:

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <description></description>
    <display-name>DispatcherServlet</display-name>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

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

DispatcherServlet-servlet.xml

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

<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.belajar.spring.controller">
</context:component-scan>

applicationContext.xml

<bean id="mahasiswa" class="com.belajar.spring.controller.Mahasiswa">
    <property name="nama" value="Dwi"></property>
</bean>

SS File

【问题讨论】:

  • 您在哪个位置放置了 DispatcherServlet-servlet.xml 文件?
  • 解决了你的问题吗?

标签: java xml spring-mvc


【解决方案1】:

将 web.xml 中的现有代码替换为自定义应用程序上下文,并使用以下代码

<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/DispatcherServlet-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

【讨论】:

  • 可以复制粘贴整个 web.xml 吗?
猜你喜欢
  • 2012-11-13
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-04-21
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
相关资源
最近更新 更多