JSP requestDispacthing - java

I have two JSP pages. In first page I have given fields to fill personal details and I have written request.getRequestDispatcher("second.jsp") and forwarded the the request. But When I run the "first.jsp" on server in eclipse, it is directly going to "second.jsp" but in URL it is shopwing "first.jsp". What might be the problem?
First.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>
<br>
<h2>Enter Your Personal Details</h2>
<form action="personal.jsp" method="get">
<table>
<tr><td>Name: </td><td> <input type="text" name="name" /><br /><br /></td></tr>
<tr><td>Email-ID: </td><td><input type="text" name="email" /><br /><br /></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dob" /><br /><br /></td></tr>
<tr><td>Password: </td><td><input type="text" name="pass" /><br /><br /></td></tr>
<tr><td>Age: </td><td><input type="text" name="age" /><br /><br /></td></tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
<%!
String uname=null,pass=null,email=null;
String age=null,dob = null;
%>
<%
uname= request.getParameter("name");
session.setAttribute("username",uname);
pass= request.getParameter("pass");
session.setAttribute("password",pass);
age = request.getParameter("age");
session.setAttribute("age",age);
email = request.getParameter("email");
session.setAttribute("email",email);
dob = request.getParameter("dob");
session.setAttribute("dob",dob);
response.sendRedirect("academic.jsp");
%>
</body>
</html>
Second.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>
<br>
<h2>Enter Your Academic Details</h2>
<form action="academic.jsp" method="get">
<table><tr><td>
MID: </td><td> <input type="text" name="mid" /><br /><br /></td></tr>
<tr><td>Marks: </td><td> <input type="text" name="marks" /><br /><br /></td></tr>
<tr><td>Salary: </td><td><input type="text" name="salary" /><br /><br /></td></tr>
<tr><td>Stream:</td><td><select name="stream"><option>Java</option><option>dotNET</option><option>Testing</option></select><br /><br /></td></tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
<%
out.println(session.getAttribute("name"));
%>
</body>
</html>

You need to do response.sendRedirect() to make the effect in url.
request#forward
Silently passes the control to your another resource,And happens on server side,browser doesn't know about it.
Forward():
For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.
sendRedirect()
Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.
Highlighting Luggis comment,that move your business logic to Controller and try to avoid scriplets too if possible.
Though,it is not recommended,If you want to change the URL and still want to access the data in second page,one possibility is that put data in session and access in second jsp.

The problem is generated because you have a direct call of forward method in a scriptlet, this might look like this
request.getRequestDispatcher("second.jsp").forward(request, response);
By your question edit, this is generating the problem:
response.sendRedirect("academic.jsp");
Note that using scriptlets is highly discouraged.
Make sure all your data processing and navigation is handled in a Servlet or another controller classes provided by a MVC framework like JSF managed beans or Spring MVC #Controller decorated classes.
More info:
How to avoid Java code in JSP files?
StackOverflow's Servlet wiki, here you can find a real world basic example about how to handle data processing and manipulation from a view to a servlet and then navigating to another view.

The actual problem lies in first.jsp line response.sendRedirect("academic.jsp"); which is inside a JSP Declaration and not JSP Scriptlet, as per the doc variables and methods in JSP declarations become declarations in the JSP page’s servlet class which explains why when you hit the first.jsp its getting redirected to another page without any action and as other suggested its not advisable to use JSP scriptlets, or declarations in your JSP.

Related

Checking a checkbox on a JSP page based on List values

