gpt4 book ai didi

java - 如何将 servlet 添加到 spring 框架 java web 应用程序?

转载 作者:行者123 更新时间:2023-12-01 11:17:09 26 4
gpt4 key购买 nike

我认为这非常简单,但显然我遗漏了一些东西,而且我似乎无法弄清楚它是什么。

我正在尝试将 servlet 添加到使用 java 和 spring 编写的现有 Web 应用程序中。这是我所做的:

我将以下内容添加到 web.xml:

<servlet>
<servlet-name>SettingServlet</servlet-name>
<display-name>SettingServlet</display-name>
<description>Provides a rest endpoint for getting and setting settings.</description>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/SettingServlet-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>SettingServlet</servlet-name>
<url-pattern>/setting/*</url-pattern>
</servlet-mapping>

然后我创建了以下文件(.../WEB-INF/SettingServlet-servlet.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="settingController"
class="com.my.package.path.SettingController"
p:settingService-ref="settingService"/>

</beans>

然后我创建了以下 Controller (com.my.package.path.SettingController.java):

@Controller
@RequestMapping("/setting")
public class SettingController {
private SettingService settingService;
public void setSettingService(final SettingService settingService) {
Validate.notNull(settingService, "SettingController::settingService cannot be null");
this.settingService = settingService;
}

@ResponseBody
@RequestMapping(value = "/{name}", method = RequestMethod.GET)
@Secured({ "ROLE_ADMINISTRATOR", "ROLE_CURIOUS_GEORGE" })
public ResponseEntity<String> getSettingRequest(@PathVariable("name") final String name, @RequestParam("setting_family") final String settingFamily) {
final String jsonBody = "{\"setting\":\"" + name + "\", \"Setting Family\":\"" + settingFamily + "\", \"value\":\"test\"}";
return new ResponseEntity<String>(jsonBody, HttpStatus.OK);
}
}

我做错了什么? :( 尝试在/setting/fruit?setting_family=foods 执行 GET 请求时收到 404 未找到异常

最佳答案

当您将调度程序的 url 模式声明为“/setting/*”,然后在 Controller 中声明“/setting”作为该 Controller 的根 requestMapping 时,您应该能够使用以下 url 访问您的 Controller :/setting/setting/fruit?setting_family=食物:)

关于java - 如何将 servlet 添加到 spring 框架 java web 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31684727/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com