Send data from JSP to Java program - java

I'm a beginner to JSP (started today) and wanted to send some data (which I have got in a JSP file from an HTML form) to a JAVA program where I could use it.
Peterclass is the name of the Java program I'm gonna be making/using.
Suppose my JSP file is like this:
<%# page import="com.example.Peterclass"%>
<%# page import="java.util.*"%>
<html>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
<h1>
Hello, <%=username%>!
</h1>
</body>
</html>
and I wanted to receive the values of username and password variables in a JAVA program (I'm using Tomcat server for the purpose). How shall I do it? Please be as simple as you can be.
Thank you.

First of all, you will need a so called "Servlet" to work with request and response Parameter.
Here is a first tutorial on how to create and use servlets:
Click here
Another tip for you:
It is not state of the art to use so called Scriptlets.
Scriptlets is a form of Java-Code in JSP Sites:
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
%>
You can easily get the parameter you set in your Servlet with:
${requestScope.<<PARAMETERNAME>>}
e.g. ${requestScope.username}
or if your parameter is in the HTTPSession:
${sessionScope.<<PARAMETERNAME>>}
your jsp side would look like this afterwards:
<html>
<body>
<h1>
Hello, ${requestScope.username}!
</h1>
</body>
So, to come back to your question:
In your Servlet you can set the Parameter with
request.setParameter(<<PARAMETERNAME>>,<<VALUE>>)
In this Servlet you can call normal Java-Functions. First step for you is to read through tutorials :)

Related

how to use a variable's value throughout session in servlet/jsp?

I doing some project based on authentication using servlet/jsp.When user log in initially using username and password where authentication takes place through login servlet,there I need to save user's email in variable ,say String email by executing SELECT query.
I need to access that variable from login servlet to email servlet for sending some sort of OTP to user's email.
How to achieve that using session attribute or any relevant idea??
Use session.setAttribute() and session.getAttribute() methods.
Read javadoc of HttpSession here.
You can refer this complete example.
To save data in session you should use session object from http request like this:
HttpSession session = request.getSession();
session.setAttribute("email", email);
To retrieve data from session object with scriptlet use:
<%= session.getAttribute("email")%>
or
<%= request.getSession().getAttribute("email")%>
You can also use EL expression:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${sessionScope.email}"/>
please use as follows. you can achieve what you need.
<%session.setAttribute( "email", "test#gmail.com" );%>
<%= session.getAttribute( "email" ) %>
The other way that we use.
<c:set var="email" value="test#gmail.com" scope="session"/>
you get this using JS:
var mail ="${email}";

how do i load a jsp page from a jsp page?

I am writing a JSP code which goes like this:
<% if(---)
{----}
else
{ ---
%>
<jsp:forward page="error.jsp">
<jsp:param name="" value=""/>
</jsp:forward>
<%
}
%>
The error.jsp is in the same directory as the current jsp file still it is throwing "class not found exception". What to do?
Not much clear from your question what you are trying to achieve but If you are adding the another jsp page within current jsp page then use jsp:include otherwise if trying to redirect to another jsp page then following could be used.
Use in scriptlet response.sendRedirect in your case as below:
<%
response.setHeader("header_key", "header_value");
response.sendRedirect("your_page_location")
%>
Above could be used for external pages as well like "www.google.com"
On the other hand you could use request forward with all old parameters and data from calling page. See below:
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
Also, another easy way could be to submit a form with action="your_jsp.jsp" but this should be used in case of form submissions where you are sending some data etc.
Make choice for any of above options on a case basis.
Hope it helps!

Validating a form using JSP

