I have home page and when I click on reference Servlet don't work and I get error 404. I think issue in web.xml mapping, but a don't understand where. Please help me correct this issue. Thank you.
My web.xml
<!--Homepage.-->
<servlet>
<servlet-name>HomePageServlet</servlet-name>
<servlet-class>ru.pravvich.servlets.HomePageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomePageServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--Add user in database.-->
<servlet>
<servlet-name>AddUserServlet</servlet-name>
<servlet-class>ru.pravvich.servlets.AddUserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddUserServlet</servlet-name>
<url-pattern>/addition</url-pattern>
</servlet-mapping>
My jsp homepage:
<body>
<ul>
<li>addition</li>
</ul>
</body>
And servlet with doGet method for it:
public class HomePageServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF8");
req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req,resp);
}
}
And by http://localhost:8080/items/ I get my home page.
But, when I click on reference from index.jsp, return: HTTP Status [404] – [Not Found]
My addition.jsp same lie in /WEB-INF/views/addition.jsp
My Servlet for work with addition.jsp :
public class AddUserServlet extends HttpServlet {
private DBJoint db;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
db = (DBJoint) getServletContext().getAttribute("db");
db.getDBExecutor().addUser(
new User(req.getParameter("name"),
req.getParameter("login"),
req.getParameter("email")));
req.setAttribute("serverAnswer", "Add ok!");
req.getRequestDispatcher("/WEB-INF/views/answer.jsp").forward(req, resp);
}
}
And addition.jsp:
<body>
<form method="post" action="addition">
<input type="text" required placeholder="name" name="name"><br>
<input type="text" required placeholder="login" name="login"><br>
<input type="text" required placeholder="email" name="email"><br>
<input type="submit" value="add">
</form>
</body>
I would suggest to use try/catch and debugger mode.
And try to use like this your getRequestDispatcher
request.getRequestDispatcher("answer.jsp").forward(request, response);
or
req.getRequestDispatcher("~/WEB-INF/views/answer.jsp").forward(req, resp);
I think you need to get parameter for each of one, and than set. Try this;
public class AddUserServlet extends HttpServlet {
private DBJoint db;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
db = (DBJoint) getServletContext().getAttribute("db");
String Name = request.getParameter("name");
String Login= request.getParameter("login");
String Email= request.getParameter("email");
db.getDBExecutor().addUser(
new User(Name, Login, Email);
//And you need to 'serverAnswer' item in your 'answer.jsp' you know.
request.setAttribute("serverAnswer", "Add ok!");
request.getRequestDispatcher("answer.jsp").forward(req, resp);
}
}
And then you can use getAttribute like this in your answer.jsp,
<%String Answer= (String)request.getAttribute("serverAnswer"); %><%= Answer%>
Don't blame me, just i wanna help to you, i hope so it can be help to you, if you wanna you can look my trial project; https://github.com/anymaa/GNOHesap
Have a nice coding :)
Related
So this is the code i'm using to send the parameter "idemp" that contains the value ${masession.idemp}
<a href="<c:url value="/consultertickets">
<c:param name="idemp" value="${masession.idemp}"/>
</c:url>">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
when redirected to the servlet "/consultertickets" the browser URL shows:
http://localhost:4040/monprojet2/consultertickets?idemp=64
so the parameter is passed and working but the method used to obviously GET and not POST, which is the method i'm using in the servlet, here's the servlet's code.
#WebServlet(urlPatterns= {"/consultertickets"})
public class ConsulterTickets extends HttpServlet {
private String VUE = "/WEB-INF/ListeTickets.jsp";
#EJB
private TicketDao ticketDao;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CreationTicketForm ticketform = new CreationTicketForm(ticketDao);
List<Ticket> lticket = ticketform.recupererTickets(request);
boolean resultat;
if(lticket.isEmpty())
{
//resultat="Vous n'avez soumit aucun ticket";
resultat = false;
request.setAttribute("resultat", resultat);
this.getServletContext().getRequestDispatcher("/ListeTickets2.jsp").forward(request, response);
}else{
//String VUE = "/ListeTickets.jsp";
resultat=true;
request.setAttribute("resultat", resultat);
request.setAttribute("lticket", lticket);
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
}
}
}
is there any way to pass a parameter to a servlet through POST method, without going through the <form></form>
Solution 1:
Modifying doGet method
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
doPost(request, response);
}
Solution 2:
Remove the doGet() and change doPost() to service()
Edit1:
See, Hyperlinks(<a> tag) are meant to send GET request but not POST.
So, if you want to achieve sending POST request using Hyperlink there is no straight way. But, Javascript can be your help.
Using Javascript you can guide <a> to send POST request along with the help of <form>.
I just modified your code little bit. This should help you.
<a href="javascript:document.getElementById('form1').submit()">
<img src="<c:url value="/inc/liste.png"></c:url>" alt="consulter tickets" />
</a>
<form action="<c:url value="/consultertickets"/>" method="post" id="form1">
<input type="hidden" name="idemp" value="${masession.idemp}"/>
</form>
I have a simple servlet app. In the servlet class, doPost() and doGet() basically get the same data from model class, however, doGet() cannot get any data.
public class ClickerServlet extends HttpServlet {
ClickerModel clickerModel = new ClickerModel();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String servletPath = request.getServletPath();
if (servletPath.equals("/submit")) {
doPost(request, response);
} else if (servletPath.equals("/getResults")) {
doGet(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String answer = request.getParameter("answer");
clickerModel.addAnswer(answer);
request.setAttribute("recentAnswer", clickerModel.getRecentAnswer());
request.getRequestDispatcher("submit.jsp").forward(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ok" + clickerModel.getRecentAnswer());
request.setAttribute("clickerModel", clickerModel);
request.getRequestDispatcher("results.jsp").forward(request, response);
}
}
My ClickerModel class:
public class ClickerModel {
private String recentAnswer;
private HashMap<String, Integer> answers;
public ClickerModel() {
recentAnswer = "";
answers = new HashMap<>();
}
public void addAnswer(String answer) {
recentAnswer = answer;
if (answers.containsKey(answer)) {
answers.put(answer, answers.get(answer) + 1);
} else {
answers.put(answer, 1);
}
}
public void clearAnswers() {
answers = new HashMap<>();
}
public HashMap<String, Integer> getAnswers() {
return answers;
}
public String getRecentAnswer() {
return recentAnswer;
}
}
Anyone knows why I cannot get any data from model using doGet()? Thanks!
For more information:
doPost() is called from a form submission.
<form action="submit" method="post">
<input type="radio" name="answer" value="A"> A<br>
<input type="radio" name="answer" value="B"> B<br>
<input type="radio" name="answer" value="C"> C<br>
<input type="radio" name="answer" value="D"> D<br>
<br><input type="submit" value="submit">
</form>
doGet() is called when I directly paste and hit the url (localhost:something/getResults) in the browser.
And my web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Results</servlet-name>
<servlet-class>Clicker.ClickerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Results</servlet-name>
<url-pattern>/getResults</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Submit</servlet-name>
<servlet-class>Clicker.ClickerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Submit</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
</web-app>
I my understanding, that you place the doGet() method in Results servlet, not same as Submit one.
Submit Servlet:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String answer = request.getParameter("answer");
clickerModel.addAnswer(answer);
request.setAttribute("recentAnswer", clickerModel.getRecentAnswer());
//request.getRequestDispatcher("submit.jsp").forward(request, response);
response.sendRedirect("getResults"); // <---After submit will go to this page.
}
Results Servlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ok" + clickerModel.getRecentAnswer());
request.setAttribute("clickerModel", clickerModel);
request.getRequestDispatcher("results.jsp").forward(request, response);
}
<form method="post" action="RegisterServletPath">
Name:<input type="text" name="userName"><br>
Password:<input type="password" name="password"><br>
Email Id:<input type="text" name="email"><br>
Language: <select name="language">
<option>Hindi</option>
<option>English</option>
<option>French</option>
</select> <br>
<input type="submit" value="Submit">
</form>
after submitting the form the following error occur
HTTP Status 405 - HTTP method GET is not supported by this URL
here is my java class. i have defined only post method and called post method in html form
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
String p = request.getParameter("password");
String e = request.getParameter("email");
String c = request.getParameter("language");
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con = DriverManager.getConnection("jdbc:ucanaccess://D:/eclipse/register.accdb","","");
PreparedStatement ps = con.prepareStatement("insert into USERDETAILS values(?,?,?,?)");
ps.setString(1, n);
ps.setString(2, p);
ps.setString(3, e);
ps.setString(4, c);
int i= ps.executeUpdate();
if (i > 0) {
out.print("You are successfully registered...");
}
}
//... not relevant here
}
}
web.xml
<display-name>SimpleServletProject</display-name>
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>org.venkatesh.Servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServletPath</url-pattern>
</servlet-mapping>
add the rest of the servlet code, I think you are either using doGet method and calling super.doGet from it, or not using doGet but unfortunatly the doGet method in HttpServlet is being called.
Here comes another problem! from where the doGet method in either case is being called?
If you can't find where, then try adding
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
this should solve the problem, if it doesn't then let me know if all my assumptions are wrong.
This is my Login.jsp page
<form name="login" action="ValidateServlet" method="post">
<input type="hidden" name="pagename" value="login"/>
<table>
<tr>
<td><b>USERNAME:</b><input type="text" name="txtUsername"/> </td>
</tr>
<tr>
<td><b>PASSWORD:</b><input type="password" name="txtPassword"/></td>
</tr>
<tr>
<td><input type="SUBMIT" value="SIGN IN"/></td>
</tr>
<tr>
<td>Forgot Password</td>
</tr>
<tr>
<td> Create New user </td>
</tr>
</table>
</form>`
And this is my SignupServlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/WebPages/Signup.jsp");
rd.forward(request, response);
}
}
and this is my web.xml
<servlet>
<servlet-name>SignupServlet</servlet-name>
<servlet-class>com.affiliate.servlet.SignupServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupServlet</servlet-name>
<url-pattern>/SignUp</url-pattern>
</servlet-mapping>
Login.jsp is in Webcontent/WEB-INF/WebPages/Login.jsp
and SignupServlet in JavaResources/src/com.affiliate.servlet/SignupServlet
but my Login is not redirecting to the SignupServlet. And i have doubt on my href and form action. Please help me in this regard.
Change
Create New user
↑
To
Create New user
And in anchor tag there is no post method available. You need to change the code in SignupServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException
{
RequestDispatcher rd = request.getRequestDispatcher("Signup.jsp");
rd.forward(request, response);
}
If you want post request using a tag then refer POST from an tag
replace
Forgot Password
Create New user
To
Forgot Password
Create New user
Remove "/" before Servlet URL Pattern
Change this code
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/WebPages/Signup.jsp");
rd.forward(request, response);
}
to
protected void doPost(HttpServletRequest request, HttpServletResponse response throws
ServletException, IOException {
getServletContext().getRequestDispatcher("WEB-INF/WebPages/Signup.jsp").forward(request, response);
}
In your login.jsp call SignUp servlet in following way
<td> Create New user </td>
and In SignUp servlet in your doGet method
RequestDispatcher rd = request.getRequestDispatcher("/WEB-INF/webpages/Signup.jsp");
rd.forward(request, response);
Because when you call a servlet from a link or href it the doGet method gets run. Hope this helps
I am trying to implement a simple login servlet but it's not working properly.
What I wanted to know is how to pass the parameters using a HTTP POST. It already works with HTTP GET but the username and password are visible from the URL. It would be better to hide them in a POST.
<form method="post" action="home" >
<input name="username" class="form-login" title="Username" value="" size="30" maxlength="2048" />
<input name="password" type="password" class="form-login" title="Password" value="" size="30" maxlength="2048" />
<input type="submit" value="Connect">
</form>
web.xml
<servlet>
<servlet-name>home</servlet-name>
<servlet-class>controller.HomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>home</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
Servlet:
public class HomeController extends HttpServlet {
private HttpSession session;
private UserBean userBean;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)
throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
}
The problem is that the userName and password strings are always empty, meaning that the parameters are never fetched from the POST. What am I doing wrong?
it should work, can you check by changing form method to get and trying, you should see parameters in url.
Please try this
In your doPost(..) method code only doGet(..) and put all your logic in doGet(..) and check if still it is giving blank values.
Let me know what is the output.
Example:-
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserBean user = new UserBean();
String userName = request.getParameter("username");
String password = request.getParameter("password");
user.setUsername(userName);
user.setPassword(password);
user = UserDAO.login(user);
dispatch(request, response, ApplicationRessource.getInstance().getHomePage());
}
this simple implementation should have worked ..but since its not, there maybe some code which is manipulating the request. The code you have posted is not sufficient to determine that.
Some pointers I can give are -
Check your web.xml to see if there is any filter/interceptor which is manipulating the request.
Which web/app server are you using? Have you checked the service(Http...) method implementation of HttpServlet. You can try placing a debug point in service(..) method to see if the request object here has the required request parameters. If it doesn't, then the problem exists either in some filter or your jsp itself.
What does dispatch(request, response, ApplicationRessource.getInstance().getHomePage()); do? I know the problem is before this line, but this is not a standard HttpServlet method, so I assume there's lot more custom code then whats been posted in the question above.