如何将LoginServlet链接到Angular?

时间:2019-03-06 14:16:56

标签: angular servlets

我真的很困惑。

我是一名JAVA学生,一个讲座教我们如何使用Jersey设置网络服务。然后在另一堂课中,我们学习了如何通过角度与服务器通信。现在,我试图连接到使用角度项目构建的服务器,但我真的不知道该怎么办。

服务器中有一个登录servlet:

    package org.chay.CouponSystemJersey;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ex.InvalidLoginException;
import ex.SystemMalfunctionException;
import facade.AbsFacaed;
import facade.CouponSystem;
import facade.LoginType;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

    public static final String KEY_FACAED = "facaed";

    private static final String PARAM_LOGIN_TYPE = "loginType";
    private static final String PARAM_PASSWORD = "password";
    private static final String PARAM_USER_NAME = "userName";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/login.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // For userName -> the inserted user name.
        // For password --> the inserted password.
        // loginType --> The login type , one of : ADMIN, COMPANY, CUSTOMER.
        String userName = req.getParameter(PARAM_USER_NAME);
        String password = req.getParameter(PARAM_PASSWORD);
        String type = req.getParameter(PARAM_LOGIN_TYPE);

        LoginType loginType = LoginType.valueOf(type);

        HttpSession session = req.getSession(true);

        try {
            AbsFacaed facaed = CouponSystem.getInstance().login(userName, password, loginType);
            String pathURI;

            switch (loginType) {
                case ADMIN:
                    pathURI = "WEB-INF/admin.html";
                    break;
                case COMPANY:
                    pathURI = "WEB-INF/company.html";
                    break;
                default:/* CUSTOMER */
                    pathURI = "WEB-INF/customer.html";
                    break;
            }

            req.getRequestDispatcher(pathURI).forward(req, resp);
            session.setAttribute(KEY_FACAED, facaed);

        } catch (InvalidLoginException | SystemMalfunctionException e) {
            resp.sendRedirect(req.getContextPath() + "/login");
        }
    }
}

在每个操作之前,都有一个会话过滤器,用于检查用户是否已登录:

package org.chay.CouponSystemJersey;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

    public SessionFilter() {
        System.out.println("constructor");
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init was called");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest servletRequest = (HttpServletRequest) request;

        HttpSession session = servletRequest.getSession(false);

        if (session == null) {
            HttpServletResponse servletResponse = (HttpServletResponse) response;
            servletResponse.sendRedirect(servletRequest.getContextPath() + "/login");
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        System.out.println("Filter destroy was called");
    }

}

在邮递员请求中:

  

http://localhost:8080/CouponSystemJersey/login?password=1234&loginType=ADMIN&userName=admin

效果很好,并移至html页面。

在角度上,我真的不知道如何处理此请求:

  1. 我不知道哪种类型将返回邮寄请求(在此示例中,我将其设置为返回任何请求)。
  2. http请求无效。

这是我在Angular的服务器:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'
import { ApiResulte } from '../model/latlong.model';


@Injectable({
  providedIn: 'root'
})
export class CouponService {


  private password:string;
  private userName:string;
  private loginType:string;

  constructor(private myHttpClient: HttpClient) {

  };

  public doLogin(){
    let l = {
      password:this.password,
      loginType: this.loginType,
      userName:this.userName
    }

    this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/login?password="+this.password+"&loginType="+this.loginType+"&userName="+this.userName+"",l).subscribe(
        res=>{console.log(res)},
        err=>{console.log(err)}
    );
  } 
};

这是html的一个组件,客户端将在其中填充用户信息:

    <h1>login page</h1>

<h2>to login fill your ditel:</h2>


  <input type="text" [(ngModel)]="myService.userName"  placeholder="fill your user name">
  <input type="password" [(ngModel)]="myService.password" placeholder="password"><br>
  <input type="radio" [(ngModel)]="myService.loginType" value="ADMIN" checked> admin<br>
  <input type="radio" [(ngModel)]="myService.loginType" value="COMPANY"> company<br>
  <input type="radio" [(ngModel)]="myService.loginType" value="CUSTOMER"> customer
  <br>
  <button (click)="myService.doLogin()">submit</button>

这是我得到的错误:

enter image description here

请不要对我苛刻,我是初学者。 任何小事都会对我有很大帮助

JoHTVS 位置正确吗?

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
    resp.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    req.getRequestDispatcher("WEB-INF/login.html").forward(req, resp);

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
    resp.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
    // For userName -> the inserted user name.
    // For password --> the inserted password.
    // loginType --> The login type , one of : ADMIN, COMPANY, CUSTOMER.
    String userName = req.getParameter(PARAM_USER_NAME);
    String password = req.getParameter(PARAM_PASSWORD);
    String type = req.getParameter(PARAM_LOGIN_TYPE);

    LoginType loginType = LoginType.valueOf(type);

    HttpSession session = req.getSession(true);

    try {
        AbsFacaed facaed = CouponSystem.getInstance().login(userName, password, loginType);
        String pathURI;

        switch (loginType) {
            case ADMIN:
                pathURI = "WEB-INF/admin.html";
                break;
            case COMPANY:
                pathURI = "WEB-INF/company.html";
                break;
            default:/* CUSTOMER */
                pathURI = "WEB-INF/customer.html";
                break;
        }

        req.getRequestDispatcher(pathURI).forward(req, resp);
        session.setAttribute(KEY_FACAED, facaed);

    } catch (InvalidLoginException | SystemMalfunctionException e) {
        resp.sendRedirect(req.getContextPath() + "/login");
    }
}

1 个答案:

答案 0 :(得分:0)

出于安全原因,浏览器总是阻止不在同一域中的两个主机之间的请求。
Angular应用程序和服务器位于同一域(localhost)上,但不在同一端口上。

您必须通过向服务器响应中添加一些标头来允许Angular应用程序与服务器进行通信。
尝试将它们添加到您的doGet()doPost()方法中:

resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
resp.addHeader("Access-Control-Allow-Headers", "Content-Type, Accept");