How do JSP's and Servlets interact with each other - java

I am creating a Java Web Application on Eclipse and am unsure exactly how you can link jsp pages with Servlets. Example if your jsp page displays forms for the user to enter their First Name and age and then once they click submit, re-directing to the Servlet to handle the data.
Here is intro.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
<style>.error { color: red; } .success { color: green; }</style>
</head>
<body>
<form action="intro" method="post">
<h1>Hello</h1>
<p>
<label for="name">What's your name?</label>
<input id="name" name="name">
<span class="error">${messages.name}</span>
</p>
<p>
<label for="age">What's your age?</label>
<input id="age" name="age">
<span class="error">${messages.age}</span>
</p>
<p>
<input type="submit">
<span class="success">${messages.success}</span>
</p>
</form>
</body>
</html>
Here is IntroductionServlet.java:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/intro")
public class IntroductionServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request: we actually don't need to do any business stuff, so just display JSP.
request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request: gather and validate submitted data and display result in same JSP.
// Prepare messages.
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
// Get and validate name.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
} else if (!name.matches("\\p{Alnum}+")) {
messages.put("name", "Please enter alphanumeric characters only");
}
// Get and validate age.
String age = request.getParameter("age");
if (age == null || age.trim().isEmpty()) {
messages.put("age", "Please enter age");
} else if (!age.matches("\\d+")) {
messages.put("age", "Please enter digits only");
}
// No validation errors? Do the business job!
if (messages.isEmpty()) {
messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
}
request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
}
}
According to my understanding, form action = "intro" should re-direct the intro.jsp page to the IntroductionServlet once the submit button has been clicked.
However, I receive a requested resource is not available error in Eclipse. It seems like it searches for an intro.jsp file instead. I am running Dynamic Web Module 3.0 so I thought that mapping the servlets is not required in web.xml since I have the "#WebServlet("/intro")" tag.
Basically, I want to know how to retrieve information from a text field once the submit button has been pressed and use it as a variable in my application.

you can also submit your form by manually define your servlet,
i have used that in my application.
following is the code :-
$("#SubmitButton").click(function()
{ var HashedPass=Sha1.hash($("#userPassword").val());
$("#userPassword").val(HashedPass);
$('#loginForm').attr('method','post');
$('#loginForm').attr('action','SignupServlet');
$('#loginForm').submit();
});

Did you try giving it like this(the conventional way):
action="<%=request.getContextPath() %>/IntroductionServlet"
For your second question: Once the control reaches the servlet from the jsp page, the textfield content can be accessed via request.getparameter(textfieldname) in the servlet.
Hope this is useful.

try :
request.getRequestDispatcher("WEB-INF/intro.jsp").forward(request, response);
to receive parameters you should use :
request.getParameter("<name of input text>");
send parameters :
request.setAttribute("myobject", myobjetc);
and to access this variable from jsp using :
${myobject.atribute}
If the servlet not works add this to form (It is not necessary but you can try):
<form action="${pageContext.request.contextPath}/intro" method="POST">

Related

How to print Hindi text into web page by giving servlet , java and html code

i am using servlet, java and one html code to extract hindi text from following URL : https://hi.wikipedia.org/wiki/%E0%A4%B5%E0%A4%BE%E0%A4%B0%E0%A4%BE%E0%A4%A3%E0%A4%B8%E0%A5%80
i want to display hindi font by servlet code , code is given as :
//Extraction1.java //java file
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class Extraction1 {
public String toHtmlString(String url) throws IOException
{
StringBuilder sb = new StringBuilder();
for(Scanner sc = new Scanner(new URL(url).openStream()); sc.hasNext(); )
sb.append(sc.nextLine()).append('\n');
return sb.toString();
}
}
MultiParamServlet3.java // servlet file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MultiParamServlet3 extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
{
PrintWriter pw=resp.getWriter();
resp.setContentType("text/html");
String[] values=req.getParameterValues("habits");
Extraction1 t=new Extraction1();
String s=t.toHtmlString(values[0]).replaceAll("\\<.*?>","");
pw.println("<html><head><meta charset=\"utf-8\"></head><body>"+s+"</body></html>");
pw.close();
}
}
index.html // html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form method="Post" action="MultiParamServlet3">
<Label> <br><br> &n bsp; Enter the URL : </label>
<input name='habits' id='t2'>
<input type="submit" name="submit">
</form>
</body>
</html>
servlet program able to print english text after extraction, but hindi text converted as ????? (question mark).
how to print hindi text into web page by servlet program ?
You have to set encoding response.
change "text/html" to "UTF-8".
resp.setCharacterEncoding("UTF-8");
Use StringEscapeUtils class from apache.commons.lang and implement it like:
String output=StringEscapeUtils.unescapeHtml3(responseMessageString);
mathod depends on api version i am using commons.lang 3.3.

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

