Retrieve parameters in a servlet with a JDBC client - java

I have a JDBC client calling a servlet.
Here's my client :
String query = "select * FROM Table";
int port = 8080;
String user = "user";
String password = "passwd";
String jdbcAvaticaURL = "jdbc:avatica:remote:url=http://localhost:"+port+";authentication=BASIC;serialization=JSON";
Connection connection = DriverManager.getConnection(jdbcAvaticaURL, user, password); // ,info);
executeQuery(connection,query);
connection.close();
And here's my servlet :
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getParameter("user"); // returns NULL
Enumeration<String> params = request.getParameterNames(); // Empty Collection
response.setContentType("application/json;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
// DO THINGS
}
is there a way to retrieve the user and password from DriverManager.getConnection(jdbcAvaticaURL, user, password); in the servlet ?
I already tried String auth = request.getHeader("Authorization"); when I put the parameters in the JDBC URL, it's working, I can retrieve the user and the password, but this is not what I want.

It's fine, after trying to get the attributes, parameters, etc... of the request, turns out the credentials were just in the request...
Doing this in the servlet let me access the user and password used for the connection in the client (after some JSON parsing) :
String myRequest = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));

Related

How to get CasToken from server?

I want to do a Cas Authentication from Standalone-Application but it fails on getting the Ticket from server. Can anyone provide me example code for a method that returns the ticket as String so i can use it for the Authentication. As you see the only Parameter should be the URL from the server. Thats waht i have yet(i know casToken is initialized on null an it doesnt work).
protected String getCasTicket(String serviceUrl) {
String casToken = null;
if (casToken == null){
logger.error("Failed to get CAS-Token!");
}else{
logger.info("Got CAS-Token successful!");
}
return casToken;
}
public class CasAuthenticationServlet extends HttpServlet {
...
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// NOTE: The CasAuthenticationToken can also be obtained using
// SecurityContextHolder.getContext().getAuthentication()
final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
// proxyTicket could be reused to make calls to the CAS service even if the
// target url differs
final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);
// Make a remote call using the proxy ticket
final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8");
String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");
...
}
CasAuthenticationProvider constructs a CasAuthenticationToken including the details contained in the TicketResponse and the GrantedAuthoritys.
Control then returns to CasAuthenticationFilter, which places the created CasAuthenticationToken in the security context.
Cas Example: https://docs.spring.io/spring-security/site/docs/4.2.x/reference/html/sample-apps.html#cas-sample
EDIT:
Please refer https://www.javaworld.com/article/3313114/what-is-a-java-servlet-request-handling-for-java-web-applications.html for creating a servlet

One Servlet need to Call another Servlet along with response & request

This is the code (Validate.java Servlet File)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("u");
String password = request.getParameter("p");
Connection con = DBConnection.Connect();
String sql = "select *from users where name=? and pass=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
request.getRequestDispatcher("WelcomeServlet").forward(request, response); //This line calls another servlet
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
WelcomeServlet.java Servlet File
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
response.setContentType("html/text");
PrintWriter pw = response.getWriter();
pw.write("<html><body>");
pw.write("<title>Welcome User</title>");
pw.write("<h1>" + username + "</h1>");
pw.write("</body></html>");
pw.close();
}
Output
I want the validate servlet to call welcome servlet but its asking me whether to download a validate servlet file .PFA for more details
I am getting the popup to download Validate Ser
The content type should be text/html (you wrote html/text) otherwise the browser does not know what to do with the file and asks for downloading it.
There are also a few other problems with the code worth mentioning
You do not really check the result from the DB, so you will forward even if the user does not exist.
You use the parameter name u in one servlet but username in the other.

How to get query parameters from HttpServletRequest (Tomcat 9.0)?

The server recieves requests from two clients - Raspberry Pi and Android app, both send requests using HttpURLConnection. I need to pass parameters with theese requests, e.g:
http://192.168.0.10:8080/MyProject/MyServer/rpi/checktask?rpi="rpi"
doing it as:
String requestUrl = "http://192.168.0.10:8080/MyProject/MyServer/rpi";
String query = String.format("/checktask?rpi=%s",
URLEncoder.encode("rpi", "UTF-8"));
URL url = new URL(requestUrl + query);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.connect();
The Servlet has annotation:
#WebServlet(name = "MyServer", urlPatterns = { "/MyServer/rpi/*", "/MyServer/app/*"})
But when Servlet gets request as above following happens:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getRequestURI(); // /MyProject/MyServer/rpi/*
String query = request.getQueryString(); // null
String context = request.getContextPath(); // /MyProject
String servlet = request.getServletPath(); // /MyServer/rpi
String info = request.getPathInfo(); // /*
}
Although according to those answers:
How to use #WebServlet to accept arguments (in a RESTFul way)?
and
How come request.getPathInfo() in service method returns null?
it should look like this:
String path = request.getRequestURI(); // /MyProject/MyServer/rpi//checktask?rpi="rpi"
String query = request.getQueryString(); // rpi="rpi"
String context = request.getContextPath(); // /MyProject
String servlet = request.getServletPath(); // /MyServer/rpi
String info = request.getPathInfo(); // /checktask?rpi="rpi"
What am I doing wrong?
Your URL string is
http://192.168.0.10:8080/MyProject/MyServer/rpi/checktask?rpi="rpi"
The name of the parameter in the above String is "rpi".
The below code will give you the required value of the parameter "rpi".
String rpi = request.getParameter("rpi");

