Web Service to Html response - java

I am trying to build a web service that responds to a browser. Do I have to return the html code as a hardcoded string or is there a better way? It's a simple authentication service that needs to direct to the main page of an exam. I am really confused with all the tutorials and answers around the net, everyone has a different way for implementing a web service. What am I missing here? I use RestEasy on Wildfly 13.
Html call:
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>Hello</h1>
<form method="POST" action="resources/login/userlogin" >
Username: <input type="text" name="Username">
<br>
Password: <input type="password" name="Password">
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Service:
#POST
#Path("userlogin")
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String Authenticate(#FormParam("Username") String Username, #FormParam("Password") String Password) {
LoginToken token = LoginTokenSingleton.instance.getToken(Username, Password);
if (token == null) {
throw new RuntimeException("POST: User not found");
}
//return the html code for a succesfull login?
return null;
}

You are invoking a POST request when you submit the form having the username and password.
Once the user is authenticated in the backend you can return a Success HTTP status code - 200 and on the basis of that you can redirect the user to the main page. And if the user is not authenticated you can send a Not Authenticated Status Code 401 and redirect the user to some other page.

Related

Thymeleaf Template Not Posting Body

My thymeleaf form is not picking up the input longUrl. When I run the application on debug, it hits the post request below with "". How can I make it pick up the form input and send it over in the body?
Thymeleaf Form:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST" th:action="#{create_short_url_thymeleaf}">
<h1>Hit Enter to Shorten Your Long Url</h1>
<input type="text" th:name="longUrl"/>
</form>
</body>
</html>
Even when I try to manually populate the value, it still doesn't make it into the controller
<input type="text" name="longUrl" value="somelongurl"/>
Controller Code:
#Controller
#RequestMapping("/api/v1")
public class UrlShorteningController {
#GetMapping("/create_short_url")
public String newShortUrl(Model model) {
model.addAttribute("longUrl",
"");
return "some-form";
}
#PostMapping("/create_short_url_thymeleaf")
ResponseEntity<String> newShortUrlFromThymeleaf(#ModelAttribute String longUrl) {
// Running the application on debug, I make it here, but the longUrl is empty.
....
}
try to replace
th:action="#{create_short_url_thymeleaf} with
th:action="#{/create_short_url_thymeleaf}
Ah, I solved it. I needed to swap that #ModelMapper annotation for a #RequestBody and now it works.

Http404 error while click the submit button (Servlet question)

Guys! I am new to servlet. I tried to follow the step with book to create a servlet. It's just a login form where user enter the userid and password click the login, it should then display the input value in webpage. However, when I enter the userId and password, I get Http404 error.
I was wondering something maybe wrong with context.xml but I am not sure.
I also tried to mapping the servlet in xml, but still get the error.
here is my html
<!DOCTYPE html>
<html>
<head>
<title>USER LOGIN</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial- scale=1.0">
</head>
<body>
<form action="UserServlet" method="get">
<!-- Name text Field -->
<p>
<label>User ID</label>
<input type ="text" name="userId" size="30"/>
</p>
<p>
<label>User Password</label>
<input type ="text" name="userPassword" size="30"/>
</p>
<!--Button for submit -->
<input type ="submit" name="Login" value="LogIn"/>
<input type ="button" value="LogOut" onclick="self.close()"/>
</form>
</body>
here is my servlet.java
public class UserServlet extends HttpServlet
{
//process the HTTP GET REQUEST//
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
//get the data
String userId=request.getParameter("userId");
String passWord=request.getParameter("userPassWord");
//determine the input if user missing these two send back the message
if (userId.isEmpty()&&passWord.isEmpty())
{
out.println("UserId and passWord can not be empty.");
}
else
{
out.println("<p>your id is "+userId);
out.println("<br>your password is"+passWord);
out.println("<br>You entered the data successfully </p>");
}
}
}
here is my context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/userLogin"/>
I didn't change any thing in context.xml
its working when I run the project, but once I click the button it just gives me
Type Status Report
Message /userLogin/UserServlet
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
can you check what is the servlet mapping provided in web.xml. I think the mapping would not be matching the request.
or you can post the web.xml

initiating http post request from html form and receiving that request in java

