Not able to access request parameters in java servlets - java

I am using same dpPost method for two different form data. I am not able to access request parameters for second form.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if("schema".equals(session.getAttribute("which"))) {
second_html();
//call second page here
}
String btnClicked= request.getParameter("p2"); // This is getting null after submitting second_html()
if("edit".equals(session.getAttribute("which"))){
/* process second page here after Submit on the second page
I am trying to access request.getParameter() but value is null here for the fields in the second page */
second_html();
}
}
first_html() {
// have form and submit button
session.setAttribute("which","schema");
}
second_html() {
// have form and submit button
<input type='text' name='p2' id='p2' size='3' >
session.setAttribute("which","edit");
}
EDIT : My session getters are working fine. But the request.getParameter is not working.

You are accessing session variables, not your request parameters.
You can access them using
request.getParameter("which")

If I understand your question, you should be using ServletRequest.getParameter(String),
String v = request.getParameter("which");
if (v.equals("schema")) {
} else if (v.equals("edit")) {
}

Related

retrive session attribute and sort it into String [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 7 years ago.
I've been a PHP developer but recently need to work on some project using Google App Engine (Java). In PHP I can do something like this (in term of MVC model):
// controllers/accounts.php
$accounts = getAccounts();
include "../views/accounts.php";
// views/accounts.php
print_r($accounts);
I take a look at some demos of Google App Engine Java using Servlet and JSP. What they're doing is this:
// In AccountsServlet.java
public class AccountsServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("accountid");
// do something
// REDIRECT to an JSP page, manually passing QUERYSTRING along.
resp.sendRedirect("/namedcounter.jsp?name=" + req.getParameter("name"));
}
}
Basically in the Java case it's 2 different HTTP requests (the second one being automatically forced), right? So in JSP file I can't make use of the data calculated in the Servlet.
Is there some way I can do it similar to the PHP way?
You will need to set the data retrieved in the servlet in request scope so that the data is available in JSP
You will have following line in your servlets.
List<Account> accounts = getAccounts();
request.setAttribute("accountList",accounts);
Then in JSP you can access this data using the expression language like below
${accountList}
I would use request dispatches instead of the sendRedirect as follows
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(req, res);
If you can use RequestDispatcher then you can store these values in request or session object and get in other JSP.
Is there any specific purpose of using request.sendRedirect?. If not use RequestDispatcher.
See this link for more details.
public class AccountServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Account> accounts = getAccountListFromSomewhere();
String url="..."; //relative url for display jsp page
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
request.setAttribute("accountList", accounts );
rd.forward(request, response);
}
}
What you want to do is first define an object to represent the information from getAccounts() - something like AccountBean.
Then in your servlets doPost or doGet function, use the request info to populate your AccountBean object.
You can then store the AccountBean object either in the request, session, or servlet context by using the setAttribute method, and forward the request to the JSP page.
The AccountBean data in your jsp page is extracted using the and tags.
Here might be an example of your servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
// get data from request querystring
String accountId = req.getParameter("accountid");
// populate your object with it (you might want to check it's not null)
AccountBean accountBean = new AccountBean(accountId);
// store data in session
HttpSession session = req.getSession();
session.setAttribute("accountBean", accountBean);
// forward the request (not redirect)
RequestDispatcher dispatcher = req.getRequestDispatcher("account.jsp");
dispatcher.forward(req, resp);
}
Then your JSP page would have the following to display the account information:
<jsp:useBean id="accountBean" type="myBeans.AccountBean" />
Your account is <jsp:getProperty name="accountBean" property="status" />
Besides what's mentioned above about using expression lang, you can also pass attributes via request itself. In Servlet's doGet(), we write something like:
Account[] accounts = AccountManager.getAccountList();
request.setAttribute("accountList", accounts );
RequestDispatcher rd = req.getRequestDispatcher(nextJSPurl);
rd.forward(req, resp);
In JSP, we can retrieve the attribute from request:
<%
Account[] accounts= (Account[])request.getAttribute("accountList");
if (accounts.length>0) {
for (Account account: accounts) {
%>
<blockquote>account name: <%= account.getName() %></blockquote>
<%
}
}
%>
import javax.servlet.http.*;
public class AccountsServlet extends HttpServlet {
public void doGet (HttpServletRequest request, HttpServletResponse response) {
try {
// Set the attribute and Forward to hello.jsp
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
getServletConfig().getServletContext().getRequestDispatcher("/namedcounter.jsp?name=" + req.getParameter("name")).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
In the above code servlet will not create 2 different requests. It will forward, also will retain all data from original request.
request.setAttribute ("somename", "someValue"); // to save your temporary calculations.
This is my understanding of your question - you want to redirect or dispatch to a new JSP page along with the data calculated in Servlet, right? To do so you need to set request attributes before dispatching the request.
You can set attributes using HttpServletRequest object (req.setAttribute("attribute name", "attribute value")). Attribute value can be any Java object.
You can retrieve the value by req.getAttribute("attribute name"). You'll also need to type cast the object while user getAttribute() function.
You can set the data inside java beans and easily access that data onto jsp page when control goes to jsp. set the date in java beans using setters get access those data onto jsp page by including that bean into jsp.
<%#page contentType="text/html"%>
<jsp:useBean id="man" class="beans.Person"/>
<jsp:setProperty name="man" property="*"/>
First Name: <jsp:getProperty name="man" property="firstName"/>
like this you can access as many properties your bean class can have.

Use Java variable in HTML File

I made a LoginServlet with Java, that gets username and password from a database. Now I want to display the username on my website after logging in.
Servlet Code:
public class LoginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
Sql2o sql2o = DatabaseConnetcionProvider.getSql2oConnection();
User user = UserDAO.findBenutzerByUsername(username, sql2o);
if(user != null && user.getPassword().equals(password)){
UserListe.getInstance().add(user);
HttpSession session = req.getSession();
session.setAttribute("user", user);
resp.sendRedirect("/public/Home.html");
} else {
resp.sendRedirect("/public/Error.html");
}
}
}
Now I want to display the username on my Website.
I hope you can help me :)
In case of JSP you can use session implicit object
<%= ((User) session.getAttribute("user")).getUsername %>
You can retrieve value in your Home.html as below
<script type="text/javascript">
$(document).ready(function() {
userName = "{{user}}";
$("#yourFieldName").val(userName);
});
</script>
if the page is static html page,the static page can not handle the servlet page scope data,use jsp or other dynamic page to handle it,freemarker,velocity is suitable.
in jsp,you can use EL Express to show the data.the format is ${sessionScope.user}.
you should review the pageScope,requestScope,sessionScope,applicationScope concept.
sendRedirect method can cause data missing in pageScope,you should choose the right scope and the redirect or forward method,test it,please.
if the page is static page,please use AJAX to send request and handle the data,jQuery library is classic.

