First of all, this might seem like a duplicate but I assure you I have tried many questions and still hasn't got a proper answer. So I'm asking this here.
I have an HTML form from which I would like to submit a query to a servlet and show the results in a different division.
My HTML code essentially consists of the following:
<form>
<input name="query" id="query" placeholder="Query">
<button id="searchDoc">Search</button>
</form>
<div id="search-results"></div>
I have the following jQuery in order to handle the ajax call.
$('#searchDoc').click(function() {
var q = $('#query').val();
$.ajax({
url: "QueryServlet",
data: {query:q},
success: function(data) {
alert("data: " + data);
$('#search-results').html(data);
}
});
});
My QueryServlet is:
#WebServlet("/QueryServlet")
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public QueryServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String query = request.getParameter("query");
QueryUtil qu = new QueryUtil();
String mySqlQuery = qu.buildMySQLSearchQuery(query);
System.out.println(mySqlQuery);
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
con = new DbConnection().getConnection();
st = con.createStatement();
rs = st.executeQuery(mySqlQuery);
if(rs != null) {
response.setStatus(HttpServletResponse.SC_OK);
while(rs.next()) {
out.println("" + rs.getString("fileName") + "");
}
} else {
// TODO add keywords to database
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Even when I submit a valid query, the div does not get loaded up with the data from the servlet. The data reaches the servlet and gets displayed in the console, but I am unable to retrieve that data from the script.
The <button> tag is equivalent to an <input type="submit"/>. If you in your form tag don't declare any action attribute, the standard action causes that the page is reloaded. This causes that, although the returned data are inserted in #search-results div, you'll never be able to see them, because the page is immediately reloaded.
You should deactivate the default "Submit" button this way:
$('#searchDoc').click(function(e) {
e.preventDefault();
[....]
});
This should fix your problem!
the issue seems related to context path, your path should look like this if servlet is not in context root :-
<host> / <context path>/ <servlet>
Thanks :)
Related
I have a Java Dynamic Web Project where one of the Servlets does the following:
/**
* Servlet implementation class DataAPIServlet
*/
#WebServlet(name = "data", urlPatterns = { "/data" })
public class DataAPIServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String format;
/**
* #see HttpServlet#HttpServlet()
*/
public DataAPIServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
format = request.getParameter("format").replaceAll("\"", "");
// create data model and add to request object
RequestDispatcher requestDispatcher = null;
if (format.equals(null)) {
requestDispatcher = jsonDispatcher(request);
response.setContentType("text/json");
} else {
System.out.println("SERVING FORMATTED DATA : " + format);
String returnString;
switch (format.toLowerCase()) {
case "xml":
returnString = Films.getFilmsXML();
request.setAttribute("data", returnString);
requestDispatcher = xmlDispatcher(request);
response.setContentType("text/xml;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
break;
case "csv":
returnString = Films.getFilmsCSV();
request.setAttribute("data",returnString);
requestDispatcher = csvDispatcher(request);
response.setContentType("text");
break;
case "json":
returnString = Films.getFilmsJSON();
request.setAttribute("data", returnString);
requestDispatcher = jsonDispatcher(request);
response.setContentType("text/json");
response.setContentType("text/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
break;
}
}
// Forward the request to the view
requestDispatcher.forward(request, response);
}
private RequestDispatcher xmlDispatcher(HttpServletRequest request){
return request.getRequestDispatcher("xml.jsp");
}
private RequestDispatcher jsonDispatcher(HttpServletRequest request) {
return request.getRequestDispatcher("json.jsp");
}
private RequestDispatcher csvDispatcher(HttpServletRequest request){
return request.getRequestDispatcher("csv.jsp");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doGet(request, response);
}
}
One of the servlets spits out the data in xml/json/csv format based on the url query (for exmaple /data?format=json will return json data for all the films in databse).
Through debug I have found that my JAXB/GSON methods are properly creating a data set from my model however when viewed in the response to the browser something is going wrong which likely looks like the HTML escape sequences for special characters such as "<" on xml tags.
This narrows it down to something to do with the "" method in JSTL.
My XML is displayed by the following jsp:
<%#page contentType="application/xml" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page trimDirectiveWhitespaces="true"%>
<c:set var="data" value="${data}"></c:set>
<c:out value="${data}" />
I can tell the data being passed by the response to the JSP is correct by debug :
Unless the issue with what I'm doing would be resolved by some better mechanism for serving the xml/json/csv data than simply serving it to a jsp file? suggestions welcome.
In the tag of JSTL set escapeXML to false in order to maintain the original characters. Otherwise escapeXML true will do the opposite.
<c:out value='${foo(someParameter)}' escapeXml="false"/>
This is the code (Validate.java Servlet File)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("u");
String password = request.getParameter("p");
Connection con = DBConnection.Connect();
String sql = "select *from users where name=? and pass=?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
request.getRequestDispatcher("WelcomeServlet").forward(request, response); //This line calls another servlet
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
WelcomeServlet.java Servlet File
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
response.setContentType("html/text");
PrintWriter pw = response.getWriter();
pw.write("<html><body>");
pw.write("<title>Welcome User</title>");
pw.write("<h1>" + username + "</h1>");
pw.write("</body></html>");
pw.close();
}
Output
I want the validate servlet to call welcome servlet but its asking me whether to download a validate servlet file .PFA for more details
I am getting the popup to download Validate Ser
The content type should be text/html (you wrote html/text) otherwise the browser does not know what to do with the file and asks for downloading it.
There are also a few other problems with the code worth mentioning
You do not really check the result from the DB, so you will forward even if the user does not exist.
You use the parameter name u in one servlet but username in the other.
The webapp I'm working on is running JSP and JAVA in the backed on Tomcat server.
How would it be possible to only allow each user to have only one session at a time, meaning not allowing any user to sign in more than one from same or other machine/browser.
The JSP client side:
<input type="text" name="uname" placeholder="Username"> <br>
<input type="password" name="pwd" placeholder="Password"> <br>
<input type="submit" value="Login">
<% String fail = request.getParameter("loginFailed");
if(fail != null && fail.equals("yes"))
{
out.println("<br><font color=\"red\"> Login failed</font>");
}
else if(request.getParameter("loggedOut") != null)
{
out.println("<br><font color=\"red\">You have been logged out.</font>");
}
%>
JAVA Part:
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String[] uname = request.getParameterValues("uname");
String[] pass = request.getParameterValues("pwd");
if( uname.length == 0 || pass.length == 0)
{
response.sendRedirect("/MASC/index.jsp?loginFailed=yes");
return;
}
UsersDB authdb = new UsersDB();
User authUser = null;
try {
authUser = authdb.auth(uname[0], pass[0]);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(authUser == null)
{
response.getWriter().append("not authenitacted");
Cookie authCookie = new Cookie("auth", "no");
response.addCookie(authCookie);
response.sendRedirect("/MASC/index.jsp?loginFailed=yes");
}
else
{
System.out.println("auth session " + authUser);
HttpSession session = request.getSession();
session.setAttribute("uid", authUser.getUid());
session.setAttribute("level", authUser.getLevel());
session.setAttribute("aeid", authUser.getAeid());
session.setMaxInactiveInterval(15*60);
response.sendRedirect("/MASC/welcome.jsp");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
Is there a way to store the logged in users, or create a new column in the database "Loggedin" and check for that column before allowing user to sign in? Or is there any more efficient way to implement that ?
First, you'd need to define what should happen when user logs in using a different session. Remember, if the user closed the browser, your server is not notified, so a new session can even be from a restart of the same browser.
Given that, I think the only way it makes sense, is to invalidate the existing session of the user, when the user logs in again.
To do that, you should create an application-scoped attribute (on ServletContext) with a map of user to active session. When logging in, you replace the current entry, if any. For every other access, if current session is not the active session, redirect to login page.
Create a map with userid as key and session object as value. Whenever a login request is received first check in this map the value corresponding to user id. If the value is not null, it means a session already exist for this user. So either invalidate the existing session and create a new one or use the previous one and display a message to user that user is already logged in. Point to note is that whenever a user log off, its entry in the map must be removed. You can use sessioncontextlistener for this.
i have the following pice of code 'anmelden.java':
#WebServlet("/anmelden")
public class anmelden extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String benutzer = request.getParameter("benutzer");
String passwort = request.getParameter("passwort");
try {
PrintWriter out = response.getWriter();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test","admin","*****");
PreparedStatement stmt = con.prepareStatement("SELECT benutzer,passwort,rolle FROM login WHERE benutzer = ? AND passwort = ?");
stmt.setString(1, benutzer);
stmt.setString(2, passwort);
ResultSet rs = stmt.executeQuery();
if(rs.next())
{
HttpSession session = request.getSession();
session.setAttribute("benutzer", rs.getString("benutzer"));
RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);
out.print("1");
}
else
{
out.print("Benutzername und/oder Passwort falsch");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my jsp file 'login.jsp':
$("#anmelden").click(function(){
var benutzer = $("#benutzer").val();
var passwort = $("#passwort").val();
if(benutzer == "" || passwort == "")
{
return;
}
$.ajax({
url:"anmelden",
type:"POST",
data:"benutzer="+benutzer+"&passwort="+passwort
}).success(function(data){
var erfolg = data;
if(erfolg == "1")
{
window.location.href="http://localhost:8080/PSD/mandant.jsp";
}
else
{
$("#ok").text(erfolg);
}
});
});
As u can see i tries to set the name coming from my DB into my session Attribute.
I want to use the Attribute in my 'mandant.jsp' file.
But it dosen't work - all what happens is, that my 'login.jsp' file which makes the ajax call, print the code from 'mandant.jsp' into my div as text.
So it dosen't opend the next page as i want -.-
But if i comment out the HttpSession block then it works fine but then i can't use ,of course,the session Attribute.
So what's wrong or what must i change so that this code works?
Many thanks
This is because this part of the code:
RequestDispatcher dis = request.getRequestDispatcher("mandant.jsp");
dis.forward(request, response);
is generating the HTML from mandant.jsp file using the request object (along with HttpSession and ServletContext) to fulfill any Expression Language and writing this HTML into the response. Just remove these lines and you'll be ok.
You are mixing two types of communication here, from the JSP page you are making an ajax call but from the Servlet you are making a Dispatch redirect.
If you want the login page to be redirected after a a successful login then don't call the Servlet with an ajax call and better do a form submit.
If you rather want to only check credentials on the servlet and redirect from the client then keep the ajax call but avoid the request dispatcher in the servlet and return a success/error code instead. Then capture that code from the ajax response and redirect to a successful page if you want.
Okay, so I have created a music uploading website that uploads OGG music. It also has an audio tagger incorporated. I also put the album art into my database as a string.
Now, I want to display that string (representing my album art) to my JSP:
#WebServlet(name = "LoadAlbumArt", urlPatterns = { "/LoadAlbumArt" })
public class LoadAlbumArt extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpg");
try {
OutputStream outputStream = response.getOutputStream();
DBConnector bConnector = new DBConnector();
PreparedStatement preparedStatement = bConnector
.Connect("SELECT * FROM devwebmp3.musicdatabase where musicno = ?");
preparedStatement.setInt(1,
Integer.parseInt(request.getParameter("musicno")));
ResultSet resultSet = preparedStatement.executeQuery();
Blob blob = null;
String imagestring = null;
while (resultSet.next()) {
imagestring = resultSet.getString("albumart");
}
//BufferedImage bi = ImageIO.read(ImageIO.createImageInputStream(new ByteArrayInputStream(Base64Coder.decode(imagestring.toCharArray()))));
//outputStream.write(blob.getBytes(1, (int) blob.length()));
byte[] hello = Base64Coder.decode(imagestring);
//ImageIO.write(bi, "jpg", outputStream);
//System.out.println("byte" + hello);
outputStream.write(hello);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// ...
}
// ...
}
}
In addition, this is the java servlet page:
src=<%="\"LoadAlbumArt?musicno="+request.getParameter("musicno") +"\""%>>
First of all, where do you call this processRequest(..) method?
Are you sure that you included a call for processRequest(..) in that servlet's doGet(..) method like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
processRequest(req,resp);
}
Did you check the output of a known record by requesting
http://.../LoadAlbumArt?musicno=1
Does your Servlet properly response with a JPEG image? If not, then you should check your Servlet code.
Also change your expression in your View page to this:
<img src="/LoadAlbumArt?musicno=${param.musicno}" />
Those JSP scriptlets and expressions (<% %> and <%= %>) are antique relics now, you should NEVER use them unless you have some old code to resurrect.
You didn't give enough details about your database table, BLOB field, even there are random commented code in your question which is hard to decide whether you used them or not.