i am running a simple web server in java that is running on port 8080 on my machine , the server do receive request that come from browsers (when i write this URL (localhost:8080) ) however i wanted to receive request that come from this html page
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="post" action="192.168.1.1:8080">
<input type="text" name ="txt">
<input type="submit" name="sub">
</form>
</body>
</html>
and the result was The webpage cannot be displayed
and my second try was this
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="post" action="server.java">
<input type="text" name ="txt">
<input type="submit" name="sub">
</form>
</body>
</html>
and after i clicked the submit button it opened the download dialog (download server.java).
however i managed to initiate a request on my own in java
Socket socket = new Socket("localhost",8080);
String request = "get / http/1.1";
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();
os.close();
and my server received that request with no problems , i am not sure what am I missing here and what is that layer that initiate a correct request to a php website for example.
Java is not a scripting language and does not work like php or perl. In your server you should map request URI to handling code (e.g. in web.xml). In your <form action="..."> you should provide an URI which your server will handle.

Validating a form using JSP

I'm completely new to JSP and am creating a simple form and validating it through JSP.
Here's my code :-
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<%#page import="java.io.* , java.sql.* , java.util.* , javax.servlet.*" %>
<body>
<h1>Login Page by JSP</h1>
<hr>
<form method="post" action="index_jsp">
Enter name : <input type="text" name="user">
Enter password : <input type="password" name="pass">
<input type="submit" value="login">
</form>
<%
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
%>
<br>
Click here !
</body>
</html>
But each and every time I run it , I get a NullPointerException .
What am I doing wrong ? Immediate help would be appreciated !
Thanks!
First bit of advice, since you're new to JSP: Don't write scriptlet code. That's all the stuff between <% and %>. It's a 1998 vintage technology that should be discouraged. Learn JSTL and Model-2 MVC instead.
You need a servlet to orchestrate those JSPs. Every web MVC framework that I know of has what's called a front controller servlet to manage the communication and orchestration. You should, too.
You have the form POST in this JSP, sending the HTTP request to index_jsp (bad name). It's executing in the browser on the client machine.
I would expect you to send this to a servlet on the server side that gets the HTTP request, gets the username and password out, compares the values to a database to see if the user is indeed registered. Then I'd either send the next view or route to the "sorry" page. That's not what you're doing.
Don't do equals checks on the variables, rather do them against the constants:
if("admin".equals(user) && "admin".equals(pass)) {
response.sendRedirect("wel.html");
}
This way you cannot get the NPE.
Change this line
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
with
if(user!=null){
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
}
You are not checking null for request attributes.
replace
String user = request.getParameter("user");
String pass = request.getParameter("pass");
with
String user = request.getParameter("user") != null ? request.getParameter("user") : "";
String pass = request.getParameter("pass") != null ? request.getParameter("pass") : "";
change codeļ¼š
if("admin".equals(user) && "admin".equals(pass)) {
response.sendRedirect("wel.html");
}
When you first run jsp,it will execute the code,but user and pass is null.

How to send the url of current page to the servlet without refreshing the page

I want to send the url of current page to the servlet without refreshing or reloading the page. here is the code-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Action Onclick </title>
<!-- <script>
$('#contactForm').submit(function () {
alert('sdafjb');
return false;
});
</script>-->
</head>
<body>
<form id="contactForm" >
<fieldset>
<label for="Name">Name</label>
<input id="contactName" type="text" />
</fieldset>
<fieldset>
<label for="Email">Email</label>
<input id="contactEmail" type="text" />
</fieldset>
<fieldset class="noHeight">
<textarea id="contactMessage" cols="20"></textarea>
submit
</fieldset>
</form>
<small id="messageSent">Your message has been sent.</small>
</body>
My servlet's name is scriptservlet. Please help me...
AJAX was built for communicating with a server without reloading or changing the current page in the browser. You should be able to just create an AJAX call to your server and send your server whatever data you want without affecting the current page.
Under normal circumstances, AJAX calls are restricted to "same origin" which means you can only communicate with a server on the same domain as the current web page so you would also have to make sure that you satisfy this security restriction.
Do an ajax call to the servlet and pass the Url of current page by doing (request.getRequestUri()) to the servlet.
var requestUri = '<% request.getRequestUri()%>';
var hostname = location.host;
$.ajax({
type: "POST",
url: "/scriptServlet",
data: { "host": hostname, "uri": requestUri }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Please note, syntax might not be correct but u have to make a ajax callt o achieve the result.
This is possible by sending back the appropriate response code (204 I guess) back to the client from the server (servlet). This way even though the request is submitted the page is not refreshed / reloaded.
You could use a hidden field in your form.
<input type="hidden" name="currentPage" value="<%=request.getRequestURL()%>">

Categories