【发布时间】:2016-03-08 22:29:41
【问题描述】:
我是 spring MVC 的新手,我正在尝试从我的 Java 应用程序访问 spring servlet 并打印结果。但我不能让它工作。我可以从导航器的 url 访问 index.jsp 文件:http://localhost:8080/MyApp/ 但是我的主课引发了一个异常 java.io.FileNotFoundException:http://localhost:8080/MyApp/helloWorld。 谁能帮帮我?
这是我的 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" 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>MyApp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!-- will look for application-servlet.xml file to load -->
<servlet-name>application</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
我的应用程序-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.myapp.server.controllers" />
<context:component-scan base-package="com.myapp.server.managers" />
<context:component-scan base-package="com.myapp.server.repositories" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
我的弹簧控制器
@Controller
public class ApplicationController {
@Autowired
private ApplicationManager applicationManager;
@RequestMapping("/helloWorld.do")
public String helloWorld() {
return "helloWorld";
}
}
我的 Java 代码
public class Test {
public static void main(String[] args) throws IOException {
String url = "http://localhost:8080/MyApp/helloWorld";
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
System.out.println(response.read());
}
}
【问题讨论】:
-
你有一个名为“helloWorld”的jsp吗?因为 spring 正在试图找到它,这就是你得到异常的原因。
-
您是否暗示当您在普通网络浏览器中打开
http://localhost:8080/MyApp/helloWorld时它可以正常工作?如果也不是,那么这个问题与URLConnection无关。
标签: java spring spring-mvc servlets