我想将有角的6前端连接到Java Servlet

时间:2018-08-16 05:12:58

标签: java angular servlets

在这里,我需要将数据从有角度的6前端发送到Java Servlet。我需要知道是否有相同的目录结构。现在,我要附加我的密码

app.component.html

<html>
  <body>
    <form action="welcome" method="get">
      Enter your name<input type="text" name="name"><br>
      <button (click)="getValue()">Get Version</button>
    </form>
  </body>
</html>

app.component.ts

import { Component } from '@angular/core';
import { TestService } from './test.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private testService: TestService) { }

  getValue(){
    this.testService.getData("abc");
  }

}

service.ts

import { Injectable, EventEmitter } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TestService {
  constructor(private httpClient: HttpClient) {}
  public getData(num: String) {
    return this.httpClient.post("http://localhost:8080/first/welcome",num);
  }
}

hello.java(Servlet)

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Hello extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Hello() {}
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        String sid=request.getParameter("num");
         System.out.println(sid);
        out.print("<html><body>");
        out.print("<h3>Hello Servlet</h3>");
        out.print("</body></html>");
    }

}

此代码根本不起作用。

如果对此有任何解决方案...

此处sid的值显示为空

提前谢谢

1 个答案:

答案 0 :(得分:0)

在您的服务中,您必须映射响应才能接收数据。像这样的JSON响应:

getValue(){
  let headers = new Headers({ 'Content-Type': 'application/json' });
  let options = new RequestOptions({ headers: headers });

  return this.httpClient.post("http://localhost:8080/first/welcome",num, options )
   .map(res => res.json());
}

在您的组件中,您必须订阅:

getValue(){
  this.testService.getData("abc")
   .subscribe(
    response => {
      //do something with the response
    });

}

而且:我不会从服务器返回HTML。将其写入组件中,然后仅从服务器返回所需的值,并在客户端显示它们。