Servlet Dispatcher URL

I have problem when I submit my form to insert data
the URL can't change and when I refresh it, the data reinsert
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String _1 = request.getParameter("company_name").toString();
String _2 = request.getParameter("city").toString();
String _3 = request.getParameter("state").toString();
String _4 = request.getParameter("zipcode").toString();
String _5 = request.getParameter("branch").toString();
String _6 = request.getParameter("address").toString();
Database db = (Database) getServletContext().getAttribute("db");
try {
String sql = "insert into company(company_name,city,state,zipcode,branch,company_address) values('"+_1+"','"+_2+"','"+_3+"','"+_4+"','"+_5+"','"+_6+"')";
db.updateSql(sql);
} catch (Exception e2) {
System.out.println(e2);
}
getServletContext().getRequestDispatcher("/company.jsp").forward(request, response);
}
Your problem comes from the understanding of the forward method.
This method transfer the request and the response object to the new URL. It is invisible for the client's browser so the URL is unchanged. By reloading the page, you repeat your resquest so your sending again your data.
This behaviour is completely normal. If you want to redirect to another URL and have another request then you should use the sendRedirect method.
Refer to this post to have a complete description of both methods.

Declare a session variable golbaly to access from DoGet and DoPost in a sevlet

I have a servlet where I need to declare a session which can be acceptable form doGet and doPost both how I should do this?
I have done
#WebServlet(name = "LoginLogout", urlPatterns = {"/LoginLogout.do"})public class LoginLogout extends HttpServlet {//For Session
HttpSession session = request.getSession(true);
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String status = request.getParameter("status");
System.out.println(status);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String loginId = request.getParameter("login_id");
String password = request.getParameter("password");
System.out.println(loginId);
//Inserting value to the Pogo named "newLoginPogo"
loginData newLoginPogo = new loginData();
newLoginPogo.setLoginId(loginId);
newLoginPogo.setPassword(password);
//Creating a obj of ModelLogin to send the loginId and Password via a method which is in ModelLogin class
ModelLogin loginBis = new ModelLogin();
loginData userData = loginBis.checkUser(newLoginPogo);
String userExist = userData.getUserExist();
System.out.println(userExist);
if ("yes".equals(userExist)) {
System.out.println("In while loop of Servlet");
String firstName = userData.getFirstName();
String userId = userData.getUserId();
boolean IsSu = userData.getIsSu();
//conveting boolean to string
String superuser = new Boolean(IsSu).toString();
//Creating a session
session.setAttribute("firstName", firstName);
session.setAttribute(userId, "userId");
session.setAttribute(superuser, "IsSu");
//==============================================================================================================
//If user does exist show the Success Message and forward Dashboard
//==============================================================================================================
//Session for success message
String succmsg = "Login Successful";
session.setAttribute("succmsg", succmsg);
getServletConfig().getServletContext().getRequestDispatcher("/WEB-INF/ViewPages/dashboard/dashboard.jsp").forward(request, response);
} //==============================================================================================================
//If user does not exist show the Error Message
//==============================================================================================================
else if ("no".equals(userExist)) {
//Session for success message
System.out.println("inside NO");
String emsg = "Login Error";
session.setAttribute("errmsg", emsg);
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
} else {
}
/*
//===============================================================================================================
//code for Logout
//===============================================================================================================
String status = request.getParameter("status");
if ("logout".equals(status)) {
//clearing the session
session.invalidate();
//forwarding to index page
getServletConfig().getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
*/
} finally {
}
}}
But it says
Can Not find Symbol
in this line HttpSession session = request.getSession(true);
You don't need to have session variable in servlet as field. In general - this is kind of common mistake. There will be only one onstance of servlet serving lots of requests, and unless you declare it as single-threaded - the requests would be handled concurrently.
HttpSession will be pre-exist for you in doGet and doPost via request object. Servlet container will guarantee this. So simply obtain reference to the session in doGet/doPost and do whatever you want.
What you desire is one of the roles of HTTP session.
You can look at it as a conversation between the client and the server.
As long as the "conversation" (HTTP session) is open and alive, you can set variables on the HTTP session, and access them from different requests that will sent on the same session.
Look at this as some sort of "shared memory" that exists during the "conversation time".
You can find many examples on how to do that over the internet.
Here is an example for session tracking.

Categories