Sessions showing null error - java

I have a JSP page, say xyz.jsp in which I've set a session
request.getSession().setAttribute("path", loc);
and in a.java I've used this session successfully and sent response back to jsp page,
String fpath = request.getSession().getAttribute("path").toString();
But, when I to use the same session value in b.java I am getting null pointer exception.
my.jsp->on button click->a.java->get session1->send response to my.jsp->my.jsp reloads->b.java trying to use session1->NullPointerExceptionError
I've tried,
Using different session variables
session.setAttribute("session1", loc);
session.setAttribute("session2", loc);
Creating a new session variable in a.java and access the same in b.java
Still with the same error.
my.jsp looks like,
String loc = "/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/" + ip +"/" +timeStamp;
session.setAttribute("path", loc);
a.java looks like
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String fpath = session.getAttribute("path").toString();
if(!new File(fpath).exists())
{
File uploadedFile = new File(fpath, fileName);
item.write(uploadedFile);
two_file = "Right file " +fileName;
request.setAttribute("file2", two_file);
String f2 = "<span class='blue'>" +"Uploaded file " +fileName+ " at " +uploadedFile.getAbsolutePath()+ "<br>" + "</span>";
request.setAttribute("f2stat", f2);
}
RequestDispatcher rd = request.getRequestDispatcher("geco.jsp");
rd.forward(request, response);
b.java looks like
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
String b = session.getAttribute("path").toString();
File file = new File(b);
if(!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("hi");
bw.close();
}

This is just to help you with the problem. What i mean to say is using the scriptlets in jsp, the naming conventions, using two servlets in this scenario are all not recommended..
code snippets
web.xml
<servlet>
<servlet-name>myservleta</servlet-name>
<servlet-class>com.examples.example.MyServletA</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>myservletb</servlet-name>
<servlet-class>com.examples.example.MyServletB</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservleta</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>myservletb</servlet-name>
<url-pattern>*.go</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
index.jsp
<body>
<%
session.setAttribute("location", "tvm");
%>
<form action="gotoajava.do" method="post">
<input type="Submit" />
</form>
</body>
page2.jsp
<body>
<form action="gotobjava.go" method="get">
<input type="Submit" />
</form>
</body>
MyServletA.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String loc = request.getSession().getAttribute("location").toString();
System.out.println("location in ServletA from session is " + loc);
RequestDispatcher rd = request.getRequestDispatcher("geco.jsp");
rd.forward(request, response);
}
MyServletB.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String loc = session.getAttribute("location").toString();
System.out.println("location in ServletB from session is " + loc);
}
Console log:
Mar 20, 2014 9:28:33 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 343 ms
location in ServletA from session is tvm
location in ServletB from session is tvm
edit: The jsp that performs 'gotobjava.go' action is renamed to page2.jsp as per OP's edit request

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

Output of ServletContext in java is not getting as Expected?

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

sending data from java servlet to jsp

I am trying to send a string from a Java servlet to JSP but I always get a null in the string
Test.java servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String s = "HelloWolrd";
System.out.println(s);
response.setContentType("text/jsp");
request.setAttribute("s", s);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test.jsp");
dispatcher.forward(request,response);
}
test.jsp
<body><%= request.getAttribute("s")%> </body>
web.xml has servlet class mapped to apis. Test and url-pattern as /test.
The test.jsp file is placed outside the WEB-INF as per your project structure. Validate it again.
Servlet:
public class Test extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = "HelloWolrd";
System.out.println(s);
response.setContentType("text/jsp");
request.setAttribute("s", s);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/test.jsp"); // CHANGE IT HERE
dispatcher.forward(request, response);
}
}
web.xml:
<servlet>
<servlet-name>XYZ/servlet-name>
<servlet-class>apis.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>XYZ</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
Have a look at my another post How does a servlets filter identify next destination is another filter or a servlet/jsp? for detailed description on Servlet Matching Procedure used for url-pattern.
Note: Always try to avoid Scriplet instead use JavaServer Pages Standard Tag Library and Expression Language.
Also as per your eclipse directory structure you have your JSP under WebContent folder. So you need to do
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/traders/test.jsp");
Few other thing you can try
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/traders/test.jsp?s=s");
and then in your JSP you can do
<%= request.getAttribute("s")%>
OR
you can use Session
HttpSession session = request.getSession(true);
session.setAttribute("s", "s");
and do
<%= session.getAttribute( "s" ) %>

browser shows 404 error [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I am new to servlet and making my first servlet using eclipse.I have made Index.html, Login.java and WelcomeServlet.java. But whenever I am trying to access the using
localhost:8080/ServletExample/
It shows 404 error.Here are the codes..
Index.html
<form action="Login" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
public class Login extends HttpServlet {
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("userPass");
if(p.equals("servlet")) {
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
} else {
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
package java.io;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
package java.io;
why u put this line in WelcomeServlet.java.
You're mapping to 'WelcomeServlet' not 'ServletExample'.
Try going to localhost:8080/WelcomeServlet
EDIT: There shouldn't be a trailing slash, sorry!
Make sure ur projrct name is ServletExample.
localhost:8080/ServletExample/index.html

Categories