Http404 error while click the submit button (Servlet question) - java

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

Related

Controller sends empty Object from Thymeleaf - Spring Boot

Hi Guys!
I have been implementing service in Spring Boot which
allows users to send anonymouse questionaries to server.
I have already implemented most of the backend like adding users etc. and right now I have been struggling with one action which take answers from user and sends into server (save in database).
Object containing answers (filledSurvey) is being sent as empty. In this same logic in logging users fields from form are corectly send forward.
This endpoint displays questionary:
#RequestMapping(path = {"/try", "/try/{id}"})
public String tryCompletingSurvey(Model model, #PathVariable("id") Long id) {
Connection connection = connectionService.getConnection(id);
FilledSurvey filledSurvey = connection.getSurvey().getTemplate();
for (FilledQuestion filledQuestion : filledSurvey.getFilledQuestions()) {
filledQuestion.getFilledAnswers().get(0).setCheck(true);
}
model.addAttribute("filledSurvey", filledSurvey);
return "completing/completing";
}
This is thymeleaf html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Completing survey</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">
</head>
<body>
<center>
<form action="#" th:action="#{/user/surveys/finish}" th:object="${filledSurvey}" method="post">
<!-- <div th:each="question, questionStat : ${survey.getFilledQuestions()}" >-->
<!-- <p th:text="${question.getQuestion()}"></p>-->
<!-- <div th:each="answer, answerStat: ${question.getFilledAnswers()}" >-->
<!-- <input type="radio"-->
<!-- th:name="question+${questionStat.index}"-->
<!-- th:field="*{}"-->
<!-- th:value="${true}">-->
<!-- <label th:text="${answer.answer}">-->
<!-- </label>-->
<!-- </div>-->
<!-- </div>-->
<h2>Survey name: </h2>
<h3 th:text="${filledSurvey.getSurveyName()}"></h3>
<h2>Number of questions: </h2>
<h3 th:text="${filledSurvey.filledQuestions.size()}"></h3>
<div class="col-md-6">
<input type="submit" style="align-content: center" class="btn btn-primary" value=" Send ">
</div>
</form>
</center>
</body>
</html>
And this is endpoint which stores empty object from thymeleaf:
#RequestMapping(path = "/finish", method = RequestMethod.POST)
public String getHash(FilledSurvey filledSurvey) {
StringBuilder sb = new StringBuilder();
for (FilledQuestion question : filledSurvey.getFilledQuestions()) {
for (FilledAnswer answer : question.getFilledAnswers()) {
if (answer.isCheck()) sb.append(answer.getAnswer());
}
}
LocalDateTime date = LocalDateTime.now();
sb.append(date);
String hash = sb.toString();
hash = Base64.getEncoder().encodeToString(sb.toString().getBytes());
filledSurvey.setHash(hash);
surveyMagazinService.addSurveyToMagazin(filledSurvey);
return "completing/finish";
}
I changed code to automaticly mark answers for now.
This the picture of the object in the next endpoint:
filledSurvey object
I am aware that this is common question but i have been looking for the answer for a while now and couldn't figure it out. I have no errors in the console as well. I would appreciate any help or feedback.
If I understood correctly, I see following issue:
You are using a form to submit the survey data and use the th:object="${filledSurvey}" to bind the data. But there is actually not data send back to the controller, when the form is submitted, because there are no input fields defined that have the th:field attribute applied.
The request that will be send to the server on a submit, will contain form encoded data of all fields that you assign a th:field attribute to. The controller will map the form encoded data to a FilledSurvey object using java bean convention in the getHash method.
EDIT: can you try adding the #ModelAttribute annotation:
#RequestMapping(path = "/finish", method = RequestMethod.POST)
public String getHash(#ModelAttribute FilledSurvey filledSurvey) {
...
Try adding an input field like this inside your form:
<input type="hidden" th:field="*{surveyId}" >
This should give you at least an FilledSurvey object with the id set on your "/finish" endpoint. You can then use the id to fetch the survey like its done in the first code snippet.
The way you are using the th:field within your list of questions will not work, because spring cannot map this kind of structure. See https://spring.io/guides/gs/handling-form-submission/ to understand how form submission works with spring mvc.
I hope this helps a bit, best regards ;)

Web Service to Html response

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.

Changing form action method name but server reffering to old method name

