I want to change the table from the page /manager/html/sessions of Tomcat.
The jsp file for that page is tomcatpath/webapps/manager/WEB-INF/jsp/sessionsList.jsp
I want to add a new column in table which contains the path of last page which client has requested.
Ex: if the last request of client is mydom.com/path/3, I want to show in table /path/3
This is the part where are iterated all sessions
<%
for (Session currentSession : activeSessions) {
String currentSessionId = JspHelper.escapeXml(currentSession.getId());
String type;
if (currentSession instanceof DeltaSession) {
if (((DeltaSession) currentSession).isPrimarySession()) {
type = "Primary";
} else {
type = "Backup";
}
} else if (currentSession instanceof DummyProxySession) {
type = "Proxy";
} else {
type = "Primary";
}
//I have problem getting the last accessed path by client.
String lastPath = ...;
%>
//html where is printed every row with data from session
//use here <%= lastPath %>
<%
} //end of for
%>
I don't know how to extract the last accessed path.
Tomcat version: Apache Tomcat/9.0.20
Related
I have my JSP that controls the frame behavior of my page as the following:
<%
print_header();
String especialidade = request.getParameter("especialidade");
String medico = request.getParameter("medico");
String paciente = request.getParameter("paciente");
String data_consulta = request.getParameter("data_consulta");
String convenio = request.getParameter("convenio");
if (especialidade == null) {
print_especialidade_form();
} else if(paciente == null) {
print_agendamento_form();
}
print_footer();
%>
I have the definition of the functions defined in the same JSP, delimited by <%! and %> tags, but the creation of the form, that happens inside of those functions, get executed even if the function isn't called like print_footer(); for instance.
I 'm used to programming in ASP and I could easily do these there, but I'm having a hard time migrating to JSP. What am I doing wrong?
i have a resultset. if result set is empty or null, then i want to set the value of "int b=0" in str16. And if the result set is not empty/find out something then execute the query. But i am facing some problem when the resultset is empty, then value is not setting in str16. What i did in my project is that after login i will show the total number of leave on employee profile if he took leave already. if employee did not take any leave then show 0 on the profile.
*checkleave.jsp *
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%
// storing the login id in abc becouse i have give table name as employee id
String abc= session.getAttribute("empid").toString();
%>
<%
try{
int b=0;
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery("select approcode,approemail,appromon,approvemon,approtue,approvetue,approwed,approvewed,approthr,approvethr,approfri,approvefri,approsat,approvesat,commen,months,SUM(nol) from `pushkalit`.`approval`WHERE (CONVERT( `approcode` USING utf8 ) LIKE '%"+abc+"%')");// here what i am doing that if employee login then check in approval table where is approcode column as employee id if find something then execute table if column is not there then put value of b(i have declared int b=0) in str16.
if(rs !=null)
{
if (rs.isBeforeFirst() && rs.isAfterLast())
{
session.setAttribute("str16",b);
}
else
{
while(rs.next())
{
String str=rs.getString("approcode");
String str1= rs.getString("approemail");
String str2=rs.getString("appromon");
String str3=rs.getString("approvemon");
String str4=rs.getString("approtue");
String str5=rs.getString("approvetue");
String str6=rs.getString("approwed");
String str7=rs.getString("approvewed");
String str8=rs.getString("approthr");
String str9=rs.getString("approvethr");
String str10=rs.getString("approfri");
String str11=rs.getString("approvefri");
String str12=rs.getString("approsat");
String str13=rs.getString("approvesat");
String str14=rs.getString("commen");
String str15=rs.getString("months");
String str16=rs.getString(17);
session.setAttribute("str16",str16);
}
}
}
else
{
session.setAttribute("str16",b);
}
}
catch(Exception e) {
System.out.println(e);
}
%>
but i am getting problem when employee login if column is empty then getting error. this is empprofile.jsp.it will come after login. this code i have put in empprofile.jsp
<%
String a = session.getAttribute("str16").toString();
int y = Integer.parseInt(a);
<tr><td><label>Total Leave Day:</label></td>
<td><%=y %></td>
%>
Methods like isBeforeFirst() and isAfterLast() are only required to work with scrollable result sets. If you want to be able to use all types of result sets and all JDBC implementations, then you have several options:
Define a boolean variable initially set to false, and set it to true in the while loop; base your decision on this while loop
Similar to one, but define an integer count instead
Check rs.next() and process the result using do ... while
I am developing a small application using spring mvc where I need to have option to delete each item from cart (in case customer feels he donot need after adding to cart).
I have got a "delete" button below each item item.(The items added are in a list).My pupose is when I click delete button against a particular item only that item should be removed from the cart.
I have written some code but it is remove lastest added items from cart and not required one.
I know my mistake but not able to proceed further.Here is what I implemented.
This is jsp :
<c:forEach items="${cart}" var="nextMovie">
<li>
<h2>${nextMovie.title}</h2>
</li>
<h2>Price</h2>
<h2>${nextMovie.price}</h2>
<c:set var="totalPrice" value="${0}" />
<c:forEach var="nextMovie" items="${cart}">
<c:set var="totalPrice" value="${totalPrice + nextMovie.price}"/>
</c:forEach>
<form method='post' action='<c:url value="removeFromCart.do"/>'>
<input type='image' src='Delete.png'/>
<input type='hidden' name='id' value='${nextMovie.id}'/>
</form>
</c:forEach>
This is my controller:
#RequestMapping("/removeFromCart")
public ModelAndView removeFromCart(HttpSession session) {
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
}
List<Movie> allMovies = cart.getAllItems();
for(int i= 0;i<allMovies.size();i++)
{
allMovies.remove(i);
}
return new ModelAndView("/cartContents.jsp", "cart", allMovies);
}
Please suggest me how I will be able to delete the element again the delete button from the list.
Thanks
Maruthi
[HttpPost]
[Route("~/CartDetail/DeleteCartDetail")]
public ActionResult DeleteCartDetail(CartDetailModel model)
{
var response = _cartDetailService.DeleteCartItem(model.Id);
return Json(new
{
success = response.Success,
message = response.Message
});
}
}
I am importing my data from service DeleteCartItem
Here is service code
public BaseResponse DeleteCartItem(int cartDetailId)
{
var response = new BaseResponse();
try
{
var itemCart = _context.CartDetails.FirstOrDefault(x => x.Id == cartDetailId);
if (itemCart == null)
{
response.Message = "This item does not exist in the cart.";
return response;
}
_context.CartDetails.Remove(itemCart);
_context.SaveChanges();
response.Success = true;
}
catch (Exception exception)
{
response.Message = "Some error occured : " + exception.ToString();
}
return response;
}
Your JSP has nested <c:forEach> tags, with both containing the same items expression. Either you don't need 2 of them of else you need to close the first one before starting the second.
Your application has some problems:
First, your problem is because you are using the same var attribute name, for your both foreach tags. The first tag defines an attribute named nextMovie in its scope, the second foreach which is nested within first, defines the same attribute name, and then iterates, so when its iteration completes, nextMovie will be last element in the list, so ${nextMovie.id} will be last element's id.
Second,
List<Movie> allMovies = cart.getAllItems();
for (int i= 0;i<allMovies.size();i++) {
allMovies.remove(i);
}
is equivalent of allMovies.clear(), isn't it? So you are removing all items form list, what else do you need?
Third, next problem is you have an object of type ShoppingCart in your session which is named cart, and you add an object of type List<Movie> to your model with the same name; although when EL processor tries to resolve a name request has a more priority than session, but believe me it is much better to rename one.
Forth, why are you calculating 'totalPrice' in each iteration? And what is its use?
I am trying to store the results of my query in a string, and print them to the bottom of my JSP page by passing that string to it. Right now, the JSP page displays fine initially, but nothing is happening when I click the button to post the command. Earlier when I accessed the servlet from an html page, and printed all my output to out using a PrintWriter, I got the results to display, but they would display on a separate page.
1) Is it a good idea to store out in this way, or should I make it something different than a string?
2) How do I get the results of the query to post to the JSP page?
databaseServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String out = "\n";
String query = request.getParameter("query");
if (query.toString().toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query.toString());
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.concat(metaData.getColumnName(i));
}
out.concat("\n");
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.concat((String) resultSet.getObject(i));
}
out.concat("\n");
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toString().toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query.toString()).executeUpdate(query.toString());
out = "\t\t Database has been updated!";
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out = "\t\t Not a valid command or query!";
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
dispatcher.forward(request, response);
request.setAttribute("queryResults", out);
}
}
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>This is the MySQL Servlet</h1>
<form action = "/database/database" method = "post">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<textarea name = "query" cols="20" rows="5"></textarea>
<input type = "submit" value = "Run MySQL Servlet" />
<input type = "reset" value = "Clear Command" />
</label>
</p>
</form>
<hr>
<%=
request.getAttribute("queryResults");
%>
</body>
</html>
dispatcher.forward(request, response);
request.setAttribute("queryResults", out);
It should be like this
request.setAttribute("queryResults", out);
dispatcher.forward(request, response);
Before the request is dispatched the attributes has to be set
1) Is it a good idea to store out in this way, or should I make it something different than a string?
Since this is tabular data, I'd use something that preserves that structure, so that the JSP can piece it apart easily for customized formatting. Bold headers, putting it in an HTML table and stuff. Either some custom bean, or maybe just a List<String[]>.
2) How do I get the results of the query to post to the JSP page?
What you are doing now (request.setAttribute) should work. However, you need to set the attribute before you forward the request.
You could then print the String you now have like this:
<%= request.getAttribute("queryResults") %>
Or if you go with a table-structure
<% List<String[]> rows = request.getAttribute("queryResults"); %>
and then loop over that.
1) Is it a good idea to store out in this way, or should I make it something different than a string?
NO. Don't mix the presentation logic in Java code. Leaverage your JSP for that purpose I would advice you to use JAVA objects and store the row wise values in one object instance. Put all the objects in a collection and use the same in JSP for display. Same goes with column names.
2) How do I get the results of the query to post to the JSP page?
In your current format of queryResults, just print the results using = operator or out.println method in your JSP as:
<hr>
<%=request.getAttribute("queryResults"); %>
or
<% out.println(request.getAttribute("queryResults"));%>
But if you decide t use collection as adviced in answer1, then get the collection back from the request, iterate and print the results, e.g. if you decide to use List<String[]> where String[] maps one row data then:
<TABLE id="results">
<% List<String> columns = (List<String>)request.getAttribute("queryColumns");
List<String[]> results = (List<String[]>)request.getAttribute("queryResults");
out.println("<TR>");
for(String columnName: columns ){
out.println("<TD>"+columnName+"</TD>");
}
out.println("</TR>");
//print data
for(String[] rowData: results){
out.println("<TR>");
for(String data: rowData){
out.println("<TD>"+data+"</TD>");
}
out.println("</TR>");
}
%>
</TABLE>
I just want to check that the parameter passed to the jsp are null or not using httpcontext so how i can able to do that
case_yr = Integer.parseInt(request.getParameter("case_yr"));
sub_type_int =Integer.parseInt(request.getParameter("sub_type_int"));
String case_num = request.getParameter("case_num");
String lang_mode = request.getParameter("lang_mode");
String mobile_no = request.getParameter("caller_id");
String dialled_id = request.getParameter("dialled_id");
i want to above values are valid or not I am submitting value from xml page to jsp page and getting value in jsp using request.getparameter()
so pleaase tell how to check values are null or not and there is no sevlet only vxml page and jsp page
Use JSTL
<c:if test="${not empty case_num}">
case_num is NOT empty or null.
</c:if>
if you wanna check if the request attributes are null,just check if they are null this way
String case_num = request.getParameter("case_num");
if(case_num!=null){
//do your logic
}
else {
System.out.println("case_num is null");
}
int number ;
String num = request.getParameter(num);
if(num!=null){
number = Integer.parseInt(num);
}
else {
System.out.println("case_num is null");
}