HTTP-Get request returns HTML-Code (Google AppEngine)

I am using an AppEngine Server to answer HTTP-Get requests of my app, but the request always returns the HTML of the index.html.
This is my doGet-Method:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String name = req.getParameter("name");
String score = req.getParameter("score");
if(score==null && name!=null){
resp.getWriter().println(name);
}
else if(name!=null && score!=null){
int p = Integer.parseInt(score);
addHighscore(name, p);
}
else{
resp.getWriter().println("error");
}
}
so if i type the url http://high-1212.appspot.com/?name=test into my browser, i want it to return the value of the name parameter, but it only returns the web page. So my app does not display the value of the parameter either, but the HTML-Code. For that reason I guess, it's because of the doGet-Method. But I don't understand, what's wrong.
By default the home page will be loaded when you visit the website. If you want to display the data you are sending, you have to do in the response page.

Java Servlet mapping when using a filter

I am quite new to using Servlets and JSP but I was wondering if someone can help me with the following question I have.
My problem arises from the fact that my Servlet is not being invoked, and I can't seem to figure out why.
Currently my steup is that I have a filter class named VisitShopFilter which checks to see if a client is logged in before they visit the shop, if they are it just forwards the request to the shop.jsp page,if they are not then it forwards them to the login.jsp page.
Here is the VisitShopFilter:
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpSession sess = ((HttpServletRequest)servletRequest).getSession();
if(sess.getAttribute("loggedIn") == null){
servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
return;
}
if(sess.getAttribute("cart") == null){
sess.setAttribute("cart",new ShoppingCart());
}
servletRequest.getRequestDispatcher("shop.jsp").forward(servletRequest,servletResponse);
}
The filter is mapped the the URL pattern /Shop
On the shop.jsp Page I have the following form :<form onaction="Shop" method = "POST">
<input type = "hidden" name = "itemname" value = "testItem"/>
<input type = "hidden" name = "itemprice" value = "10.00"/>
<input type = "hidden" name = "itemquantity" value = "1"/>
<button type="submit" class="btn btn-default btn-submit">Add to cart</button>
</form>
and I also have a Servlet named "Shop":
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("responding to post");
if(req.getSession().getAttribute("cart") == null || req.getSession().getAttribute("loggedIn") == null){
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("cart");
try{
cart.addItem(
req.getParameter("itemname"),
Double.valueOf(req.getParameter("itemprice")),
Integer.valueOf(req.getParameter("itemquantity"))
);
}catch (NumberFormatException e){
e.printStackTrace();
}
req.getSession().setAttribute("itemNamesInCart",cart.getItemNames());
req.getSession().setAttribute("itemPricesInCart",cart.getItemPrices());
req.getSession().setAttribute("itemQuantitiesInCart",cart.getItemQuantities());
req.getSession().setAttribute("totalItemsInCart",cart.getTotalCartSize());
req.getSession().setAttribute("totalPurchasePrice",cart.getTotal());
req.getRequestDispatcher("shop.jsp").forward(req, resp);
}
My problem is, "responding to post" isn't even printed out when clicking the submit button for the form. In my web.xml file I have tried mapping the servlet to /Shop, /shop.jsp and a bunch of other things including switching between GET and POST methods and I just can't seem to figure out what I am doing wrong.
Thanks for any help!
Currently my steup is that I have a filter class named VisitShopFilter which checks to see if a client is logged in before they visit the shop, if they are it just forwards the request to the shop.jsp page,if they are not then it forwards them to the login.jsp page.
Bad idea.
A filter should be an interceptor that provides common functionality for a set of resources (like how you check for session). You should have actual resources (Servlets/jsps) mapped to your end points. When a filter is done with it's work, it should invoke chain.doFilter(...) which lets the request processing reach its mapped end point.
A filter should change the course of request processing (by invoking another resource) only on exceptions (logical, business or technical). And as you have it in your code already, it does that by invoking the request dispatcher.
Thank you everybody for your fast replies.
I have taken into account what each one of you have said and managed to Improve from there. The two problems ended up being that I accidentally had onaction in the HTML file instead of action, and that I wasn't calling chain.doFilter(req,resp) method.

