Я пытаюсь использовать класс Java в сочетании с JSP. Когда сервер запускается, пользователь переходит к JSP, который перенаправляет их в форму аутентификации для третьей стороны. После проверки подлинности они могут заполнить свою информацию, нажать «Отправить», и эта информация будет отправлена на сервер в виде HTTP-сообщения. У меня проблема с передачей переменных из моего JSP в мой класс Java. Я подозреваю, что мне может понадобиться использовать сервлет, но я хотел посмотреть, есть ли способ сделать это с помощью только Java-класса / bean-компонента, прежде чем переместить все это в сервлет. Я понимаю, что мне, возможно, придется вызвать переменную, но я не уверен, как это сделать. Любые ответы или советы будут очень полезны! Я новичок в программировании, но очень хочу, чтобы это маленькое приложение заработало. Спасибо!
serverFlow.java
public class serverFlow {
public StringBuffer getAccessToken(String redirectUri, String clientId, String clientSecret, String authCode)
throws IOException {
// Define base URL
String baseUrl = "https://idfed.constantcontact.com/as/token.oauth2";
// Build URL
String fullUrl = baseUrl + "?code=" + authCode + "&redirect_uri=" + redirectUri
+ "&grant_type=authorization_code&scope=contact_data";
URL authorizeUrl = new URL(fullUrl);
// Open connection
HttpURLConnection con = (HttpURLConnection) authorizeUrl.openConnection();
// Encode Auth Info
String credentials = clientId + ":" + clientSecret;
String auth = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
// Post Method for CTCT request
con.setRequestMethod("POST");
// Add Headers
con.setRequestProperty("Authorization", auth);
// Open input steam
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer result = new StringBuffer();
// Append each line
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
// Close the stream
in.close();
return result;
}
public static void main(String[] args){
serverFlow server = new serverFlow();
// Print string buffered response of access token, refresh token and authentication type
// Attempted to use a reqeust but unable to utilize 'reqeust.' is there a way to get the authCode in this Java class from my JSP?
System.out.println(server.getAccessToken("http%3A%2F%2Flocalhost%3A8080%2Fsignup", clientId, clientSecret, authCode));
}
}
signup.jsp
<jsp:useBean id="auth" class="infoClass" scope="session" />
<jsp:setProperty name="auth" property="authCode" />
<html>
<head>
<title>My Jmml</title>
</head>
<body>
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Attempt to get the auth code -->
<%
%>
<jsp:getProperty name="auth" property="authCode"/>
<% if(request.getMethod().equals("GET")){
// This is where the authCode is generated, how do I get this back over to my serverFlow.jsp?
String authCode = "";
try {
authCode = request.getParameter("code");
request.setAttribute("authCode", authCode);
// Verifies it in console
System.out.println("Here is the auth code: " + authCode);
}catch(Exception a){
System.out.println("Could not get Auth Code: " + a);
}
}%>
<!-- Input Form -->
<form method='post' action='<% request.getRequestURL(); %>'>
<div align="center">
<label>Email Address</label><br /><br />
<input type='text' name='email' size='50' placeholder="Email" required />
<br />
<br />
<input class="submitbutton" type='submit' value='Submit'/>
<br />
</div>
</form>
<!-- Posts info after user presses submit -->
<% if(request.getMethod().equals("POST")) {
}%>
</body>
</html>