Output of ServletContext in java is not getting as Expected? - java

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);
}

Related

Servlet request.getParameter() returns null [duplicate]

This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 2 years ago.
I have read all the questions about this here, but I still do not have any progress. I want to pass the value from the input field to my servlet, but the servlet's request.getParameter returns null, instead of what is inputted. Here is my HTML:
<form method="post" action="MyHttpServletDemo" id="myForm">
<input type="text" id="input" name="input1" placeholder=" Input coordinates...">
</form>
<button type="button" id="vnes" onclick="Vnes()">Search</button>
Here is my .xml:
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
And the Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("input1");
out.println("<h1>" + value + "</h1>");
}
I tried this:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("input1");
out.println("<h1>" + value + "</h1>");
}
HTML:
<form method="post" action="/welcome" id="myForm">
<input type="text" id="input" name="input1" placeholder=" Input coordinates...">
<button type="button" id="vnes" onclick="Vnes()">Search</button>
</form>
And still does not work.
It worked! Here's the solution:
HTML:
<form method="get" action="welcome" id="myForm">
<input type="text" id="pole" name="pole1" placeholder=" Input coordinates...">
<button type="submit" id="vnes">Search</button>
</form>
.xml file:
<servlet>
<servlet-name>MyHttpServletDemo</servlet-name>
<servlet-class>MyServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServletDemo</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String value = (String) request.getParameter("pole1");
out.println("<h1>" + value + "</h1>");
}

Don't work servlet. Issue with servlet mapping in web.xml

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 :)

doGet() cannot get any data from model

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);
}

servlet returning blank page

i m trying to create a registration page in servlet..using tomcat 7 with eclipse, it returning blank page, i have tried available steps but no go.. please help....
here is JSP page
<form method="post" action="mbregistrationservlet">
First Name: <input type=text name=firstfame><br>
Last Name: <input type=text name=lastname></br>
Gender: <input type="radio" name="gender" Value="Male" checked>Male
<input type="radio" name="Gender" Value="Female">Female</br>
E-mail: <input type="email" name="email"><br>
Password:<input type="password" name="password"><br>
Security Question<select name="securityquestion">
<option value="Name of your first pet">Name of your first pet</option>
<option value="Name of your first byke">Name of your first byke</option>
<option value="Name of your first car">Name of your first car</option>
<option value="Name of your first school">Name of your first school</option>
<option value="Name of your first GF/BF">Name of your first GF/BF</option>
</select><br>
Answer: <input type="text" name="answer"><br>
Telephone:<input type="text" name="telephone"><br>
Address:<input type="text" name="address"><br>
City:<input type="text" name="city"><br>
State:<input type="text" name="state"><br>
Country:<input type="text" name="country"><br>
<input type="submit" value="suuubmit" name="Submit">
</form>
Servlet page
public class mbregistrationservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static boolean register(String firstname, String lastname, String gender,String email, String password, String securityquestion, String answer, String telephone, String address, String city, String state, String country) throws IOException
{
HttpServletResponse response = null;
//response.setContentType("text/html");
PrintWriter out = response.getWriter();
boolean x =false;
try{
/*dbconn obj=new dbconn();*/
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","******","*******");
PreparedStatement ps = con.prepareStatement("insert into mbregistration values(?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,firstname);
ps.setString(2,lastname);
ps.setString(3,gender);
ps.setString(4, email);
ps.setString(5, password);
ps.setString(6, securityquestion);
ps.setString(7, answer);
ps.setString(8, telephone);
ps.setString(9, address);
ps.setString(10,city);
ps.setString(11,state);
ps.setString(12,country);
int i = ps.executeUpdate();
if (i>0){
x=true;
}
out.print("registered succcessfully");
//out.close();
}
catch(Exception e)
{
out.print("error");
//out.close();
}
return x;
}
XML page
<display-name>MobileWorld</display-name>
<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>
</welcome-file-list>
<servlet>
<description></description>
<display-name>mbloginservlet</display-name>
<servlet-name>mbloginservlet</servlet-name>
<servlet-class>mbworld.mbloginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mbloginservlet</servlet-name>
<url-pattern>/mbloginservlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Validate</display-name>
<servlet-name>Validate</servlet-name>
<servlet-class>mbworld.Validate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Validate</servlet-name>
<url-pattern>/Validate</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>success</display-name>
<servlet-name>success</servlet-name>
<servlet-class>mbworld.success</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>success</servlet-name>
<url-pattern>/success</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>mbregistrationservlet</display-name>
<servlet-name>mbregistrationservlet</servlet-name>
<servlet-class>mbworld.mbregistrationservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mbregistrationservlet</servlet-name>
<url-pattern>/mbregistrationservlet</url-pattern>
</servlet-mapping>
please let me know if i m doing something wrong.......
First of all you have to write your code in doPost method and the second thing is that if you are not using rd.forward(request,response) after RequestDispatcher rd=request.getRequestDispatcher("Name of page you want to redirect"); it will be a blank page after you click submit button.
so it should be like:
RequestDispatcher rd=request.getRequestDispatcher("Welcome");
rd.forward(request,response);
Change your method name as doPost instead of register (without static keyword) and from there using http servlet request access form fields using getParameter api. so it looks like:
public class mbregistrationservlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstfame");
//and so on
}
I don't see a doPost() method in the servlet, which is actually going to be called by the service method when you submit your form.
structure of doPost() method
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code
}
Corrections
You are not going to get input fields via parameters as you are expecting with you register method
public static boolean register(...)
morever this is illegal.
In,Order to get your input field parameters user Enumeration params = request.getParameterNames() which will return an Enumeration of all the parameters and via request.getParameterValue(params.nextElement()) you can access value corresponding to the input field specified by params.nextElement().
EXAMPLE.

HTTP method GET is not supported by this URL

<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.

Categories