I found similar problem: Checking a checkbox based on a database entry on a JSP page
I have a Faculty entity and a Subject entity. Every faculty has a list of preliminary subjects.
So also I have a faculty edit page where I have a checkbox with all subjects.
Let's say I have two collections. One with all the subjects and another with subjects that needed for this faculty.
And when user wants to edit faculty at the start he gets edit page with checked values on subjects where value from faculty subjects equals to value from collection of all subjects.
How this can be achieved ? Or maybe there is a simpler way ?
EDIT:
My project is based on jsp and servlets. I have one servlet which is a Front Controller and Command Pattern design. So controller calls appropriate Command, that performs some work and then returns a path to resource. My Model is dao and transfer objects, they interact with MySQL database.
My facultyEdit.jsp page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${faculty.name}</title>
</head>
<body>
<h1>${faculty.name}</h1>
<form id="edit_faculty" action="controller" method="POST">
<input type="hidden" name="command" value="editFaculty" /> <input
type="hidden" name="oldName" value="${requestScope.name}" /> <input
type="hidden" name="show" value="false" />
<fieldset>
<label for="name">Faculty name:</label> <input name="name"
type="text" value="${requestScope.name}" /> <label
for="budget_seats">Budget seats:</label> <input name="budget_seats"
type="text" value="${requestScope.budget_seats}" /> <label
for="total_seats">Total seats:</label> <input name="total_seats"
type="text" value="${requestScope.total_seats}" />
<p>
<label>Preliminary subjects:</label>
</p>
?????
<input type="submit" value="Edit" />
</fieldset>
</form>
</body>
</html>
So the question what to put instead of ????? to make some of the subjects ckecked.

How to put html tag inside html tag in jsp page

In my website, I download a full webpage from another site, modify something and extract it as a string. Now, I want to display it as a part of my .jsp page, with scrolling bar.
How can I do that? It shows me error when I try to put another <html> tag.
Thanks for your help.
EDIT!!!
Here is my .jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=UTF-8">
<title>Create Your XSLT Here</title>
</head>
<body>
<form action="../AdminServlet">
URL <input type="text" name="txtUrl" value="" /><br/>
Start Promotion <input type="text" name="txtStart" value="" /><br/>
Produt Name <input type="text" name="txtProductName" value="" /><br/>
<input type="submit" value="View" name="action" />
</form>
<c:if test="${not empty requestScope.website}">
<div>
${requestScope.website}
</div>
</c:if>
</body>
</html>
requestScope.website is a full html page as a string, return from server. When I run, everything in the requestScope.website (such as background image) apply to all my page. I want to limit it to a part of my page, just like using iframe.
I think u can use the <jsp:include ...>tag.
Put the whole source code into a jsp and use the tag to include to your page.
Something like
<jsp:include page="mypagepath/page.jsp"></jsp:include>

Call external javascript function frm JSP

I'm brand new to the javascript. I'm trying to call a javaScript function from my jsp.Its not working. I was trying to debug it through bugzila. It saying "No Javascript on this page"
<%# 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>
<script type="text/javascript" src="ajaxs.js"></script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<%
out.println("Bismillahir Rahmanir Rahim");
%>
<jsp:useBean id="numBean" class="beans.NumberBean">
<jsp:setProperty name="numBean" property="*" />
</jsp:useBean>
<form action="index.jsp" method="post">
<table>
<tr>
<td>Enter Integers:</td>
<td><input type="text" id="inputString" name="inputString"
value="<jsp:getProperty name="numBean" property="inputString" />"
/> </td>
<td>(Use semi-colon to separate number)</td>
</tr>
<tr>
<td>M - number of largest element to find.:</td>
<td>
<input type="text" id="nthHighest" name="nthHighest"
value="<jsp:getProperty name="numBean" property="nthHighest" />" />
</td>
</tr>
</table>
<input type="submit" value="Identify" onclick="ajaxFunction()" />
<div id="result"></div>
</form>
</body>
</html>
I'm trying to call "ajaxFunction()" on onclick event.
I included js file as following at the top:
<script type="text/javascript" src="ajaxs.js"></script>
can u pls help me to identify what I'm doing wrong here...
Thanks in advance
Try with including script tag with "src="ajaxs.js" (your current script that including "src="ajaxs.js") within head tag.The contents within head tag load at the loading page .
thanks....

The resource required (servlet) not available

