how to send parameter from servlet to jsp page - java

I want to pass parameter from servlet to jsp page . That is why , in servlet , I have written the following code :
request.setAttribute("errorMessage", dbMessage);
response.sendRedirect(redirectURL + "index.jsp");
In index.jsp I have written the following code :
<%
String error_msg = (String)request.getAttribute("errorMessage");
out.println(error_msg);
if (error_msg != null) {%>
<div class="alert alert-danger">
<%=error_msg%>
</div>
<% } %>
But I do not have the value of errorMessage in index.jsp page. What is the reason ? Please help me . Point to be noted : error Message is not null .

You can not pass hidden params while using request.sendRedirect. You have following options to pass parameters to the JSP from servlet.
Set request params in the url itself as
response.sendRedirect(redirectURL + "index.jsp?errorMessage=", dbMessage);
and then in JSP change code to
String errorMsg = request.getParameter("errorMessage")
Error message will be visible in URL on the browser side.
Use server-side forwarding as mentioned in the answer by Jaydip as shown below.
request.setAttribute("errorMessage", dbMessage);
RequestDispatcher dispatcher = serveltContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
Using session
request.getSession().setAttribute("errorMessage", dbMessage);
on the JSP, change code to
String error_msg=(String)request.getSession().getAttribute("errorMessage");
Using cookie
Cookie errorCookie = new Cookie("errorMessage", dbMessage);
errorCookie.setPath(request.getContextPath());
response.addCookie(errorCookie);
On browser side you can read cookie via js or from the request itself
String error_msg = null;
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("errorMessage".equals(cookie.getName())) {
error_msg = cookie.getValue();
}
}

You should write like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
**request.getSession().setAttribute("mango", "Mango is a sweet Fruit");**
response.sendRedirect(request.getContextPath() + "/index.jsp");
}

The problem here is you are using sendRedirect. Understand that sendRedirect will initiate new request to different url. Try to using forward or include to maintain the request parameter.

Related

How can I dispatch from Registration Servlet to Login Servlet POST method

how to redirect the request from registration servlet to login servlet POST method . i wanna do this because the user after registration, i redirect him to the homepage as already logged.
here is my Registration servlet
-------
response.setContentType("text/html");
String nome=request.getParameter("Nome");
String cognome=request.getParameter("Cognome");
String email=request.getParameter("Email");
String password=request.getParameter("Password");
String documento=request.getParameter("Documento");
String num_documento=request.getParameter("NumeroDocumento");
Utente u = new Utente(email,password,nome,cognome,documento,num_documento);
System.out.println("qui");
RequestDispatcher d;
UtenteDAO ud = new UtenteDAO();
if(ud.doSave(u)){
d = request.getRequestDispatcher();
d.forward(request, response);
}else{
request.setAttribute("err", true);
d=request.getRequestDispatcher("Registrazione.jsp");
d.forward(request, response);
}
}
sorry for my English :(
You can set the response of your servlet to status code 301. Something like below.
response.sendRedirect("https://www.google.com");
This will instruct the browser to go to www.google.com, you can replace this with your URL.

How to redirect/forward request to another jsp page in servlet called by $.ajax() function

I am using $.ajax() function to call servlet in my application and i am forwarding request to anothor jsp page and setting request attribute.....I just want to know is it good approach to forward request and setting request parameter in ajax based servelt?
Here is my sample code.....
var id= $("#id").val();
$("#add-btn").click(function(e) {
e.preventDefault();
var dataString ='action=insert'+'&id='+id
console.log(dataString);
$.ajax({
type: "POST",
url: "RecordHandler",
data: dataString,
success: function(data){
console.log('Add');
$('body').html(data);
$('body').prepend('<div style="width:100%;text-align:center;"><h3 style="color:green" >Record Added Succesfully</h3></div>')
}
});
});
and here is my servlet code......
private static String UserRecord = "/list.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String redirect = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("insert")) {
String id= request.getParameter("id");
int uid = Integer.parseInt(id);
RecordBean record = new RecordBean();
record.setId(uid);
dao.addRecord(record);
redirect = UserRecord;
request.setAttribute("records", dao.getAllRecords()); //Is it good approach to set request attribute in ajax based servlet?
System.out.println("Record Added Successfully");
RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
view.forward(request, response);
}
How to do it using ajax without refreshing page......
even i use window.location.herf="list.jsp" in ajax success method it is refreshing page
When you call a servlet via AJAX, you stay on the same page by definition, regardless of the headers sent by the server.
If you want to change the page, you must do it with javascript, in the success handler function for the $.ajax(..) call.
You can read the Location response header and set the window.location.href to that value. See here for other options.

why don't i see a new jsp page when i click the fire button in the applet?

I am trying to communicate with a servlet and jsp via an applet. When the button in the applet is clicked request is fired to the servlet and then i try to forward from that servlet to a jsp page. Though the request is made successfully to the servlet's doGet method,i neither see a servlet page in the browser nor a jsp page. why is that ? what am i missing ?
applet button click code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("pressed the button !");
try {
URLConnection connection = new URL("http://localhost:8084/poll/servlet_1").openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
InputStream response = connection.getInputStream();
connection.connect();
}catch(Exception exc) {
exc.printStackTrace();
}
}
servlet code :
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
System.out.println("---inside the doGet method of servlet----");
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
writer.println("You just landed on a servlet from an applet !");
RequestDispatcher rd = request.getRequestDispatcher("jsp_1.jsp");
rd.forward(request, response);
}
What i see in the server log is the message : ---inside the doGet method of servlet----
when i fire the event the first statement inside the doGet method gets printed but the request is not forwarded to the jsp page. why is that ?
If I am getting you correctly you need to Redirect from an applet to servlet and then forward JSP page?
after your servlet response
.....redirect to jsp from applet.
AppletContext appletContext = getAppletContext();
appletContext.showDocument(new URL(getDocumentBase(), "yourJsp.jsp"));

