我正在尝试使用Spring和Hibernate构建REST API。
运行服务器时,它不会返回任何错误,但无法访问链接。
这是我的配置文件:
spring.xml
<mvc:annotation-driven />
<context:component-scan base-package="org.bloggy.spring" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/my_bloggy?createDatabaseIfNotExist=true" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="txManager"
class="org.springframework.transaction.jta.JtaTransactionManager" />
那是我的web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/resources/spring.xml</param-value>
<param-value>WEB-INF/resources/dao.xml</param-value>
<param-value>WEB-INF/resources/service.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
控制器:
@Controller
@RequestMapping(value = "users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public List<User> getUsers() {
return userService.listUsers();
}
}
答案 0 :(得分:1)
如@Ken所述,为了将您的API公开为REST AP,您需要使用@RestController,或者如果您想使用@Controller,则使用@ResponseBody注释。
关于您的问题,我认为您需要将RequestMapping定义为
@Controller
@RequestMapping(value = "api")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/users", method = RequestMethod.GET)
public List<User> getUsers() {
return userService.listUsers();
}
}
或
@Controller
@RequestMapping(value = "api/users")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(method = RequestMethod.GET)
public List<User> getUsers() {
return userService.listUsers();
}
}
请查看是否有效。
答案 1 :(得分:1)
在logs中可见,应用程序MyBloggy
实际上并未初始化任何spring bean。 Tomcat上部署的缓存或war文件存在问题。理想情况下,在部署war
时,除非已禁用,否则所有初始化的bean都可以在日志中看到。确保您在服务器上部署了正确的war
。
答案 2 :(得分:0)
您正在使用@Controller批注,但是如果要公开REST Web服务,则需要使用@RestController或@ResponseBody
@RestController
@RequestMapping(value = "users")
public class UserController