Restful webservice无法在jersy中读取Angular 5服务调用的参数

时间:2018-04-05 20:08:23

标签: java angular5 restful-architecture

我试图通过从httpParams和header传递参数来从Angular组件调用Restful Webservice,但是Jery Restful Webservice无法从请求中读取用户名(uname)。

Angular 5中的AppTestService

import { Injectable, Inject } from "@angular/core";
import { Http, Headers } from "@angular/http";
import { HttpParams, HttpHeaders } from "@angular/common/http"
import { HttpClient } from "selenium-webdriver/http";

@Injectable()
export class AppTestService {
    constructor(@Inject(Http) private proxy: Http){}

    url = "http://localhost:8081/loginangular/webapi/AngularUser/login";
    postGitUser(){        
        let headers = new Headers();
        headers.append('Content-Type','application/json; charset=utf-8');

        return this.proxy.post(this.url,{params:{uname: 'rajdharg',paswd: '****'}}, {headers:headers}).subscribe(resp => {
            console.log("response %o , ", resp);
        });
    }
}

RestFul Webservice中的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.grajdhar</groupId>
    <artifactId>loginangular</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>loginangular</name>

    <build>
        <finalName>loginangular</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <inherited>true</inherited>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.glassfish.jersey</groupId>
                <artifactId>jersey-bom</artifactId>
                <version>${jersey.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.glassfish.jersey.containers</groupId>
            <artifactId>jersey-container-servlet-core</artifactId>
            <!-- use the following artifactId if you don't need servlet 2.x compatibility -->
            <!-- artifactId>jersey-container-servlet</artifactId -->
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.inject</groupId>
            <artifactId>jersey-hk2</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- uncomment this to get JSON support-->
        <dependency>
            <groupId>org.glassfish.jersey.media</groupId>
            <artifactId>jersey-media-json-binding</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

    </dependencies>
    <properties>
        <jersey.version>2.26</jersey.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
</project>

UserResource.java

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

/**
 * @author rajdhagG
 *
 */

@Path("/AngularUser")
public class UserResource {

    UserRepository user = new UserRepository();
    User loginUser = new User();

    @POST
    @Consumes({MediaType.APPLICATION_JSON})
    @Produces({ MediaType.APPLICATION_JSON })
    @Path("login")
    public User searchUser(@QueryParam("uname") String uname, @QueryParam("paswd") String paswd){
        System.out.println("Logging in the with " + uname + ", " + paswd);
        System.out.println("This = > " + user.getUserDetails(uname, paswd));
        loginUser = user.getUserDetails(uname, paswd);
        if(loginUser.getUname() != "" && loginUser.getPaswd() != ""){
            return loginUser;
        }else {
            loginUser.setUname("Not Present");
            loginUser.setPaswd("Not present");
            return loginUser;
        }
    }
}

Response to Angular Service call with null username and password, event after passing it in the request

Restful Webservice IDE控制台上的输出:

    Fri Apr 06 01:26:25 IST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Logging in the with null, null
    This = > User [uname=, paswd=]

1 个答案:

答案 0 :(得分:0)

基本上,您创建了使用application/json内容的请求的服务方法,同时期望查询参数为application/x-www-form-urlencoded内容的请求。这两个是不匹配的。你必须直截了当,所以你有两个选择:

  • 将您的请求的内容类型更改为application/x-www-form-urlencoded,并通过删除@Consumes({MediaType.APPLICATION_JSON})注释来更改服务方法定义。
  • 更改服务方法以使用您自己的某个对象,自定义类Credentials,其中包含2个字段:用户名和密码。请求您在其正文中包含序列化的Credentials对象。

这两种解决方案中的一种是必要的,因此服务可以匹配您使用适当的服务方式发送的请求。

我希望它有所帮助。