I'm using Eclipse Indigo. In my HTML form action method I put <form action="T1" method="post"> where T1 is a Java servlet. If I edit and rename form action method to T2 and save changes, when running tomcat server on localhost, after clicking on button it still goes to T1!
I tried refreshing my project, deleting and recreating server but still the same problem. What should I do?
Any help is appreciated.
My web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
This is my html file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Pk" method="post">
Name <input type="text" name="tex1"> <br>
Address <input type="text" name="tex2"> <br>
College Name <input type="text" name="tex3"> <br>
Aggregate percentage <input type="text" name="tex4"> <br>
Title of Resume <input type="text" name="tex5"> <br>
Username <input type="text" name="tex6"> <br>
Password <input type="password" name="tex7"> <br>
<input type="submit" name="sub" value="Login"> <br>
</form>
</body>
</html>
And this is servlet file:
public class Pk extends HttpServlet {
private static final long serialVersionUID = 1L;
String name="",addr="",coll="", aggper="", tor="", user="", pass="";
public Pk() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
name=(String)request.getParameter("tex1");
addr=(String)request.getParameter("tex2");
coll=(String)request.getParameter("tex3");
aggper=(String)request.getParameter("tex4");
tor=(String)request.getParameter("tex5");
user =(String)request.getParameter("tex6");
pass =(String)request.getParameter("tex7");
System.out.println("Reached after fetching values");
if(user.equals("")||pass.equals("")||user.equals(null)||pass.equals(null))
{
out.println("Username or Password cannot be blank.");
}
else
{
System.out.println("Reached in else condition");
Pk2 reg=new Pk2();
reg.Registration(name,addr,coll,aggper,tor,user, pass);
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.forward(request, response);
}
}
}
The previous time I faced the same issue was because of the browser caching the webpage. Can you please clear history or try the same in Private Mode of the browser(or Chrome Incognito mode). You can also verify the source code of the webpage by using firebug utility or chrome's own utility by pressing F12 button in Chrome.
PS - I could have mentioned this in a comment, but I don't have enough Stackoverflow reputation to comment on this post.
Got it fixed finally,problem was with my annotation itself,hence page was not loading after clicking login button.Also after making changes to html/servlet file and refreshing and cleaning project, i still used to get 404 error, but then realized problem was with browser caching the page.So cleared cache and voila!
And thanks everyone for all the help

URL rewriting in Servlet/JSP

I know that response.sendRedirect() destroys the request/response object and new request is sent to the resource. So how come request.getParameter("") fetches me the value if the earlier request/response object has already been destroyed.
NewFile.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action ="MyServlet">
<label>Username</label>
<input type="text" name="textbox1"/><br>
<label>Password</label><input type="password" name="textbox2"/>
<input type="submit"/>
</form>
</body>
</html>
Servlet
/**
* Servlet implementation class MyServlet
*/
#WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("textbox1");
String password = request.getParameter("textbox2");
if (user.equals("abc")&&password.equals("123"))
{
response.sendRedirect("NewFile.jsp?name="+user);
}
}
}
Newfile.jsp
<%= "hi there"+request.getParameter("name") %>
I repeated here the comment so you can mark your question as solved by this answer :D
If you are talking about your jsp getting parameter "name"... it's simply because you have put the request directly in the url (NewFile.jsp?name=xuser). If not, I didn't understand your question, please try to be clearer
It is because at very first request, you are getting the parameter, after that you are sending redirect response, if you will do same thing on redirected page or servlet, you will not able to get any thing. In your case, you are sending parameter name with value, so you will be able to get it.
Go to your "NewFile.jsp" page, in that page <%=request.getParameter("name")>.
It will simply get the value you passed in URL("NewFile.jsp?name="+user).

JSP and servlet does not respond to forwarding

I'm having some problems with forwarding and where the JSP file refuses to forward even though I'm forwarding : I start from here :
index.html :
<!DOCTYPE html>
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form action="loginPage">
Username: <input type="text" name="username"><br>
Password : <input type="text" name="password"><br>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
with the screen :
Then I move to that JSP file - adminPage.jsp:
<!DOCTYPE html>
<html>
<head><title>System Administrator Page</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<h1>Hello ${name.firstName} ${name.lastName} , You've logged in successfully!</h1>
<h1>
Please choose one of the following options
</h1>
<fieldset>
<legend>Add a new manager to the bank system</legend>
<form action="adminAdds1">
Press here to continue
</form>
</fieldset>
<fieldset>
<legend>Add a new employee to the bank system</legend>
<form action="adminAdds2">
Press here to continue
</form>
</fieldset>
</body></html>
with that screen :
but when I click either one of the two options , and move to adminAddNewEmployee.jsp of adminAddNewManager.jsp , I get this , over and over again , even though both files are located at the same folder of adminPage.jsp:
HTTP Status 404 -
--------------------------------------------------------------------------------
type Status report
message
description The requested resource () is not available.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.28
where the project tree is :
How can I fix this ? I understand that WEB-INF requires some forwarding , but where do I put the forwarding ? in the JSP ?
but note that I use href and it still failing .
Regards
EDIT:
in adminPage.jsp is added that :
<fieldset>
<legend>Add a new manager to the bank system</legend>
<form action="adminAdds1">
Press here to continue
</form>
</fieldset>
and created a new servlet Admin1.java :
package servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/adminAdds1")
public class Admin1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
request.getRequestDispatcher("/WEB-INF/results/adminPage.jsp").forward(request, response);
}
}
but when I run the all thing again I get :
HTTP Status 404 - /WebBank/src/servlets/Admin1
--------------------------------------------------------------------------------
type Status report
message /WebBank/src/servlets/Admin1
description The requested resource (/WebBank/src/servlets/Admin1) is not available.
--------------------------------------------------------------------------------
Apache Tomcat/7.0.28
Files inside WEB-INF are not directly accessible from client.
One way would be change
<a href="SomeServletmapping">
Inside SomeServlet get method do
request.getDispatacher(yourJSP).forward();
Second way:
move those JSPs outside the WEB-INF folder.
Take a look here
Press here to continue
According to specification nothing is accessible (directly) inside WEB-INF folder.
It can be possible to do it using
<%# include file="WEB-INF/path/to/expected.jsp" %>
Or dispatching to JSP using request dispather or using framework like Spring!

Categories