I want to execute an SQL query in JSP. The display must be in JSP code, not in java.
I cannot introduce JSP code in a java page.
package tn.com.tradenet.utilisateur;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Modification extends HttpServlet
{
public void doPost()
{
try
{
String id ="1"; //request.getParameter("userName");
String nom ="mecchlaoui"; //request.getParameter("userName");
String prenom ="fawzia"; //request.getParameter("userName");
String email ="hotmail"; //request.getParameter("password");
String profil ="fawzia"; //request.getParameter("password");
String login ="fawzia"; //request.getParameter("password");
String pass ="1258"; //request.getParameter("password");
ConnectionBD mod = new ConnectionBD();
//String sql="SELECT id FROM utilisateur";
//ResultSet res=mod.execMonSQl(sql);
//while (res.next())
//{
//id = res.getString(1);
//}
mod.execMonUpdate("UPDATE utilisateur SET nom='"+nom+"',prenom='"+prenom+"', email='"+email+"', profil='"+profil+"',login='"+login+"',pass='"+pass+"' WHERE 'id'='"+id+"'");
System.out.println("element ajoutté");}
catch(SQLException s)
{
System.out.println("erreur" +s);
}
}
public static void main(String[] args) {
Modification mdf =new Modification();
mdf.doPost();
}
}
You need to override the real HttpServlet#doPost() method, not to add another one which won't be invoked by the servletcontainer.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Do your job here.
}
And you need to map this servlet in web.xml on a known URL pattern.
<servlet>
<servlet-name>modification</servlet-name>
<servlet-class>com.example.Modification</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>modification</servlet-name>
<url-pattern>/modification</url-pattern>
</servlet-mapping>
With the above <url-pattern> the servlet will listen on URL http://example.com/context/modification.
Finally change the HTML form action URL in your JSP so that it matches the servlet URL.
<form action="modification" method="post">
See also:
Servlets tag info page - How servlets work and a little Hello World
Unrelated to the concrete question/problem, note that you still need to change your servlet code to display some result page in flavor of a JSP. E.g.
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
Also, the main() method inside the servlet makes no sense, remove it. Last but not least, your SQL approach is sensitive to SQL injection attacks. Learn PreparedStatement.
Related
indexrk.jsp
if(doc.data().disease=="" && (doc.data().test!="exit site" || doc.data().test!="exit" || doc.data().test!="Exit Site") ){
cell5=row.insertCell(6);
cell5.innerHTML="<form method='post' target='tabCalc' action='ImageCalc'><input type='hidden' name='test' id='test' value="+doc.data().test+"><input type='hidden' name='latestsample' id='latestsample' value="+doc.data().image.toString()+"> <input type='hidden' name='samid' id='samid"+rownum+"' value="+doc.id.toString()+"><input type='hidden' name='patpat' id='patpat"+rownum+"' value="+doc.data().Patient.toString()+"><input type='hidden' name='colorvol' id='colorvol"+rownum+"' value="+doc.data().colour.toString()+"> <input type='submit' onclick='act()' value='Calculate' class='btn editbtn' id='b"+rownum+"'> </form>";
cell5.style.width="100px";
row.style.background="#b7daa4";
}
ImageCalc.java
package com.example.servlet;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
#WebServlet(
name = "ImageCalc",
urlPatterns = "/ImageCalc"
)
public class ImageCalc extends HttpServlet{
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String[] answer;
String image = req.getParameter("latestsample");
//String DocId=req.getParameter("dropDownDest");
String sampleId=req.getParameter("samid");
String colorvol=req.getParameter("colorvol");
String type=req.getParameter("test");
System.out.println("vgierfvbierfvieufbeuj "+type);
//req.setAttribute("name",DocId);
if(type.equalsIgnoreCase("pdbag") ||type.equalsIgnoreCase("cloudy bag")) {
Patients p=new Patients();
try {
p.patients(image.toString());
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.setAttribute("hexval",p.gethexval());
req.setAttribute("color"," ");
req.setAttribute("disease",p.getinterpretation());
req.setAttribute("id",sampleId);
p.clearall();
}
else if(type.equalsIgnoreCase("volume")) {
int voltype=Integer.valueOf(colorvol);
Volume v=new Volume();
String fvol="";
try {
fvol = Volume.vol(image.toString(),voltype);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
req.setAttribute("id",sampleId);
req.setAttribute("color", colorvol);
req.setAttribute("hexval","---");
//req.setAttribute("color","not required");
req.setAttribute("disease",fvol);
//req.setAttribute("disease",p.getinterpretation());
}
else if(type.equals("Exit site")|| type.equals("exit")) {
req.setAttribute("hexval","---");
req.setAttribute("color","---");
req.setAttribute("disease","---");
req.setAttribute("id",sampleId);
}
RequestDispatcher view = req.getRequestDispatcher("res.jsp");
view.forward(req, resp);
}
}
Error Message
HTTP Status 404 – Not Found
Type Status Report
Message /WebProject/ImageCalc
Description : The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
My thoughts:
The error is probably due to the path. Since the servlet is at location WebProject/src/com/example/Imagecalc. But I don't know how to set the right URL.
Your web.xml may be incorrect.
The correct web.xml should be according to your project :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>imageCalc</servlet-name>
<servlet-class>com.example.servlet.ImageCalc</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageCalc</servlet-name>
<url-pattern>/ImageCalc</url-pattern>
</servlet-mapping>
</web-app>
Try to hit the URL on the browser: http://localhost:8080/WebProject/ImageCalc -the browser should open based on the GET/POST request.
PrintNamesServlet.java:
This servlet prints the entered name of the user
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "PrintNamesServlet")
public class PrintNamesServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Ram Dhakal");
}
}
CounterServlet.java:
Counts the number of hits or visit in the page
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "CounterServlet") public class CounterServlet
extends HttpServlet {
int totalHits;
public void init() throws ServletException{
totalHits = 0;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("Total visit count: " + totalHits++);
} public void destroy(){
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>PrintNamesServlet</servlet-name>
<servlet-class>PrintNamesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PrintNamesServlet</servlet-name>
<url-pattern>/PrintNamesServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CounterServlet</servlet-name>
<servlet-class>CounterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CounterServlet</servlet-name>
<url-pattern>/CounterServlet</url-pattern>
</servlet-mapping>
</web-app>
I am getting error:
No webpage was found for the web address: http://localhost:8080/
As, I am trying to run the servlet for the first time, I am not getting what is wrong with my code. I typed http://localhost:8080/PrintNamesServlet in the url.
You have used Servlet 3.0 specification
Lets takes look at it
In Servlet 3.0, servlet metadata can be specified using #WebServlet
#WebServlet(name="mytest",
urlPatterns={"/myurl"})
public class TestServlet extends javax.servlet.http.HttpServlet {
....
}
In this way the servlet is accessed by using the url pattern specified in the annotation.
##WebServlet(name="mytest",urlPatterns={"/myurl"})
according to that servlet is acceseed using
http://localhost:8080/myurl
In you case you have only specified name you have to specify urlPatterns also, so you can able to call you servlet properly.
#WebServlet(name = "CounterServlet",urlPatterns={"/CounterServlet"}) public class CounterServlet extends HttpServlet {}
And you do not need to use web.xml file.
When you use annotations like this #WebServlet(name = "PrintNamesServlet") the web.xml mapping is not used.
You have to either remove these annotations or add urlMapping attribute to them.
I am having this little problem, I see that it is impossible to load picture in my console, I don't know how to solve the problem.
I am getting my image name from database as a String in my controller, just the name, something like that ' image.jpg' and it is stored in my folder 'images'.
Here is my jsp file :
<c:if test="${ !(post.cover == 'empty')}">
<div class="imgPub">
<img src="Assets/images/${post.cover }">
</div>
</c:if>
In my inspector i can see the whole src written exactly, but a message next to it saying impossible to load image.
Any help would be much appreciated.
HttpServlet will do the job.
use:
youraddress.xxx/images/filename.png
this is important #WebServlet("/images/*")
It will automatically leads to folder defined in PATH and retrieve the image based on the name.
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
#WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
public static final String PATH = "C:/"
/*
linux
public static final String PATH = "/home/images/"
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
File file = new File(PATH,filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length",String.valueOf(file.length()));
response.setHeader("Content-Disposition","inline; filename=\""+filename +"\"");
Files.copy(file.toPath(),response.getOutputStream());
}
}
I need to logout from dahboard.jsp and go to index.jsp but while I'm clicking the logout button it is showing the error message like this,
HTTP Status 404 - /Project/logout
type Status report
message /Project/logout
description The requested resource (/Project/logout) is not available.
Apache Tomcat/6.0.20
the dashboard.jsp and the servlets login and logout are posted below, what might be the error in that.
dashboard.jsp
<div class="ends">
<form action="logout" method="post" >
<input type="submit" value="logout">
</form>
</div>
servlet page login login.java
package com.signin;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import com.db.DBCon;
/**
* Servlet implementation class login
*/
public class login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uid=request.getParameter("uid");
String pwd=request.getParameter("pwd");
try {
DBCon dbc = new DBCon();
if(dbc.validateLogin(uid, pwd))
{
HttpSession session=request.getSession();
session.setAttribute("userid",uid);
response.sendRedirect("dashboard.jsp");
}
else
out.println("<center><h3>Sign in Failed!</h3><br><a href='index.jsp'>Go to Sign up page</a></center>");
dbc.closeCon();
}
catch(Exception e){ e.printStackTrace(); }
}
}
logout.java
package com.signin;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class logout
*/
public class logout extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession();
session.removeAttribute("userid");
session.invalidate();
response.sendRedirect("index.jsp");
}
}
Check your web.xml file whether you map your logout class correctly. The issue may be there. Otherwise share the full error description and web.
I wrote this little servlet, but it does not execute:
index.html
//Press button to call Servlet
<form method="post" name="postform" action="/WebApp/NewServlet">
web.xml
<servlet-name>NewServlet</servlet-name>
<servlet-class>javax.NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
NewServlet.java
//Servlet should execute keypress(just an example)
package javax;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class NewServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_L);
} catch (AWTException ex) {
}
}
}
It compiles without errors but does not execute, please help before Im get nuts.
Maybe Java does not allow this action on Servlets or on post-actions?
But maybe you know another similar but working way, even if its not java.
maybe something "easier".