I can't retrieve responseText from servlet using AJAX

I have a servlet file called NewServlet.java. This servlet is called by my AJAX script to retrieve the response.
I have verified the servlet by testing it in a browser.
But when I call it from my AJAX script it gives me a blank responseText and an error that says
XMLHttpRequest cannot load
http://localhost:8084/WebApplication1/NewServlet.
Origin null is not allowed by
Access-Control-Allow-Origin
NewServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<option value='1'>one</option>");
out.println("<option value='2'>two</option>");
out.println("<option value='3'>three</option>");
out.println("<option value='4'>four</option>");
out.println("<option value='5'>five</option>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
test.html
<html>
<head>
<script language = "javascript">
var xmlDoc = 0;
var xhttp = 0;
function reciveData()
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = redirectUser;
xhttp.open("GET","http://localhost:8084/WebApplication1/NewServlet",true);
xhttp.send();
}
function redirectUser()
{
if (xhttp.readyState == 4)
{
log = 0;
xmlDoc = xhttp.responseText;
alert(xmlDoc);
}
}
</script>
</head>
<body onload="reciveData()">
</body>
</html>
Can some one point me in a right direction ?
Thanks.
That's on the browser side...the security model only allows AJAX requests to the same host/port that you fetched the page from. Make sure that you've fetched your page via the server (e.g. http://localhost:8084/test.html) and not loaded it via the filesystem. Then you should be good to go...or at least continue debugging. ;)
This can indeed happen when the servlet runs on a different port than where the ajax request is coming from. This violates the Same Origin Policy for ajax requests and thus the browser won't process the ajax response. Apart from hosting the servlet behind the same port, other solutions are to return JSONP instead or to let the servlet set the HTTP Access-Control headers.
response.setHeader("Access-Control-Allow-Origin", "*");
You however need to keep in mind that this way your servlet is by Ajax accessible to everyone. If the servlet returns sensitive information, then this is a security hole. But if it does not and it is supposed to be a public webservice, then it's safe.
in my experience, if you want to load data with ajax, send your request to a jsp file, and get your response text from that jsp file. it is a lot easier to handel. see this example if you like
EDITED<<
==========================
ajax_load.js :
var xmlhttp;
function loadAdminRight(category){
xmlhttp = GetXmlHttpObject();
if (xmlhttp == null) {
alert("Your browser does not support Ajax HTTP");
return;
}
var url = "load.jsp";
url = url + "?category="+category;
xmlhttp.onreadystatechange = getLoad;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function getLoad(){
if (xmlhttp.readyState == 4) {
document.getElementById("right_content").innerHTML = xmlhttp.responseText;
//or what you want to do
}
}
===========================
load.jsp :
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String l_category = request.getParameter("category");
if(l_category.equals("article")){
out.write("You have choosen article category");
out.write("<br/>");
}
}else if(l_category.equals("news")){
out.write("You have choosen article category");
out.write("<br/>");
}
%>
and to make the ajax going you just need to call the .js function from where you want, for example on a button click action :
onClick="loadAdminRight("article");"
and you can import your java classes in a jsp file with adding <%page import="" %> to the top of your jsp page for example :
<%#page import="com.omicc.classes.Article"%>
write your own load.jsp file which handles the response, then use out.write in your jsp file to write the response text.
i wish it helps you
This will solve your issue..
// Ajax response
res.setContentType("text/javascript");
res.setCharacterEncoding("UTF-8");
res.setHeader("Cache-Control", "no-cache");
PrintWriter out = res.getWriter();
out.print("GRANTED");
out.close();

How to pass a value of a variable from a java class to the jsp page

I have 2 files named Admin.java and index.jsp.
In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.
The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.
The code of Admin.java is:
public Admin()
{
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
if (action.equals("login"))
{
String userName="";
String password="";
userName = request.getParameter("username");
password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
return;
}
The code of index.jsp is
function login(user, pass)
{
$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){
}
within the
function(response)
{
......
}
I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.
From your code,
request.setAttribute("rest", res);
You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by
response.getWriter().write(res);
This way it'll end up in the response body and be available as variable response in your JS function.
See also:
How to update current page by Servlet/Ajax?
Seems like you're doing AJAX, so I'd say your response would need to be encoded in an AJAX-compatible way (JSON, XML, ...).
If you do AJAX-encoding, your function might look like this:
function(response)
{
var toplevel = response.<your_top_level_element>;
}
Edit:
We're using JSON Simple for JSON encoding.
Our Java backend then looks like this (simplified version without error checking):
public String execute()
{
JSONObject jsonResult = new JSONObject();
jsonResult.put( "result", "ok");
return jsonResult.toJSONString();
}
And in the Javascript function:
function(response)
{
var result = response.result; //now yields "ok"
}
If this is an ajax request, you can forward the request into another jsp page rather than return. With this
getServletContext().getRequestDispatcher("/ajax.jsp").forward(request, response);
create the jsp page(ajax.jsp) on your webcontent and add this sample code.
<p>${rest}</p>
<!-- Note: You can actually design your html here.
You can also format this as an xml file and let your js do the work.
//-->
Another way is replace your System.out.println with this
PrintWriter out = response.getWriter();
out.print("The value of res been passed is "+res);
but I guess this is a bad practice. See example here.

Categories