<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.
Related
The following is my servlet program for role based authentication
the below is the Filter
#WebFilter("/loginFilter")
public class LoginCheckFilter implements Filter {
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
HttpSession session = request.getSession();
Boolean adminURI = request.getRequestURI().endsWith("login/admin/adminAccount");
Boolean userURI = request.getRequestURI().endsWith("login/user/userAccount");
System.out.println(session.getAttribute("userName"));
if(request.getRequestURI().endsWith("/login")){
chain.doFilter(req,resp);
} else if(session.getAttribute("userName") != null && session.getAttribute("userRole").equals("user") && adminURI){
request.getRequestDispatcher("index.jsp").forward(req,resp);
} else if(session.getAttribute("userName") == null){
request.getRequestDispatcher("index.jsp").forward(req,resp);
} else
chain.doFilter(req,resp);
}
public void destroy() {}
}
I haved mapped this filter to a pattern of /* , and the login servlet is
#WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName, password;
userName = request.getParameter("userName");
password = request.getParameter("password");
LoginService loginService = new LoginService();
DataAccessObject dataAccessObject = new DataAccessObject();
dataAccessObject.setUserName(userName);
dataAccessObject.setPassword(password);
String result = loginService.authenticate(dataAccessObject);
if(result.equals("admin")){
HttpSession session = request.getSession();
session.setAttribute("userName", userName);
session.setAttribute("userRole", result);
response.sendRedirect("admin/adminAccount");
return;
}
else if(result.equals("user")){
HttpSession session = request.getSession();
session.setAttribute("userName", userName);
session.setAttribute("userRole", result);
response.sendRedirect("user/userAccount");
return;
}
}
}
when I enter the url localhost:8080/login I get a login screen, but when i enter the id and password and press submit, the request is send to localhost:8080/login/login , I am new to servlet and dont understand why it is happening.
my index.jsp has login in its action. When I map my servlet to #WebServlet("/login/login"), then only it seems to run. What mistake have I done?
my understanding is that, after the browser goes to the servlet the request should be made to the localhost:8080/login/ and then according to the condition, it should transfer the page to localhost:8080/login/admin/adminAccount or /user/userAccount
, my index.jsp is inside a login folder in the web directory.
the below is my jsp code
<form action="login" method="post">
<table align="center">
<tr>
<td>Username</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"/></td>
</tr>
</table>
</form>
Your jsp is rendered in case someone enters /login, but than your action="login" will send you (since it is relatively) to [current location="/login"]/login.
Try to change the action to action="/login". That should solve the problem.
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 :)
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 am trying to read certain values from web.xml file and I am getting the error in the image at the bottom of this question.
Config.html
<form action="go" method="get">
Enter name:<input type="text" name="pname"><br>
Enter Age:<input type="text" name="page"><br>
<input type="submit" value="submit">
</form>
UseServletContext.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter pw=response.getWriter();
//Read form data through Form Page:
String name=request.getParameter("pname");
String age=request.getParameter("page");
//Approach1
ServletConfig cg=getServletConfig();
ServletContext sc=cg.getServletContext();
String db2url=sc.getInitParameter("db2url");
String db2user=sc.getInitParameter("db2user");
String sql="insert into jalajclients(name,age) values(?,?)";
//Convert age to numeric values.
int age1=Integer.parseInt(age.trim());
//Store these Values to the DataBAse.
try {
Class.forName("com.ibm.db2.jcc.Db2Driver");
Connection con=DriverManager.getConnection(db2url,db2user,"786");
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,name);
ps.setInt(2, age1);
int i=ps.executeUpdate();
pw.println(i);
} catch(Exception e) {
e.printStackTrace();
}
}
I am getting the following error:
web.xml
<servlet>
<description></description>
<display-name>UseServletContext</display-name>
<servlet-name>UseServletContext</servlet-name>
<servlet-class>UseServletContext</servlet-class>
</servlet>
<context-param>
<param-name>db2url</param-name>
<param-value>jdbc:db2://localhost:50000/mydb1235</param-value>
</context-param>
<context-param>
<param-name>db2user</param-name>
<param-value>piyush</param-value>
</context-param>
<servlet-name>UseServletContext</servlet-name>
<url-pattern>/go1</url-pattern>
</servlet-mapping>
Can anyone guide me what I am doing wrong?
Did you override the init method in your Servlet?
If yes, then don't forget to call super.init(config);in it like below
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
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.