Ajax response doesn't display in JSP page

I'm Trying to Save small record using JSP ajax in technology. The project working procedure is like this.
01. index.jsp : Send data to SaveStudent servlet
02. SaveStudent : Get request form jsp and send it to validation java class
03. Validation : Validate data and Send to DaoImpl java class
04. DaoImpl : Override the method in StudentDAO, Do the save SQL query.
05. StudentDAO : A interface has all the database related methods.
Here is the image of the project.
Given below is index.jsp files source code.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form action="SaveStudent" method="post">
<label>Enter Name:</label>
<input type="text" name="name" id="txtName"/>
<br/>
<label>Enter City:</label>
<input type="text" name="city" id="txtCity"/>
<br/>
<input type="submit" value="Send" id="btnSave"/>
<div id="response"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
var $name = $("#txtName").val();
var $city = $("#txtCity").val();
$.post('SaveStudent', {
name: $name,
city: $city
}, function(responseText) {
if (responseText !== null) {
$('#response').text(responseText);
} else {
alert("Invalid Name");
}
});
});
});
</script>
</body>
Here is SaveStudent java class's source code.
package Control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Validation;
public class SaveStudent extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String record = "";
try {
Validation val = new Validation();
record = val.validateSave(request, response);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
if (record != null) {
out.write(record);
} else {
out.print("Error Occured..!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Save record is working fine. Database is also updating. But the problem is The "Save Successful" message is appears in servlet page. Not under the jsp page.
Please help me on this. Thank you.
I figure out a way. I put replace "submit" type to "button". Now working perfectly. Thank you for your Time.

JSP/Servlet if error stay on same page instead of forwarding

I am new here and have been working on this all evening. I know this should be simple and I am just missing something silly. I have a jsp page and a servlet (code below). I am trying to search out a customer from my database, which works. However, if the customer is not found I want to post an error message on the same jsp page so that the user can possibly re-enter the phone number in case they made a mistake. I am unsure how to do this. I can forward to the new "customer" page just fine and I have tried successfully to redirect back to the same page, but I don't know how to put the message there. Help please!
jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %>
<%# page import="java.util.*" %>
<%# include file="staticpages/pageHeader.html" %>
<br />
<hr />
<br />
<form name="custform" method="POST" action="ChooseCustomer.do" >
<span class="sectionheader">Look Up Customer by Phone Number:</span>
<input type="text" name="phone1" size="3" maxlength="3" onKeyUp="checklen(this)" />
<input type="text" name="phone2" size="3" maxlength="3" onKeyUp="checklen(this)" />
<input type="text" name="phone3" size="4" maxlength="4" onKeyUp="checklen(this)" />
<input type="submit" name="formaction" value="Search" />
<input type="submit" name="formaction" value="Enter New Customer" />
</form>
<%# include file="staticpages/pageFooter.html" %>
servlet code:
package pizzapkg;
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ChooseCustomer
*/
#WebServlet("/ChooseCustomer")
public class ChooseCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
/** #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Customer c = null;
if (request.getParameter("formaction").equals("Search")) {
Database db = (Database) getServletContext().getAttribute("db");
/* Search Database for existing customer */
String searchPhone = request.getParameter("phone1")
+ request.getParameter("phone2")
+ request.getParameter("phone3");
String sql = "SELECT * FROM customers WHERE cust_phone=\"" + searchPhone + "\";";
ResultSet rs;
try {
rs = db.runSqlQuery(sql);
rs.next();
c = new Customer(rs.getString("cust_id"), rs.getString("cust_fname"),
rs.getString("cust_lname"), rs.getString("cust_address"),
rs.getString("cust_city"), rs.getString("cust_state"),
rs.getString("cust_zip"), rs.getString("cust_phone"),
rs.getString("cust_notes"));
} catch (Exception e) { e.printStackTrace(); }
request.setAttribute("customer", c);
}
RequestDispatcher rd = request.getRequestDispatcher("/customer.jsp");
rd.forward(request, response);
}
}
PS This the the first time I have built a servlet so this is all new to me. I love examples so any help you can give will be greatly appreciated.
You may set a flag in request object inside your servlet, if the customer is not found e.g.
request.setAttribute("customerFound", "No");
In your JSP, put a JSP scriptlet to check the request attribute and print the message wherever you want e.g. if you want the message after your <HR/> then:
<hr />
<% if("No".equals(request.getAttribute("customerFound")) { %>
<div style="color: red">No customer found</div>
<% } %>
<br />
I am sharing the very basic way of achieving your desired result.

Problem with jsp/servlet page

I want to create a simple JSP page. I have an EJB, in this there is a session bean.
I have a JSP page and a Servlet, but I have a strange situation.
When I click execute on my page, this turns in a white page and don't give me the result.
I post here my code, can you help me please.
Servlet:
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ejb.calc;
/**
* Servlet implementation class calcServlet
*/
public class calcServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public calcServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession(true);
RequestDispatcher rd=this.getServletContext().getRequestDispatcher("/index.jsp");
float a=Float.parseFloat(request.getParameter("n1"));
float b=Float.parseFloat(request.getParameter("n2"));
char oper=request.getParameter("oper").charAt(0);
float result=0;
try {
Context ctx=new InitialContext();
// call the calcImpl class of the SimpleCalculator EJB with the mappedName
calc cl=(calc) ctx.lookup("Firstcalc");
switch(oper){
case '+': result=cl.sum(a, b); break;
case '-': result =cl.minus(a, b); break;
case '*': result =cl.mult(a, b); break;
case '/': result =cl.div(a, b); break;
}
session.setAttribute("result",result);
request.setAttribute("a", a);
request.setAttribute("b", b);
}
catch(NamingException e)
{session.setAttribute("erreur: ",e.getMessage());
}rd.forward(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2> <b> Hello World To The Simple Calculator </b> </h2> <% float a=2,b=1; if (request.getAttribute("a")!=null) a=Float.parseFloat(request.getAttribute("a").toString()); if( request.getAttribute("b")!=null) b=Float.parseFloat(request.getAttribute("b").toString()); %> <form method="post" action="calcServlet"> <b>Number 1:</b><input type='text' name='n1' value="<%=a%>" /> <br/>
<b>Number 2:</b><input type='text' name='n2' value="<%=b%>" /> <br/>
<u><b>Options:</b></u> <br/>
<ul>
<li><b>+</b><input type='radio' name="oper" value='+' checked /></li>
<li><b> -</b><input type='radio' name="oper" value='-' /></li>
<li><b>*</b><input type='radio' name="oper" value='*' /></li>
<li> <b>/</b><input type='radio' name="oper" value='/' /></li> </ul>
<b>-------------------------------------------</b> <br/>
<input type="submit" value="Executer" /> </form>
<font color='blue'><b>Result is: </b> <%=session.getAttribute("result")%> </font> <br/> <font color='red' >Error: <%=session.getAttribute("error")%></font>
</body>
</html>
A JSP will blank out when you use old fashioned scriptlets (those <% %> things) and one of such a scriptlet has thrown an exception while the response has already been committed. It's too late then to display the error page. The browser ends up with a halfbaked HTML page (the HTML generated by JSP is incomplete and the browser will usually go blank). You should read the server logs for the exception and fix the code accordingly.
Unrelated to the actual problem, your approach is pretty clumsy. You don't need scriptlets at all. Just use EL (those ${} things). It has instant access to request parameters. E.g.
<input type="text" name="n1" value="${param.n1}" />
(for extra course points: use JSTL fn:escapeXml() to prevent XSS)
You don't even need to duplicate them as request attributes in the servlet. You should also not store the result as session attribute (it would be shared among all browser windows/tabs in the same session, you don't want to have this for a request based variable). Store it as request attribute
request.setAttribute("result", result);
and access it by EL as follows, it has instant access to page/request/session/application scoped attributes by just its name:
<b>Result is: </b> ${result}
Related questions:
Simple calculator in JSP/Servlet (with optional Ajax)
How to avoid Java code in JSP files

Categories

Resources