Getting null While Passing String from jsp to servlet - java

This is my Jsp File
<body>
<%
URL url = new
URL("http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet");
URLConnection conn =url.openConnection();
conn.setDoOutput(true);
BufferedWriter bw= new BufferedWriter( new OutputStreamWriter(
conn.getOutputStream() ) );
bw.write("username= Shanx");
out.flush();
out.close();
%>
</body>
This is my servlet class
#SuppressWarnings("serial")
public class JSPToServletToCloudServlet extends HttpServlet
{
private final static String _USERNAME = "username";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String username = request.getParameter(_USERNAME);
response.setContentType("text/html");
out.println("HelloWorld");
out.println("Hello " + username);
out.close();
}
This is the web.xml file
<servlet>
<servlet-name>JSPToServletToCloud</servlet-name>
<servlet-class>pack.exp.JSPToServletToCloudServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSPToServletToCloud</servlet-name>
<url-pattern>/jsptoservlettocloud</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
My Jsp File is in Dynamic Web Application and is sending a string to Servlet which is in Web application Project. I am running the dynamic web application project on apache tomcat server and after the server is started I am running my web application projewct as web application and checking on local host and getting null.
Help me out guys.

you will have to put username name wither in session, because you are not set the username in request.
put user name in session and on server Side write :-
HttpSession session = request.getSession();
String username = session.getAttribute("username")

Related

AJAX call is not reaching Servlet

I am trying to make a simple textbox which initiate a suggestive feedback based on the characters entered by the user. I am trying to fetch a JSON object from a Servlet but my AJAX call is somehow not reaching the servlet. On checking the status of AJAX request using this.status I am getting error code 404. Can anyone suggest me a solution:
[![enter image description here][1]][1]
Here's my servlet: FetchServ.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Connection con;
ResultSet rs;
java.sql.PreparedStatement pst;
String ch = request.getParameter("q");
String data;
ArrayList<String> list = new ArrayList();
response.setContentType("application/JSON");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("drivers registered");
con = DriverManager.getConnection(con_url, userID, password);
System.out.println("connection created");
pst = con.prepareStatement("SELECT * FROM candidates where FirstName LIKE ?");
pst.setString(1, ch + "%");
rs = pst.executeQuery();
System.out.println("query executed");
while(rs.next())
{
data = rs.getString("FirstName");
list.add(data);
}
String json = new Gson().toJson(list);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
response.getWriter().append("Served at: ").append(request.getContextPath());
} catch (SQLException | ClassNotFoundException e) {
System.err.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
the jsp code:
<script>
function suggest(str){
if(str.length == 0){
return;
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
document.getElementById("sugg").innerHTML = this.status;
if(this.readyState == 4 && this.status == 200){
//var res = JSON.parse(this.responseText);
document.getElementById("sugg").innerHTML = this.responseText;
}
};
try{
xmlhttp.open("GET", "com.test.java/FetchServ", true);
xmlhttp.send();
}catch(e)
{
alert("unable to connect ");
}
}
}
</script>
</head>
<body>
<form>
Search:<input type="text" onkeyup = "suggest(this.value)">
</form>
<p id = "sugg"></p>
</body>
</html>
and this is the result I am getting:
[![enter image description here][2]][2]
<display-name>ACtxtbox</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.test.java/FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/FetchServ</url-pattern>
</servlet-mapping>
</web-app>
your Web.xml entries are not proper, check the url which you are using in urlbar and the form submitted using xmlhttp.open("GET", "fetch", true); you can debugg the actual url passed as a request to the server by opening developer tools and navigating to the network tab it will look something like below.
also your <servlet-class>ACtxtbox/FetchServ</servlet-class> is not correct, it should be with package path like <servlet-class>sompackagepath.FetchServ</servlet-class>
EDIT
As per your images, I can see you have declare index.jsp which will be accesible by giving url: http://localhost:<port_number>/ACtxtbox/index.jsp.
Now you should note below points:
As you are calling servlet using ajax call where you have given
parameters as fetch in this line of code in you javascript
xmlhttp.open("GET", "fetch", true); hence it is now changing your
url to http://localhost:<port_number>/ACtxtbox/fetch
your web.xml entry should be like this
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.rishal.test.FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/fetch</url-pattern>
</servlet-mapping>
How come your url pattern is coming like
http://localhost:<port_number>/ACtxtbox/com.test.java/fetch ? is
it you have modified the web.xml entries. Please read the tutorials
and google about web application,jsp,servlets and ajax calls. you
should also note that you have to create your servlet class under
some package as i have given in the web.xml entry
com.rishal.test its package path and class is inside this package
path.
package com.rishal.test;
public class FetchServ extends HttpServlet {
----------------------
---------------------------
}

Allowing download servlet only for users who are logged in

