我想用Spring框架(而不是spring boot)公开服务。然后,我可以使用该服务来供给仪表板。仪表板中的图表需要json格式的数据。我的问题与这个主题类似,但有更多关于code.question的问题:Expose Service Layer directly in spring mvc
我首先做了模型,存储库来访问数据库。我正在使用Hibernate和MySQL。我使用包含main方法的类运行我的应用程序。然后,我尝试添加一个rest控制器来访问findAll方法。但是当我在Tomcat上部署应用程序时,我只得到了消息404 not found。
这是我的第一个控制器
@RestController
@RequestMapping("/fruit")
public class FruitController {
@Autowired
private IFruitRepository fruitRepo = new FruitRepository();
@RequestMapping( value = "/all", method = RequestMethod.GET )
public @ResponseBody List<Port> getFruit() {
List<Fruit> res = fruitRepo.findAll();
return res;
}
}这就是界面
public interface IFruitRepository {
Boolean create(Fruit p);
Fruit findById(int id);
List<Fruit> findAll();
Fruit update(Fruit f);
boolean delete(int id);
}这是findAll方法的实现
public List<Fruit> findAll(){
List<Fruit> à_retourner = new ArrayList<>();
try (SessionFactory factory = HibernateUtil.getSessionFactory()) {
Session session = factory.openSession();
Query query = session.createQuery("from Fruit");
à_retourner = query.getResultList();
} catch (Exception e) {
System.out.println("exception _ findAll _ Fruit : " + e);
}
return à_retourner;
}编辑:网络.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
</web-app>
dispacher-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
applicationcontext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
我应该添加servlet、dispacher servlet、应用程序上下文来通过URI查找资源吗?
发布于 2019-07-10 04:05:46
我不知道您用来测试服务的确切url是什么,但是如果您试图调用/fruit/all,它将无法工作,因为servlet调度程序被配置为处理以.form结尾的请求。要使其正常工作,您应该将servlet分派器的url-pattern更改为类似于/fruit/*的内容
https://stackoverflow.com/questions/56944813
复制相似问题