I'm completely new to JSP and am creating a simple form and validating it through JSP.
Here's my code :-
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<%#page import="java.io.* , java.sql.* , java.util.* , javax.servlet.*" %>
<body>
<h1>Login Page by JSP</h1>
<hr>
<form method="post" action="index_jsp">
Enter name : <input type="text" name="user">
Enter password : <input type="password" name="pass">
<input type="submit" value="login">
</form>
<%
String user = request.getParameter("user");
String pass = request.getParameter("pass");
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
%>
<br>
Click here !
</body>
</html>
But each and every time I run it , I get a NullPointerException .
What am I doing wrong ? Immediate help would be appreciated !
Thanks!
First bit of advice, since you're new to JSP: Don't write scriptlet code. That's all the stuff between <% and %>. It's a 1998 vintage technology that should be discouraged. Learn JSTL and Model-2 MVC instead.
You need a servlet to orchestrate those JSPs. Every web MVC framework that I know of has what's called a front controller servlet to manage the communication and orchestration. You should, too.
You have the form POST in this JSP, sending the HTTP request to index_jsp (bad name). It's executing in the browser on the client machine.
I would expect you to send this to a servlet on the server side that gets the HTTP request, gets the username and password out, compares the values to a database to see if the user is indeed registered. Then I'd either send the next view or route to the "sorry" page. That's not what you're doing.
Don't do equals checks on the variables, rather do them against the constants:
if("admin".equals(user) && "admin".equals(pass)) {
response.sendRedirect("wel.html");
}
This way you cannot get the NPE.
Change this line
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
with
if(user!=null){
if(user.equals("admin") && pass.equals("admin"))
{
response.sendRedirect("wel.html");
}
}
You are not checking null for request attributes.
replace
String user = request.getParameter("user");
String pass = request.getParameter("pass");
with
String user = request.getParameter("user") != null ? request.getParameter("user") : "";
String pass = request.getParameter("pass") != null ? request.getParameter("pass") : "";
change codeļ¼š
if("admin".equals(user) && "admin".equals(pass)) {
response.sendRedirect("wel.html");
}
When you first run jsp,it will execute the code,but user and pass is null.

Nutch Newbie - JSP with html problem

System: Mac OSX
I have set up nutch so that it crawls and indexes my site. It also returns search results. My problem is that I want to customise the Nutch index.jsp and search.jsp pages to fit with my site. Ive read up and on jsp and it says its just a matter of putting in the html tags and then using <% %> to enclose the Java scriplets you want. For some reason nothing changes when i edit the files (index and search)
Here is what the original file displays:
<%# page
session="false"
import="java.io.*"
import="java.util.*"
%><%
String language =
ResourceBundle.getBundle("org.nutch.jsp.search", request.getLocale())
.getLocale().getLanguage();
String requestURI = HttpUtils.getRequestURL(request).toString();
String base = requestURI.substring(0, requestURI.lastIndexOf('/'));
response.sendRedirect(language + "/");
%>
Here is my edited version with sum gibberish test added to test it:
<html>
<head>
</head>
<body>
gigigyigig
<%# page
session="false"
import="java.io.*"
import="java.util.*"
%><%
String language =
ResourceBundle.getBundle("org.nutch.jsp.search", request.getLocale())
.getLocale().getLanguage();
String requestURI = HttpUtils.getRequestURL(request).toString();
String base = requestURI.substring(0, requestURI.lastIndexOf('/'));
response.sendRedirect(language + "/");
%>
ghjgjkbkhb
hjgjvjhvj
</body>
</html>
Nothing has changed tho and the nutch homepage/index.jsp still displays the same as original. This is my first encounter with JSP so its just what ive picked up so far. Can anyone tell me why the page isnt displaying the html with gibberish typed??
I have my search totaly modified. However I have my <html>... tags after the second scriptlet ie <% %> not <%# page.
As for your index.jsp modified it has a redirection response.sendRedirect and therefore it looks normal to me that you see nothing.
Also I presume you took care of loading the jsp pages at the right place under the tomcat/webapps tree, because the standard ant make file doesn't. So I ended up adding some Ant task to patch my test website.
Beware if you are going to change the .jar files you also need to restart Tomcat.

JSP: Use information from one page to another

I currently have a JSP page with a Form for the user to enter their name, but what I want is to get the user forwarded to a different JSP page after form submission and to carry on their name to be used.
I don't want to use JSTL EL just simple JSP uses.
I was thinking of using a bean storing the detail in a session but how would it work.
Thanks.
You'd have JSP enter the info into a form and POST it to a servlet. The servlet would validate the form input, instantiate the bean, add it to session, and redirect the response to the second JSP to display.
You need a servlet in-between. JSPs using JSTL are for display; using the servlet this way is called MVC 2. Another way to think of it is the front controller pattern, where a single servlet handles all mapped requests and simply routes them to controllers/handlers.
duffymo you have the best idea but here is a quick solution by just passing things through the JSP.
Here is the JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Simple jsp page</title></head>
<body><form name="test" action="./stackTest2.jsp" method="POST">
Text Field<input type="text" name="textField">
<input type="submit">
</form> </body>
</html>
and then the second page looks like this:
<html>
<head><title>Simple jsp page</title></head>
<body><%=request.getParameter("textField")%></body>
</html>
And then put information in a hidden field, you can get information by using the request.getParameter method. This just prints out what was in the form, but using the same idea for inputting it in to the hidden field in a form. I recommend this as all my experience with sessions have ended in a failure. I STRONGLY DO NOT Recommend this method, MVC is a much better way of developing things.
Dean

Categories