There is a scenario in which I am having a form which is shown from my application as a pop up dynamically for various events. I am filling up the form and submitting it which causes session expiry.
I found out that when printing the values of the request headers in the form, i see that the jsession id is missing or sometimes new jseesion id is created.
This is not happening frequently. In working cases I am not missing any jsession id or getting differnt jseesion id's.
Any suggestions?
Below is the code sample.
<HTML>
<HEAD>
</HEAD>
<%
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements())
{
String headerName = headerNames.nextElement();
String headerValue = request.getHeader(headerName);
System.out.println("Header Name " +headerName );
System.out.println("headerValue " +headerValue );
}
%>
<body>
Comments </br>
<form name = 'savefrm' action ='save.jsp'>
<textarea name = 'comments' id = 'text' cols=38 rows=8>"+comments.trim()+"</textarea>
<input type="submit" value="ok"/>
</form>
</body>
</html>
You should set your session timeout through web.config like this:
<configuration>
<system.web>
<sessionState timeout="100000"></sessionState>
</system.web>
</configuration>
1000 ms = 1 second
On web.xml file :
<web-app>
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
20 = 20 minutes
Or you can do it inside the code :
HttpSession session = request.getSession();
session.setMaxInactiveInterval(20*60);
20 * 60 = 20 minutes
Related
I would like to create a form for a patient database system. Then I will give some input data to each textbox of the form and the data will be stored in a MySQL database.
I wrote a JSP file as follows
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
<tr><td>Address</td><td><input type="text" name="patientaddress" ></td></tr>
<tr><td>Phone number</td><td><input type="number" name="Ph" required /></td></tr>
<tr><td>Email</td><td><input type="email" name="email" required /></td></tr>
<tr><td>Type</td><td><input type="text" name="patienttype" ></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="register"></td></tr>
</table>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitalm","root","1234");
out.println ("database successfully opened.");
String sql = "INSERT INTO patient (pid, pname, address, phone, email_id,ptype) values (?, ?, ?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, Pid);
statement.setString(2, Name);
statement.setString(3, "Forrest");
statement.setDouble(4, 664208158);
statement.setString(5, "ava#gmail.com");
statement.setString(6,"G");
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("One row inserted.");
}
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
%>
</body>
</html>
This two lines throw error
statement.setString(1, Pid);
statement.setString(2, Name);
If I input some values like 'p101' for Pid and 'John' for Name then I can easily entered a record on the database hospitalM.
But if I try Pid and Name which are the variable names for table,
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
I got error.
How could I solve this?
JSP does not automagically bind request parameters in to Java variables, which is what you're trying to do here.
In order to get the parameters, you need to query the request object directly. Something akin to:
statement.setString(1, request.getParameter("Pid"));
statement.setString(2, request.getParameter("Name"));
Addenda:
Regarding double (or other non-strings), there's two things you can do.
One, you can convert them on the fly:
statement.setDouble(4, Double.parseDouble(requests.getParameter("phone")));
Second, you can rely on the SQL driver to do it for you.
statement.setString(4, requests.getParameter("phone"));
The "setXXX" in JDBC is based on the value that you're setting, NOT the data type of the column in the database. Inevitably, most of the time, whatever you set in the JDBC statement is going to be turned in to a string before being shipped up to the DB anyway. So, you can just use setString and be done with it and let the driver/db figure it out.
Either way, if you send in badly formatted data (i.e. "Tom" for the phone number), you're going to get an exception, either from the Double.parseDouble or when the DB tries to convert it during the insert. But that's a separate issue from simply setting parameters.
I like to create a registration form where user can register his or her data and the given data will be saved on a database. I created a database HospitalM using mysql workbench 8.0. I ran the project, the jsp file for form creation on Tomcat server. The pid is a primary key in the table called patient in the database HospitalM.
When I run the form on server a form generated but the form did not wait for input data and throw a message SQLException caught: Column 'pid' cannot be null.
I will share my code and the form in the below. Can any one give me some hints why it did not work?
JSP code: (name of the jsp file insert.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
<tr><td>Address</td><td><input type="text" name="patientaddress" ></td></tr>
<tr><td>Phone number</td><td><input type="number" name="Ph" required /></td></tr>
<tr><td>Email</td><td><input type="email" name="email" required /></td></tr>
<tr><td>Type</td><td><input type="text" name="patienttype" ></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="register"></td></tr>
</table>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitalm","root","1234");
out.println ("database successfully opened.");
String sql = "INSERT INTO patient (pid, pname, address, phone, email_id,ptype) values (?, ?, ?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, request.getParameter("pid"));
statement.setString(2, request.getParameter("pname"));
statement.setString(3, request.getParameter("address"));
statement.setString(4, request.getParameter("phone"));
statement.setString(5, request.getParameter("email_id"));
statement.setString(6,request.getParameter("ptype"));
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("One row inserted.");
}
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
%>
</body>
</html>
The sql query for patient table:
create table patient(pid varchar(10),
pname varchar(40) not null,
address varchar(10),
phone numeric(10,0) not null,
email_id varchar(20) not null,
ptype varchar(2),
primary key(pid),
check(email_id like '%_#__%.__%'));
The output that I got
The problem here is that when you first access the page, all of that code gets executed, but there was no request to process.
So, during the first access, all of those request parameters are null.
As suggested by Piotr, you could use the request method to get for whether it's a GET or a POST, and only execute the code on the POST.
The proper answer to that goes much deeper into how these kinds of things are architected along with the page workflow, but that's a much deeper topic that to go in to here.
For now, the simple issue is that on the first access, there are no parameters, so you're essentially trying to do:
statement.setString(1, null);
Which is illegal (to set a column to an explicit SQL NULL value in JDBC, you use the statement.setNull(1) method).
This is my code:
AdminDelete.jsp:
<%# page import ="java.sql.*" %>
<%
String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub",
"root", "root");
Statement st = con.createStatement();
int t= st.executeUpdate("DELETE * FROM post WHERE(uid like'"+uid+"' AND content like'"+content+"')");
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
this is in the Admin's index:
<form method="send" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<% String content = request.getParameter("content");%>
<input type="button" value="delete" id="content">
</form>
I am trying to make a button that when i'm clicking on it, it delete's all of the posts in my website but when i click it, it dosen't do anything
I can not write entire answer in comment. So writing answer. As I mentioned in comment. You need to add space after LIKE. Also using PreparedStatement.
<%# page import ="java.sql.*" %>
<% String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub", "root", "root");
PreparedStatement ps = con.prepareStatement("DELETE FROM post WHERE uid like ? AND content LIKE ?");
ps.setString(1, "%" + uid + "%");
ps.setString(2, "%" + content + "%");
int t= ps.executeUpdate();
try {
con.close();
} catch(Exception e) {
e.printStackTrace();
}
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
One thing to note here is that you need to verify the UID is set in session and content is set in request parameters.
Also you have used method="send". Instead use method="POST".
<form method="POST" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<input type="text" name="content" />
<input type="submit" value="Delete" />
</form>
Suppose one record in DB has UID containing letter a and corresponding to this record content has value containing b. Now submit data with b as input in form and make sure UID in session has value set to a. It should work. If you come up with any error message let me know.
Given that a page http://test.intra has the following form code:
<form>
<textarea id="description" name="description"><p>Hello</p></textarea>
<input type="submit" name="submit_save" id='submit_btn' value="Save">
</form>
description field is submitted on browser with value <p>Hello</p>
But using the following code:
$crawler = $client->request('GET', 'http://test.intra');
/* $client is a instance of \Symfony\Bundle\FrameworkBundle\Client ]
* $crawler is a instance of \Symfony\Component\DomCrawler\Crawler
*/
$domForm = $crawler->filter('form');
$domForm = $domForm->selectButton('submit_btn');
$this->client->submit($form);
description field is submited with value <p> </p>
Should client [\Symfony\Bundle\FrameworkBundle\Client] decode form data before submit is called? Am I missing something?
Thanks
I'm not totally sure what you are asking, but I noticed your code wasn't correct.
$crawler = $client->request('GET', 'http://test.intra');
$domForm = $crawler->filter('form')->form();
$crawler = $this->client->submit($domForm);
Now you'll be able to check your asserts on $crawler.
$this->assertTrue($this->client->getResponse()->isSuccessful());
If I have a form on a JSP like this:
<form action = "/myApp/myServlet?rssFeedURL=${rssFeedURL}' />" method = "post">
<input type = "button" value = "See data for this RSS feed."/>
</form>
What I find is that if the variable ${rssFeedURL} has no query string, then the server receives it properly, e.g.:
http://feeds.bbci.co.uk/news/rss.xml
But if a query string exists, e.g.:
http://news.google.com/news?ned=us&topic=m&output=rss
I expect that it is to do with the encoding of the '&' character. Can anyone advise?
The server receives only:
http://news.google.com/news?ned=us
My pages are charset=UTF-8 encoded.
You need to URL-encode request parameters. Otherwise they will be interpreted as part of the initial request URL.
JSTL offers you the <c:url> for this.
<c:url var="formActionURL" value="/myApp/myServlet">
<c:param name="rssFeedURL" value="${rssFeedURL}" />
</c:url>
<form action= "${formActionURL}" method="post">
...
An alternative is to create an EL function which delegates to URLEncoder#encode().