Tomcat не вызывает контроллер API - PullRequest
0 голосов
/ 12 февраля 2019

Я новичок в весне и пробую веб-приложение maven spring.когда я пытаюсь вызвать любой API из контроллера на почтальона, я получаю http status 404 not found.Но index.jsp работает на домашней странице веб-приложения.

SpringConfig.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mongo="http://www.springframework.org/schema/data/mongo"
   xsi:schemaLocation="http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
      http://www.springframework.org/schema/data/mongo
      http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<mongo:mongo id="mongo" host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="employee" />
<mongo:repositories base-package="com.mongofunction.base.Repository"/>

<context:component-scan base-package="com.mongofunction.base"/>


<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongo" />
</bean>

web.xml:

    <!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>spring controller</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring controller</servlet-name>
    <url-pattern>/.*</url-pattern>
  </servlet-mapping>
</web-app>

Контроллер:

package com.mongofunction.base.Controller;

import com.mongofunction.base.ApplicationRuntimeException.ApplicationRuntimeException;
import com.mongofunction.base.DTO.EmployeeDTO;
import com.mongofunction.base.DTO.ResponseDTO;
import com.mongofunction.base.Service.EmployeeService;
import com.mongofunction.base.model.Employee;
import org.json.simple.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/employee")
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    @RequestMapping(value = "",method = RequestMethod.PUT)
    public ResponseDTO add(EmployeeDTO employeeDTO)
    {
        ResponseDTO responseDTO=new ResponseDTO();
        try {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        if (employee.checkNull() != null)
            throw new ApplicationRuntimeException(employee.checkNull() + " Not Found");
        employee=employeeService.add(employee);
        if(employee==null)
            throw new ApplicationRuntimeException("Error Adding to Database");
        responseDTO.setValue("Added Successfully",HttpStatus.CREATED);
    }catch (ApplicationRuntimeException e)
    {
       responseDTO.setValue(e.getMessage(), HttpStatus.BAD_GATEWAY);
    }
        return responseDTO;
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    public ResponseDTO getAllEmployee()
    {
        ResponseDTO responseDTO = new ResponseDTO();
        List<Employee> employeeList;
        try {
            employeeList=employeeService.getAll();
            if(employeeList==null||employeeList.isEmpty())
                throw new ApplicationRuntimeException("NO Records Found");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("EmployeeList", employeeService.getAll());
            responseDTO.setData(jsonObject);
            responseDTO.setValue("Records Found", HttpStatus.ACCEPTED);
        } catch (Exception e) {
            responseDTO.setValue(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return responseDTO;
    }
    @RequestMapping(value = "/{employeeId}", method = RequestMethod.GET)
    public ResponseDTO getEmployee(@PathVariable String employeeId) {
        System.out.println(employeeId);
        ResponseDTO responseDTO = new ResponseDTO();
        JSONObject jsonObject = new JSONObject();
        try {

            Employee employee = employeeService.get(employeeId);
            if(employee==null)
                throw new ApplicationRuntimeException("Record Not Found");
            responseDTO.setValue("Record Found", HttpStatus.OK);
            jsonObject.put("data", employee);
            responseDTO.setData(jsonObject);
        } catch (Exception e) {
            responseDTO.setValue(e.getMessage(), HttpStatus.BAD_REQUEST);

        }
        return responseDTO;
    }
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResponseDTO updateEmployee(@RequestBody EmployeeDTO employeeDTO) {
        ResponseDTO responseDTO = new ResponseDTO();

        try {


            Employee employee = new Employee();
            BeanUtils.copyProperties(employeeDTO, employee);
            if (employee.checkNull() != null)
                throw new ApplicationRuntimeException(employee.checkNull() + " Not Found");
            employee=employeeService.update(employee);
            if(employee==null)
                throw new ApplicationRuntimeException("Not Updated to the database");

            responseDTO.setValue("Updated Successfully", HttpStatus.ACCEPTED);

        } catch (Exception e) {
            responseDTO.setValue(e.getMessage(), HttpStatus.BAD_GATEWAY);
        }
        return responseDTO;
    }
    @RequestMapping(value = "/{employeeId}", method = RequestMethod.DELETE)
    public ResponseDTO deleteEmployee(@PathVariable String employeeId) {
        ResponseDTO responseDTO = new ResponseDTO();
        try {
            employeeService.delete(employeeId);
            responseDTO.setValue("Deleted Successfully", HttpStatus.ACCEPTED);

        } catch (Exception e) {
            responseDTO.setValue(e.getMessage(), HttpStatus.BAD_REQUEST);
        }
        return responseDTO;

    }


}

КогдаЯ пытался вызвать этот URL через почтальона -> localhost8080/MongoMaven/employee, я получаю http status 404 not found ошибку.(MongoMaven - это имя папки веб-приложения)

Я знаю, что весеннюю загрузку лучше использовать, но все же меня попросили сделать это в веб-приложении с данными весны.

1 Ответ

0 голосов
/ 13 февраля 2019

Твой web.xml мне кажется неправильным.Можете ли вы попробовать заменить его на:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>MongoMaven</display-name>
  <servlet>
    <servlet-name>MongoMaven</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MongoMaven</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

, а затем создать другой файл с именем MongoMaven-servlet.xml в той же папке, где находится web.xml, и с содержимым как:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.mongofunction.base" />
    <mvc:annotation-driven />

    <import resource="SpringConfig.xml"/>

</beans>

ипроверить

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...