在Spring中调用rest api时获得404

时间:2017-06-07 05:29:54

标签: java spring rest http-status-code-404

控制器

<?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/j2ee" 
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd 
http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring MVC Application</display-name>
  <servlet>
    <servlet-name>App</servlet-name>
    <servlet-class>  org.springframework.web.servlet.DispatcherServlet</servlet-class
<load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>App</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Web.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"
   xmlns:context="http://www.springframework.org/schema/context"
   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">

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

应用-servlet.xml中

Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:MathWebApp' did not find a matching property.
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server version:        Apache Tomcat/8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server built:          May 10 2017 17:21:09 UTC
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Server number:         8.0.44.0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Name:               Mac OS X
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: OS Version:            10.12.4
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Architecture:          x86_64
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Java Home:             /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/jre
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Version:           1.8.0_111-b14
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: JVM Vendor:            Oracle Corporation
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_BASE:         /Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: CATALINA_HOME:         /Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.base=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dcatalina.home=/Users/kegupta/Desktop/apache-tomcat-8.0.44
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dwtp.deploy=/Users/kegupta/Documents/Framework/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Djava.endorsed.dirs=/Users/kegupta/Desktop/apache-tomcat-8.0.44/endorsed
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/kegupta/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:39 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Jun 07, 2017 10:35:39 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 480 ms
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Jun 07, 2017 10:35:39 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.44
Jun 07, 2017 10:35:40 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Jun 07, 2017 10:35:40 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'App'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization started
Jun 07, 2017 10:35:40 AM org.springframework.web.context.support.XmlWebApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'App-servlet': startup date [Wed Jun 07 10:35:40 IST 2017]; root of context hierarchy
Jun 07, 2017 10:35:40 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/App-servlet.xml]
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req.*] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping registerHandler
INFO: Mapped URL path [/ws/req/] onto handler 'controller'
Jun 07, 2017 10:35:40 AM org.springframework.web.servlet.DispatcherServlet initServletBean
INFO: FrameworkServlet 'App': initialization completed in 617 ms
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Jun 07, 2017 10:35:40 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jun 07, 2017 10:35:40 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1514 ms

当我尝试在浏览器上点击http://localhost:8080/ws/req时,它会显示HTTP状态404.

在日志中注册的URL被注册:

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;


public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            //Toast.makeText(mContext, "isGPSEnabled = "+isGPSEnabled, Toast.LENGTH_SHORT).show();
            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//            Toast.makeText(mContext, "isNetworkEnabled = "+isNetworkEnabled, Toast.LENGTH_SHORT).show();

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
                showSettingsAlert();
                Toast.makeText(mContext, "No Internet Connection", Toast.LENGTH_SHORT).show();
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            Log.d("isNetworkEbanbled", "Network Available");
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }

                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
                                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                                (this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)
                        {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS is Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    Log.d("isGPSEnabled", "GPS");
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }

                    }
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS  settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Go to Seeting and Please Enabled GPS");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

我被困很久了。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

从日志中我可以看到正在部署的战争名称App。尝试使用此网址:

http://localhost:8080/App/ws/req 

Or

http://localhost:8080/<deployed tomcat war name>/ws/req 

答案 1 :(得分:0)

TestBean readBookmarks() {
TestBean bean = new TestBean("Test", 25);
return bean;

这个函数似乎缺少@ResponseBody,TestBean(可能是一个自定义类)也不是Spring可序列化的东西。你可以尝试发送String而不是TestBean - 这应该可行。

此外,部署目录可能与您的web.xml配置(即除App之外的其他内容)不同。您可以尝试加载http://localhost:8080/ {Dir} / ws / req,其中Dir ==部署目录(!='App')。

上述两件事应该可以解决您的问题。