I am doing one small requirement on servlet and jsp.
servlet will contain variables id,name,email,gender. some times the values will be null.
Some times the values of the varaible are null. For example id and name are containing the values 1123 and pratap.
response.setContentType("text/html;charset=UTF-8");
try {
//TODO output your page here
RequestDispatcher view = request.getRequestDispatcher("registration.jsp");
view.forward(request, response);
request.setAttribute("id","value");
} finally {
}
my jsp page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="GET" action='registration1'>
<input type="text" name="address"/>
<input type="text" name="phoneno"/>
<input type="text" name="pincode" />
<label>${id}</label>
<input type="submit"/>
</form>
</body>
</html>
so that the control is going to registration.jsp
In registration.jsp i should get the text boxes for email and gender and for the id and name i should get the values in the text boxes such that the user can not change those values.(because those are already filled and proved to be correct.)
for the above jsp i tried with id but i am unable to see the id value in jsp.
how to pass those varaibles to the text boxes of the jsp and making the prompt to enter the values if the value is null.
Thank you..
You need set values as request attributes in Servlet and get them in JSP.
After getting them in JSP, Check accordingly and enable /disable the form controls.
Servlet:
request.setAttribute("phoneno","9998386033");
JSP:
<%
String phoneno=null;
if(request.getAttribute("phoneno")!=null)
phoneno = request.getAttribute("phoneno").toString();
%>
<% if(phoneno!=null) {
out.println("<INPUT TYPE=\"text\" name=\"phoneno\" value=\""+phoneno+"\" disabled=\"disabled\" ");
} else {
out.println("<INPUT TYPE=\"text\" name=\"phoneno\" ");
}
%>
FOR JSP EL
<c:if test="${empty phoneno}">
<INPUT TYPE="text" name="phoneno" value="${phoneno}" disabled="disabled"/>
</c:if>
<c:if test="${not empty phoneno}">
<INPUT TYPE="text" name="phoneno"/>
</c:if>
Related
I am making a job search web application using java. I have alotted a job id to each job and i am displaying the list of jobs in a bootstrap table from database. on each button click i need to forward this job id to a jsp page where i am adding the applicant name to the database corresponding to the jobs.My code is:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="com.dbutil.CrudOperation"%>
<%# page import="java.util.*,java.sql.*" %>
<%# page import="javax.servlet.http.HttpSession" %>
<html>
<head>
<title>Job List</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/jobs.css">
<script src="jquery.js"></script>
<script src="bootstrap.min.js"></script>
</head>
<body data-spy="scroll" data-target=".navbar" data-offset="50">
<% Connection con = null;
ResultSet rs = null,rs1=null;
PreparedStatement ps = null;
HttpSession hs = null;
hs=request.getSession();
con = CrudOperation.createConnection();
%>
<div class="container">
<%String strsql = "select * from postjob1 where sr>0";
try {
ps = con.prepareStatement(strsql);
rs = ps.executeQuery(); %>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Job Id</th><th>Job Category</th><th>Available Posts</th><th>Required Qualifications</th><th>Salary Details</th><th>Location</th><th>Last date of application</th><th></th>
</tr>
</thead>
<% while (rs.next()) {
%>
<tbody>
<tr><td><%=rs.getString("id")%></td><td><%=rs.getString("jobcategory")%></td><td><%=rs.getString("available")%></td><td><%=rs.getString("requiredqualification")%></td><td><%=rs.getString("salarydetails")%></td><td><%=rs.getString("location")%></td><td><%=rs.getString("lastdate")%></td><td><button type="button" class="btn btn-primary" onclick="<% hs.setAttribute("ID",rs.getString("id")); %>" >View Details </button></td></tr>
</tbody>
<%}
} catch (SQLException se) {
System.out.println(se);
}%>
</table>
</div
</div>
</body>
</html>
I am facing difficulty when I am retreiving the session value ID in other jsp page as i am getting id of the last row in the table irrespective of whichever button i click.Kindly help me run my code.Thanks!
<% hs.setAttribute("ID", rs.getString("id")); %>
In the excerpt above, you are setting the session attribute "ID". After executing the while loop, it stores the last "id" value. The same value is recovered in the destination page, whichever the clicked link.
A possible solution is passing the id in the invoked URL to the following page.
<a href="jobDetails.jsp?idJob=<%=rs.getString("id")%>">
<button type="button" class="btn btn-primary">View Details</button>
You can recover the parameter in jobDetails.jsp using
request.getParameter("idJob")
Note: I'm a bit rusty in JSP. Maybe I've forgotten a quote or something, but that's the idea.
You can pass job id like request's parameter.
For example you can call your jsp-page like that:
<a href="jobDetails.jsp?job_id=3" />
Where job_id is a parameter name and 3 is its value.
After that you can read parameter's value in your jobDetails.jsp in next way:
<%=request.getParameter("job_id")%>
I am trying to store the data from jsp page,which has many fields like
type of service
online
offline etc ,based on the selection it has to write the data to the file,
now I am able to store statically where it is storing the selection value and null value for not selected values.
Thanks
i undestand what you are trying to say . find out the code . one JSP is used for Text field and another JSP is used for Storing input field value on text file .
<HTML>
<HEAD>
<TITLE>Please Sign My Guest Book!</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1>Please Sign My Guest Book!</H1>
<FORM ACTION="basic.jsp" METHOD="POST">
Your name:
<INPUT TYPE="TEXT" NAME="TEXT1">
<BR>
<BR>
<BR>
Your comments:
<BR>
<TEXTAREA NAME="TEXTAREA1" ROWS="5" COLS="50"></TEXTAREA>
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit"><INPUT TYPE="RESET" VALUE="Reset">
</FORM>
</CENTER>
</BODY>
and For Storing Input Filed value on Text File .
<%# page import="java.io.*" %>
<HTML>
<HEAD>
</HEAD>
<BODY>
<H1>Thanks for Adding to the Guest Book!</H1>
Here's what you and others have said:
<BR>
<BR>
<%
String name = request.getParameter("TEXT1");
String text = request.getParameter("TEXTAREA1");
String file = application.getRealPath("/") + "test.txt";
FileWriter filewriter = new FileWriter(file, true);
filewriter.write("<B>Name: </B>" + name + "<BR>");
filewriter.write("<B>Comments: </B><BR>");
filewriter.write(text + "<BR><BR>");
filewriter.close();
%>
<jsp:include page="ch15_04.txt" flush="true"/>
</BODY>
Happy to Help Feel free to give your opinion .
I have a jsp web application, When i try to deploy it to tomcat server, and try to run the application from different machines, i dont get new pages for every user.
My application takes input from html input and keep it in the memory with the press of the button, ao actually i push the values in the memory and keeps it untill reset is pressed.
The problem comes when i goto another machine and run that application, all i get is the same modified page from that previous user.
I have used session management to keep username in the session.
But as if my application is not creating a new session for every new user request.
eg:
main.jsp has some input fields and when i click 'add' those values from html input is stored in memory objects, and is showed in the html inputs till the memory is not cleared.
Now from another machine, i access this application and go to main.jsp, there i get prefilled html input boxes.
why am i not getting a new page everytime i go from a different machine.
Is tomcat server serves all users from same memory space?
Sample code for main.jsp
<%# page import="test.DatabaseAccessConnectionManager" %>
<%# page import="test.FunctionKeywordManager" %>
<%# page import="test.TestScenarioManager" %>
<%# page import="test.DataParameter" %>
<%# page import="test.RepositoryManager" %>
<%# page import="java.util.ListIterator"%>
<%# page import="java.util.*"%>
<%# page import="java.sql.ResultSet"%>
<%# page import="test.TestCase" %>
<%# page import="test.ReportGenerator" %>
<jsp:useBean id="connn" scope="session" class="test.DatabaseAccessConnectionManager"></jsp:useBean>
<jsp:useBean id="connn1" scope="session" class="test.FunctionKeywordManager"></jsp:useBean>
<jsp:useBean id="connn2" scope="session" class="test.TestScenarioManager"></jsp:useBean>
<%
String Username=null;
String projectName = null;
if(session.getAttribute("Username")!=null)
{
Username = session.getAttribute("Username").toString();
projectName = session.getAttribute("ProjectName").toString();
}
else
{
response.sendRedirect("Login.jsp");
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Scenario Management</title>
<script src="static/js/jquery-2.1.3.min.js"></script>
<script src="static/js/script.js"></script>
<link rel="stylesheet" type="text/css" href="static/css/style.css">
<!-- <script>
function displayMessage(strMessage) {
alert(strMessage);
};
</script> -->
</head>
<body>
<div id="parameterPopup">
<div class="heading">Enter Parameter Values</div>
<br>
<div class="content"></div>
<br>
<div class="buttons">
<input type="button" value="submit values" id="btnSubmitParams" />
</div>
</div>
<div id="wrapper">
<div id="userInfonLogout">
<p>Welcome <b><%=Username %></b></p>
<center><a href="Logout.jsp" >logout</a></center>
</div>
<div id="topheader">
<div id="logo">
<img src="static/images/CS_200px.png"/>
</div>
<center><div id="headertext"><h1>Data Validation Automation</h1></div> </center>
</div>
<div id="navigation">
<ul>
<li>Home</li>
<li>Projects</li>
<li>Repository</li>
<li>Create Test Scenario</li>
<li>Maintain Test Scenarios</li>
<li>Configuration</li>
</ul>
</div>
<div id="body">
<div id="popup" style="display:none">
<div class="content">
</div>
<input type="button" class="close" value="close"/>
</div>
<h2>
<p align="center">
Create Test Scenario</p></h2>
<%!
FunctionKeywordManager objFunctionKeywordManager;
List<String> listKeywords;
TestScenarioManager objTestScenarioManager;
ReportGenerator objReportGenerator=new ReportGenerator();
public void jspInit(){
objFunctionKeywordManager = new FunctionKeywordManager();
listKeywords = objFunctionKeywordManager.getAllFunctionKeyword();
objTestScenarioManager = new TestScenarioManager();
}
%>
<%
RepositoryManager objRM = new RepositoryManager();
List<String> listRepo = objRM.getRepositoryListForProject(projectName);
%>
P.S: A newbie to jsp and tomcat.
Thanks in advance.
I Want to pass my text box values in the jsp through hyperlink .both the text box and Hyperlink are in the same jsp page.How can i achieve this
use <a> tag & using QueryString pass the value of textbox to other JSP page.
<a href="pass.jsp" onclick="addTextBoxData(this)">
<script>
function addTextBoxData(e){
e.href = e.href + "?textbox=" + document.getElementById('textboxID').value;
}
</script>
you just need to pass reference of tag using this.
then it ll append data ?textbox=textbox value
so it ll be /pass.jsp?textbox=txt
You use GET method, for example, Create file index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form method="get" action="index.jsp">
<table>
<tr>
<td><label for="txtUserName">Username: </label></td>
<td><input type="text" id="txtUserName" name="txtUserName"/><br/></td>
</tr>
<tr>
<td><label for="emailUser">Email: </label></td>
<td><input type="email" id="emailUser" name="emailUser"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
Go to: http://localhost:8080/index.jsp (I use default port 8080 with Tomcat)
When enter
username: myname
email: myname#example.com
and press Submit button. See browser's address bar:
http://localhost:8080/index.jsp?txtUserName=myname&emailUser=myname%40example.com
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I've written the below JSP. Now I want to make it into a MVC pattern, could you please help me how to do it?
<%#page import="java.util.Date"%>
<%#include file="DBCon.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>
<script language="javascript">
function UnBloc1(test){
var temp3id= 'temp3' + test;
var temp4id= 'temp4' + test;
//alert(temp3id);
document.getElementById(temp3id).style.display='block';
document.getElementById(temp4id).style.display='block';
}
function invoke(but1)
{
//var x=document.getElementById("temp3"+but).value;
//alert(x);
document.abc.action="Up_Query_DB.jsp?val1="+but1;
document.abc.submit();
}
function invoke1(but)
{
document.abc.action="Users_2.jsp?val="+but;
document.abc.submit();
//var t=document.getElementById("ab")+z;
//alert(t);
}
</script>
</head>
<body>
<form name="abc" method="post" action=""><table>
<%
try
{
String s=(String)session.getAttribute("muusername");
int i=0;
int temp=0, temp1=0,temp2=0, temp3=0, temp4=0;
ps=con.prepareStatement("Select DBID,Query_Raised,TR from Scope2 where TR!='null' AND (Query_Answered is null OR Count1 is null) And Specialist='"+s+"'");
rs=ps.executeQuery();
out.println("<b>QueryRaised</b>");
while(rs.next())
{
i++;
%>
<tr>
<td><input type="text" value="<%=i%>" name="id1" id="id1"></td>
<td><center><input type="text" value="<%=rs.getString("DBID")%>" readonly id="abc<%=i%>" name="abc<%=i%>" size="100"></center></td>
<td><input type="Submit" value="Resume" name="temp1<%=i%>" id="temp1<%=i%>" onclick="invoke1(<%=i%>)"></td>
<td><input type="button" value="Update Answer" name="temp2<%=i%>" id="temp2<%=i%>" onClick="UnBloc1(<%=i%>)"></td>
<td><input type="text" name="temp3<%=i%>" id="temp3<%=i%>" style="display: none"/></td>
<td><input type="Submit" value="Submit Answer" name="temp4<%=i%>" id="temp4<%=i%>" style="display: none" onClick="invoke(<%=i%>)"/> </td>
</tr>
<% }
}
catch(Exception e)
{
out.println(e);
}
%>
</table>
</form>
</body>
</html>
Let's say you go to the database and get a list of objects that contain few attributes (with setter and getter methods), among them, the dbid attribute. The object would be your model. Let's call it myBean.
The Java class from you will do the query will be the Controller class. Let's call it myController. So, the controller should: 1. Get the list of objects you need. 2. Do anything that should be done before representing the information (in your case, I would say nothing) and 3. pass the information to the JSP through the list of your beans setting the information in the request so the information can be displayed.
Your JSP, now, should look like this:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# 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>
<script language="javascript">
...
</script>
</head>
<body>
<form name="abc" method="post" action="">
<table>
<c:forEach var="myItem" items="${listDbid}" varStatus="i">
<tr>
<td><input type="text" value="${i.count}" name="id1" id="id1"></td>
<td><center><input type="text" value="${myItem.getDbid}" readonly id="abc${i.count}" name="abc${i.count}" size="100"></center></td>
<td><input type="Submit" value="Resume" name="temp1${i.count}" id="temp1${i.count}" onclick="invoke1(${i.count})"></td>
<td><input type="button" value="Update Answer" name="temp2${i.count}" id="temp2${i.count}" onClick="UnBloc1(${i.count})"></td>
<td><input type="text" name="temp3${i.count}" id="temp3${i.count}" style="display: none"/></td>
<td><input type="Submit" value="Submit Answer" name="temp4${i.count}" id="temp4${i.count}" style="display: none" onClick="invoke(${i.count})"/> </td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
So, basically, you need to remove from your JSP all the code that is not "view", take it to a "controller" and use a "model" for sending the information from the "controller" to the "view".
Also
You should avoid scriptles (<% %>) in your JSP, better to use JSTL and others similar tools. If you do it, probably your JSP will not have "controller" code.
I recommend you to use a MVC framework, like Spring MVC or Struts, among others.
It is also nice if you create another layer in your code just for database access. This database layer will be used by the controllers so the controllers. You can reuse code, make controllers independent of database and keep them clearer.
I am new too MVC as well, but I can suggest you some tips. Make a bean. Beans are Java class with getter and setter. In your case the bean would be
public class Scope2
{
String dbID;
//all other attributes of the table.Beans should be reusable so usually there is only one bean for one corresponding table
public String getDBID()
{
return dbID;
}
public void setDBID(String dbId)
{
this.dbId=dbId;
}
//Other getters and setters for all other attributes
}
Now make a class that would perform database query. And return bean Scope2 from that class to jsp. And in your jsp you will simply print the values as out.println(bean.getDBID());