I implemented a download servlet based on #wen's answer in Implementing a simple file download servlet
web.xml
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
DownloadServlet.java
public class DownloadServlet extends HttpServlet {
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String fileName = "";
String fileType = "";
How can I prevent the download servlet being activated by someone who is not logged in.
I have a ClientSession object that holds all the details of the login but I do not know how to access it from within the download servlet.
For instance, if I put a token in the request, then how could I validate this token against the ClientSession object.
You should get the client session from the HttpSession.
ClientSession clientSession = (ClientSession) request.getSession().getAttribute("client_session_info");
Naturally when you log in you must store your clientSession into the HttpSession like this:
session.setAttribute("client_session_info", clientSession);
I don't know how you log your user, but you should be able to access the http session object and store your data into it.

ajax call to java servlet results in 404 [duplicate]

This question already has answers here:
HTTP Status 404 - Servlet [ServletName] is not available
(4 answers)
Closed last year.
I'm trying to get a web page to send JSON data to a java servlet via a jQuery ajax POST.
I've already checked everything I could think of, but I still can't figure out why I keep getting a 404.
Even more confusing is that other calls to the same context path work correctly.
My web.xml
<web-app>
<servlet>
<servlet-name>Controller</servlet-name>
<servlet-class>com.vibridi.klyr.servlet.Controller</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>CustomerServlet</servlet-name>
<servlet-class>com.vibridi.klyr.servlet.CustomerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/klyr</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/home</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/klyr/customer/*</url-pattern>
</servlet-mapping>
My ajax call:
$.ajax({
url: "customer/save",
type: "POST",
data: JSON.stringify(o),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(obj) {
alert('Customer saved');
},
error: function(obj) {
alert('Error!');
}
});
My servlet:
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger("KLYR_LOGGER");
private CustomerManager manager;
public void init(ServletConfig sconfig) throws ServletException {
super.init(sconfig);
manager = new CustomerManager();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//stuff
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("application/json;charset=utf-8");
try {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
sb.append(line);
}
manager.saveCustomer(sb.toString());
} catch(Exception e) {
logger.log(Level.SEVERE, "Data processing failure: " + e.getMessage());
out.write(Convertor.createBaseJSON(JSONType.E).toString());
out.close();
}
out.write(Convertor.createBaseJSON(JSONType.S).toString());
out.close();
}}
}
I can see from the Chrome's debugger tools that the call is properly directed to http://localhost:8080/klyr/customer/save but it 404's, whereas http://localhost:8080/klyr does not.
Thanks a lot!
EDIT:
I've tried to switch the servlet mappings over, i.e. /klyr (the working one) on CustomerServlet and /customer/save on Controller, but nothing happens, in fact when I call /klyr from the browser bar instead of seeing the response from CustomerServlet.doGet I still see the welcome page as if Controller.doGet fired. It looks like tomcat isn't reloading the web.xml file even if I restart it. Any ideas?
This is obvious because your CustomerServlet does not bind to $.ajax({url: "customer/save", ... so it won't work, your should change the below code :
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/klyr/customer/*</url-pattern>
</servlet-mapping>
to something like:
<servlet-mapping>
<servlet-name>CustomerServlet</servlet-name>
<url-pattern>/customer/save</url-pattern>
</servlet-mapping>
in order to solve the problem ~
I've eventually found the culprit, gonna post it here as a reference for other people.
Both servlets mapped in my web.xml are loaded on startup.
The first servlet attempted to read a config file from an incorrect path inside its init() method, but couldn't find it and threw an exception. The Catalina startup routine exited before it could load the second servlet, hence the 404 error.

Redirecting servlet to another html page

I have two html pages - one for login and one that takes in a persons details. The login page is the first page and when the database is checked for the username and password, the user is allowed to enter their details. The SQL code works perfectly, it is just a problem with the mapping I am having. I am using the Tomcat server by the way. Could anybody help or spot what i am doing wrong?
This is my java code for logging in and entering details
public class Details extends HttpServlet {
private Connection con;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
//return writer
PrintWriter out = res.getWriter();
String username = req.getParameter("username");
String password = request.getParameter("password");
out.close();
try {
login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res.sendRedirect("/redirect.html");
String name = request.getParameter("name");
String address = request.getParameter("address");
String age = request.getParameter("age");
out.println("<HTML><HEAD><TITLE>Personnel Details</TITLE></HEAD><BODY>");
out.println(name + address + age);
out.println("</BODY></HTML>");
System.out.println("Finished Processing");
}
out.close();
}
In my web.xml file I have:
<web-app>
<servlet>
<servlet-name>Details</servlet-name>
<servlet-class>Details</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Details</servlet-name>
<url-pattern>/Details</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/redirect</url-pattern>
You may try this :
response.sendRedirect("redirect.html");
or
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "redirect.html");
Alternative way,
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/redirect.html").forward(request, response);
Redirect to HTML
RequestDispatcher ds = request.getRequestDispatcher("index.html");
ds.include(request, response);
you can use
1.response.sendRedirect("redirect.html") or
2.String path= "/redirect";
RequestDispatcher dispatcher =servletContext().getRequestDispatcher(path);
dispatcher.forward(request,response);

Internal Server Error In Web Application Project

I have a Dynamic application in which I have a JSP file which is sending a string to a Servlet which is in another project which is a Web application Project. I am using Tomcat server in JSP project and the server is starting just fine but when I am trying to run the web application on local host I am getting HTTP ERROR 500
Problem accessing /jsptoservlettocloud. Reason: INTERNAL_SERVER_ERROR
This is my JSP FILE
<body>
<%
String str= "Shanx";
URL u = new
URL("http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.setDoOutput(true);
ObjectOutputStream objOut = new ObjectOutputStream(huc.getOutputStream());
objOut.writeObject(str);
objOut.flush();
objOut.close();
%>
</body>
This is my Servlet Class
public class JSPToServletToCloudServlet extends HttpServlet
{
String str;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
try
{
str= (String) ois.readObject();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
finally
{
ois.close();
}
System.out.println("Servlet received : " + str);
}
}
This is my Web.xml file
<servlet>
<servlet-name>JSPToServletToCloud</servlet-name>
<servlet-class>pack.exp.JSPToServletToCloudServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSPToServletToCloud</servlet-name>
<url-pattern>/jsptoservlettocloud</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
In the url ServletToCloud is the name of the web application project and JSPToServletToCloudServlet is the name of the servlet. Is this url correct.
In your jsp you have http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet but you have /jsptoservlettocloud in your web.xml
Your mapping is wrong.

Categories