How to save parameters and clear the url? - java

My aim is to provide the ability to sending comments or reviews on the site. When I get the parameter from the form they are properly added to my reviews database. But the problem is that the URL contains the paramaters. So when I fill the form and press the submit button, there are a new record in the database, but the comment is not shown on the page at once. Also when I refresh the page, the same record is duplicated in the database. I want user to fill the forms, press the button and then redirect to the same page with his comment or review. Here is my servlet doGet method code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
}
}
And my form in jsp:
<form action = "${pageContext.request.contextPath}/Reviews" method="get">
<p>Your name: <input type="text" size="107" name="reviewName" required></p>
<p>Your e-mail: <input type="text" size="90" name="reviewMail" required></p>
<p>Your review:</p>
<p><textarea rows="15" cols="135" name="reviewText" ></textarea></p>
<input type="submit" value="Send" name="sendReviewButton" class="btn btn-primary btn-lg" id="send-btn">
</form>

you should probably use POST and not GET, so that the data is not seen on the URL and the browser warns the user if she reloads the page
Add the new review before you get the list of reviews, so you get the updated list
use sendRedirect to the reviews.jsp page so that the url is the short one. This should render point 2 moot as you're going to list the review after you've added the new one.

I added the else statement. So the new review is correctly added, it is shown on the page immediately. When I refresh the page the record in the database is NOT duplicated:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Query query = new Query();
if (request.getParameter("sendReviewButton") != null){
String userName = request.getParameter("reviewName");
String eMail = request.getParameter("reviewMail");
String reviewList = request.getParameter("reviewText");
query.addReview(userName, eMail, reviewList);
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
response.sendRedirect("/ScopeSoftware/Reviews");
}else {
Object allReviews = query.getAllReviews();
request.setAttribute("allReviews", allReviews);
RequestDispatcher rd = request.getRequestDispatcher("reviews.jsp");
rd.forward(request, response);
}
}

You are forwarding to the JSP page, but this does not solve the refresh problem. The solution is - as you already said in your question - to redirect to the JSP:
response.sendRedirect("reviews.jsp"); // url of the JSP page.
This sends a HTTP redirect back to the browser and the browser then does a new GET to reviews.jsp.

Related

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.

What is the best way to communicate between doGet method and JSP page? [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I'm making a dynamic web project in Eclipse and cannot figure out how to send the result of the query to a jsp file.
This is the servlet doGet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String name = session.getAttribute("user").toString();
String query = "SELECT DISTINCT t.text, t.user, t.date"
+ " FROM users u, tweets t, follows f"
+ " Where t.parent is null"
+ " AND u.id ='"+name + "'"
+ " AND ( f.follower = u.id"
+ " AND f.followed = t.user"
+ " OR t.user = u.id)"
+ " ORDER BY t.date DESC;";
try {
ResultSet rs = Dao.executeQuerySQL(query);
while (rs.next()){
//Get all tweets -> THIS IS THE INFO I WANT TO RETRIEVE
rs.getString(1);
}
}
and this is the timeline.jsp:
<script>
$(document).ready(function(){
});
</script>
This is the timeline!
How I can retrieve here in the jsp the information?
Thanks in advance.
For Servlet section for doGet()
#WebServlet("/products")
public class ProductsServlet extends HttpServlet {
#EJB
private ProductService productService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productService.list();
request.setAttribute("products", products); // Will be available as ${products} in JSP
request.getRequestDispatcher("/WEB-INF/products.jsp").forward(request, response);
}
}
For JSP:
<table>
<c:forEach items="${products}" var="product">
<tr>
<td>${product.name}</td>
<td>detail</td>
</tr>
</c:forEach>
</table>
Resource Link:
doGet and doPost in Servlets
UPDATE1 for AJAX:
Returning Map as JSON
Here's another example which displays Map<String, String> as <option>:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> options = new LinkedHashMap<>();
options.put("value1", "label1");
options.put("value2", "label2");
options.put("value3", "label3");
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
And the JSP:
$(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
$.get("someservlet", function(responseJson) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
var $select = $("#someselect"); // Locate HTML DOM element with ID "someselect".
$select.find("option").remove(); // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
$.each(responseJson, function(key, value) { // Iterate over the JSON object.
$("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
});
});
});
with
<select id="someselect"></select>
Resource Link:
How to use Servlets and Ajax?
Use one of the jquery ajax functions like .ajax or .get to call the servlet.
Refer to below link for API.
http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
something like this,
$.get( "servlet url here", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
In your servlet convert your data to json or html snippet and write to response.

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.

Not able to access request parameters in java servlets

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")) {
}

Ajax call is not working

I am very new to ajax concept,I want to submit a form without refresh the page
ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Listservlet",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.fname.message.innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
JSP
<form name="fname" action="Listservlet" method="post">
<input type="text" name="txtname" id="txtname" />
<input type="button" value="Submit" onclick="ajaxFunction();" />
<div id="message"></div>
</form>
servlet
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
String name = null;
PrintWriter out = response.getWriter();
if(request.getParameter("txtname") != null) {
name = request.getParameter("txtname");
}
else {
name = "";
}
out.println("You have successfully made Ajax Call:" + name);
}
This ajax idea I got from google, bt it is not working,
While clicking on the button,nothing it showing.
Please help me.
replace
document.fname.message.innerHTML=xmlhttp.responseText;
by
document.getElementById("message").innerHTML=xmlhttp.responseText;
General Steps to find out where goes wrong:
use browser debugger to tell if ajax request was successfully sent;
debug your receiving Servlet, to tell if request was actually delivered to your Servlet;
use browser debugger to tell if the response text is desired one;
for your issue I think you need to
change
document.fname.message.innerHTML=xmlhttp.responseText;
to
document.getElementById("message").innerHTML = xmlhttp.responseText;
Also remember Close your ouputstream

Categories

Resources