Use an Ajax response in JSP

I have a JSP page which has nothing but a normal HTML table with five rows and five columns.
Now I am making an Ajax call and get a response back. Now once I have the response back, I need the data to be filled in appropriate cells of the table.
So my question is;
Should I use JSON for building the response?
How do I handle the data back at the JSP level. That is, once I have the response from the server?
Just as additional information, I am using DWR which is nothing but calling a Java method (which builds the response) from inside JavaScript code.
Let's consider this Java class.
class Employee
{
int id;
String eName;
// Setters and getters
}
In JavaScript, the JSON object:
var employee = {
id : null,
name : null
};
This is the call to a Java method from a JavaScript function:
EmployeeUtil.getRow(employee,dwrData);
In getRow() of the EmployeeUtil class, the return type of method will be Employee:
Employee getRow();
So using the setters of Employee set the data. dwrData is the callback function.
function dwrData(data) {
employee=data;
}
The data returned, which is an Employee bean, will be in the callback function.
Just initialize this in the JavaScript JSON object.
Use a JSON object accordingly to populate the table.
EDIT :
You can use List getRow() instead of Employee getRow(), returning a list of rows as a List instead of a Bean.
Now the response contains list as data.
Refer to Populate rows using DWR.
Check these examples to populate data in table:
DWR + Dojo Demo
Dynamically Editing a Table
Should I use JSON for building the response?
No need to pass JSON in response. Instead return a Bean of a class as mentioned above.
A list can be passed as a response, also as mentioned above.
How do I handle the data back at the JSP level. That is, once I have the response from the server.
Check the explanation above and the examples of the given links to handle the response in JSP and display the response data in a table.
DWR basics on YouTube
JSP pages are dynamically generated servlets. Once a user hits a JSP page, they receive dynamically generated HTML that no longer talks to the JSP page that generated it unless they complete an action such as hitting "refresh" or submitting a form. Check out the JSP Page at Oracle for more info and Wikipedia for a decent high level explanation of JSP technology.
To handle the AJAX, you're going to need to define a new network endpoint capable of processing the XML requests coming up from the Javascript. See this example, this library, or this JSON Example.
What I do quite frequently is setup two servlets for this situation:
MyServlet
MyAJAXServlet
MyServlet handles the normal HTTP requests and (usually) ends up using a RequestDispatcher to forward the request to a JSP.
Example:
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = -5630346476575695999L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
private final void doGetAndPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
/*
* Handle the response here, manipulate the 'MODEL'
*/
/*
* Forward to the 'VIEW' (No Baba Wawa jokes please)
*/
RequestDispatcher rdis = req.getRequestDispatcher("Path/To/My/JSP");
rdis.forward(req, res);
}
}
Where as the AJAX servlet checks the request's parameter list for presence of a 'command':
public class MyAJAXServlet extends HttpServlet {
private static final long serialVersionUID = -5630346476575695915L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetAndPost(req, res);
}
private final void doGetAndPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
String cmd = req.getParameter("cmd");
if (cmd == null || cmd.length() < 1) {
/* Custom fail mode here, perhaps toss back failure HTML */
return;
}
/* Easily implement command pattern here, but for simplicity, we will use an if tree */
if (cmd.equalsIgnoreCase("getSomeData")) {
String out = "<tr><td>ExampleCell in ExampleRow</td></tr>";
res.getWriter().append(out);
return;
} else if (cmd.equalsIgnoreCase("someOtherCommand")) {
/* Do something else */
}
}
}
If you format your JSP to allow for bulk replacement of html elements like so:
<table id="pleaseReplaceMyContentsTABLE">
<tr><td> </td></tr>
</table>
Then it becomes very easy to dynamically modify a web pages content (I use JQuery for this example):
var url = "http://mydomain.whatever/myapp/MyAJAXServletMappedURL?cmd=getSomeData";
$.post(url, function(data) {
//Message data a bit & display
$("#pleaseReplaceMyContentsTABLE").html(data);
});
Some limitations with sending back preformatted HTML from the AJAX Servlet:
If you are sending back a moderate to large amount of data, then your webserver will easily become overloaded when the number of clients starts to rise. Aka, it won't scale well.
Java code that is formatting HTML to send to a client can get ugly and hard to read. Quickly.
If you use DWR you don't need to use JSON, it uses internally.
Use javascript , the jsp code is out-of-scope. The page has been generated so you only can modify the DOM using javascrip
There are lot of examples doing what you need in DWR tutorials. I suppose you need just do something as:
dwrobject.funtionAjax(param,returnFunction);
...
function returnFunction(data) {
// use javascript to change the dom
}
Ajax part: We return a list of objects:
public List<IdTexto> getPaisesStartingBy(String texto,String locale){
List<IdTexto> res = new ArrayList<IdTexto>();
// Fill the array
return res;
}
The IdTexto is a simple bean with geters and setters:
public class IdTexto {
private int id;
private String texto;
private String texto2;
// getters and setters
}
And it is defined in the dwr.xml as bean:
<convert converter="bean" match="com.me.company.beans.IdTexto"/>
And the class containing the java function is defined as creator:
<create creator="new" javascript="shopdb">
<param name="class" value="com.me.company.ajax.ShopAjax"/>
</create>
In the jsp, we define a function javascript to retrieve the List of starting by some text object in this way:
shopdb.getPaisesStartingBy(req.term,'<s:text name="locale.language"/>', writePaises);
And the corresponding function to write down the texts:
function writePaides (data) {
var result="<table>";
for (i=0; i<data.length;i++) {
id = data[i].id;
texto=data[i].texto;
texto2=data[i].txto2;
// now we write inside some object in the dom
result+="<tr><td>"+id+"</td><td>"+texto+"</td><td>"+texto2+"</td></tr>";
}
result+="</table>";
$("tabla").innerHTML=result;
}
If you, instead of a bean have some other object you'll access the properties in the same way.

Categories

Resources