I have the following problem when trying to use the login.jsp
I have the following code in the login
<%# include file="/jsp/include.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>
<script>
function sendForm() {
document.formLogin.submit();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Example :: Spring Application</title>
</head>
<body>
<div class="container">
<form class="bs-docs-example form-horizontal"
action="ServletValidation" name="formLogin" id="formLogin"
method="post">
<legend>Login</legend>
<div class="control-group">
<label for="inputUsername" class="control-label">Email</label>
<div class="controls">
<input type="text" id="inputUsername">
</div>
</div>
<div class="control-group">
<label for="inputPassword" class="control-label">Password</label>
<div class="controls">
<input type="password" id="inputPassword">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox"> <input type="checkbox">
Remember me
</label>
<button class="btn" type="submit" action="sendForm();">Sign
in</button>
</div>
</div>
</form>
</div>
</body>
</html>
And the following text in the web.xml
<servlet>
<description></description>
<display-name>ValidationServlet</display-name>
<servlet-name>ValidationServlet</servlet-name>
<servlet-class>bt.servlet.ValidationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ValidationServlet</servlet-name>
<url-pattern>/ValidationServlet</url-pattern>
</servlet-mapping>
But once I click the button for submit it returns:
State HTTP 404 - /bt/jsp/ServletValidation
Description The resource required (/bt/jsp/ServletValidation) is not
available.
The folder structure is the following:
+bt
-src
-WebContent
-jsp
-resources
-WEB-INF
-classes
*web.xml
*index.jsp
The problem I'm finding is why is it sending to that URL
There are two problems:
Your servlet maps to the URL /ValidationServlet and your form has the action set to ServletValidation.
Maybe your login.jsp isn't at the same level of your servlet mapping.
The best solution would be setting the action of your form to map the full URL that maps to your servlet. This can be achieved using Request#getContextPath():
<form action="${request.contextPath}/ValidationServlet" ...>
<!-- content... -->
</form>
If you don't use JSTL in your project, then do it. You should avoid scriptlets in your jsp (those <% ... %> tags that hold nasty Java code inside the JSP). But if you don't, then you should try the following:
<form action="<%=request.getContextPath()%>/ValidationServlet" ...>
<!-- content... -->
</form>
Still, the first way is the best to go.
More info:
How to avoid Java Code in JSP-Files?
Our JSTL wiki page
Just change the web.xml file
<url-pattern>/ServletValidation</url-pattern>
ServletValidation is different from ValidationServlet.

How do I pre-fill text fields in a form with info from a database in a .jsp?

I'm trying to create a form that updates an entry in a MySQL database. The table is a users table that contains various fields related to the user. I need this page to work as an update form that takes a username that is passed to it via the previous page and pre-fills the text fields with the existing data. It's a model one application that uses a presentation, transport, and data layer. The transport layer is User.java and the data layer (that interacts with the database) is UserDB.java.
Here's the code, everything is functional except the pre-filling.
UPDATE: I've edited to reflect the changes from the answers below, I also want to note that "UserDB.getUsers()" returns an ArrayList.
<%# page language="java" contentType="text/html; charset=iso-8859-1"
pageEncoding="ISO-8859-1" import="java.util.ArrayList,beans.*,data.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
//get parameters from the request
String userName = request.getParameter("userName");
ArrayList userList = UserDB.getUsers(userName);
User user = userList.get(0);
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="styles/style.css" type="text/css" />
<title>User Admin</title>
</head>
<body>
<div id="main">
<h1>Update User</h1>
<h3>User Info</h3>
<hr>
<div id="content">
<form action="updateUser.jsp" method="get">
<p>User Name<br>
<input type="text" name="userName" size="20" value="<%=userName%>"/>
</p>
<p>Password<br>
<input type="text" name="password" size="20" value="<%=user.getPassword()%>"/>
</p>
<p>First Name<br>
<input type="text" name="firstName" size="20" value="<%=user.getFirstName()%>"/>
</p>
<p>Last Name<br>
<input type="text" name="lastName" size="20" value="<%=user.getLastName()%>"/>
</p>
<p>Email Address<br>
<input type="text" name="email" size="20" value="<%=user.getEmail()%>"/>
</p>
<p>
<input type="submit" value="Commit Update">
</p>
</form>
</div>
</div>
</body>
</html>
I know I'm doing something wrong with the "user" object, but I'm overlooking it.
you are passing the username as a string
<%
//get parameters from the request
String userName = request.getParameter("userName");
user = UserDB.getUsers("userName");
//it should be (with out the quotes
user = UserDB.getUsers(userName);
%>
The "username" should have the quotes removed. Also, where are you declaring user's type?
ie.
User user = ....getUser..

Categories