I have two html pages - one for login and one that takes in a persons details. The login page is the first page and when the database is checked for the username and password, the user is allowed to enter their details. The SQL code works perfectly, it is just a problem with the mapping I am having. I am using the Tomcat server by the way. Could anybody help or spot what i am doing wrong?
This is my java code for logging in and entering details
public class Details extends HttpServlet {
private Connection con;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
//return writer
PrintWriter out = res.getWriter();
String username = req.getParameter("username");
String password = request.getParameter("password");
out.close();
try {
login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res.sendRedirect("/redirect.html");
String name = request.getParameter("name");
String address = request.getParameter("address");
String age = request.getParameter("age");
out.println("<HTML><HEAD><TITLE>Personnel Details</TITLE></HEAD><BODY>");
out.println(name + address + age);
out.println("</BODY></HTML>");
System.out.println("Finished Processing");
}
out.close();
}
In my web.xml file I have:
<web-app>
<servlet>
<servlet-name>Details</servlet-name>
<servlet-class>Details</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Details</servlet-name>
<url-pattern>/Details</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/redirect</url-pattern>
You may try this :
response.sendRedirect("redirect.html");
or
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "redirect.html");
Alternative way,
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/redirect.html").forward(request, response);
Redirect to HTML
RequestDispatcher ds = request.getRequestDispatcher("index.html");
ds.include(request, response);
you can use
1.response.sendRedirect("redirect.html") or
2.String path= "/redirect";
RequestDispatcher dispatcher =servletContext().getRequestDispatcher(path);
dispatcher.forward(request,response);
Related
I am trying to make a simple textbox which initiate a suggestive feedback based on the characters entered by the user. I am trying to fetch a JSON object from a Servlet but my AJAX call is somehow not reaching the servlet. On checking the status of AJAX request using this.status I am getting error code 404. Can anyone suggest me a solution:
[![enter image description here][1]][1]
Here's my servlet: FetchServ.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Connection con;
ResultSet rs;
java.sql.PreparedStatement pst;
String ch = request.getParameter("q");
String data;
ArrayList<String> list = new ArrayList();
response.setContentType("application/JSON");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("drivers registered");
con = DriverManager.getConnection(con_url, userID, password);
System.out.println("connection created");
pst = con.prepareStatement("SELECT * FROM candidates where FirstName LIKE ?");
pst.setString(1, ch + "%");
rs = pst.executeQuery();
System.out.println("query executed");
while(rs.next())
{
data = rs.getString("FirstName");
list.add(data);
}
String json = new Gson().toJson(list);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
response.getWriter().append("Served at: ").append(request.getContextPath());
} catch (SQLException | ClassNotFoundException e) {
System.err.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
the jsp code:
<script>
function suggest(str){
if(str.length == 0){
return;
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
document.getElementById("sugg").innerHTML = this.status;
if(this.readyState == 4 && this.status == 200){
//var res = JSON.parse(this.responseText);
document.getElementById("sugg").innerHTML = this.responseText;
}
};
try{
xmlhttp.open("GET", "com.test.java/FetchServ", true);
xmlhttp.send();
}catch(e)
{
alert("unable to connect ");
}
}
}
</script>
</head>
<body>
<form>
Search:<input type="text" onkeyup = "suggest(this.value)">
</form>
<p id = "sugg"></p>
</body>
</html>
and this is the result I am getting:
[![enter image description here][2]][2]
<display-name>ACtxtbox</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.test.java/FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/FetchServ</url-pattern>
</servlet-mapping>
</web-app>
your Web.xml entries are not proper, check the url which you are using in urlbar and the form submitted using xmlhttp.open("GET", "fetch", true); you can debugg the actual url passed as a request to the server by opening developer tools and navigating to the network tab it will look something like below.
also your <servlet-class>ACtxtbox/FetchServ</servlet-class> is not correct, it should be with package path like <servlet-class>sompackagepath.FetchServ</servlet-class>
EDIT
As per your images, I can see you have declare index.jsp which will be accesible by giving url: http://localhost:<port_number>/ACtxtbox/index.jsp.
Now you should note below points:
As you are calling servlet using ajax call where you have given
parameters as fetch in this line of code in you javascript
xmlhttp.open("GET", "fetch", true); hence it is now changing your
url to http://localhost:<port_number>/ACtxtbox/fetch
your web.xml entry should be like this
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.rishal.test.FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/fetch</url-pattern>
</servlet-mapping>
How come your url pattern is coming like
http://localhost:<port_number>/ACtxtbox/com.test.java/fetch ? is
it you have modified the web.xml entries. Please read the tutorials
and google about web application,jsp,servlets and ajax calls. you
should also note that you have to create your servlet class under
some package as i have given in the web.xml entry
com.rishal.test its package path and class is inside this package
path.
package com.rishal.test;
public class FetchServ extends HttpServlet {
----------------------
---------------------------
}
I'm doing a project using Java servlets. I have to include code in an already functioning site. I'm using Netbeans and the server is Tomcat. The code that I added is very similar to some parts of the code of the site. I had to create a new controller that reads from a database and display, add, update and delete information. The site was functioning with different servlets that we created but a requisite for the project is to create the controller servlet. This is part of the code of the controller:
public class MaintController extends HttpServlet {
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
String url = "/maint";
if (requestURI.endsWith("/displayProducts")) {
url = displayProducts(request, response);
} else if (requestURI.endsWith("/addProduct")) {
url = addProduct(request, response);
} else if (requestURI.endsWith("/editProduct")) {
url = editProduct(request, response);
} else if (requestURI.endsWith("/deleteProduct")){
deleteProduct(request, response);
}
getServletContext()
.getRequestDispatcher(url)
.forward(request, response);
}
private String displayProducts(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
List<Product> products = ProductDB.selectProducts();
session.setAttribute("products", products);
out.println(products);
String url= "/maint/products.jps";
return url;
}
The point is that debugging the site I can see that when entering an URL that finishes with /displayProducts the displayProducts function is accessed, the products are read and the URL is returned, but when the control goes to getServletContext().getRequestDispatcher(url).forward(request, response); the url is not forwarded and I get a 404 error when the url exists.
I can see in the displayProducts() method, you have defined the url as follows:
String url= "/maint/products.jps";
shouldn't that be a typo??
String url= "/maint/products.jsp";
file extension is wrong right?
404 error indicates the requested page not found.
your return url is
String url= "/maint/products.jps";
extension of the requested page is not correct. It should be products.jsp
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.
This is my Jsp File
<body>
<%
URL url = new
URL("http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet");
URLConnection conn =url.openConnection();
conn.setDoOutput(true);
BufferedWriter bw= new BufferedWriter( new OutputStreamWriter(
conn.getOutputStream() ) );
bw.write("username= Shanx");
out.flush();
out.close();
%>
</body>
This is my servlet class
#SuppressWarnings("serial")
public class JSPToServletToCloudServlet extends HttpServlet
{
private final static String _USERNAME = "username";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String username = request.getParameter(_USERNAME);
response.setContentType("text/html");
out.println("HelloWorld");
out.println("Hello " + username);
out.close();
}
This is the web.xml file
<servlet>
<servlet-name>JSPToServletToCloud</servlet-name>
<servlet-class>pack.exp.JSPToServletToCloudServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSPToServletToCloud</servlet-name>
<url-pattern>/jsptoservlettocloud</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
My Jsp File is in Dynamic Web Application and is sending a string to Servlet which is in Web application Project. I am running the dynamic web application project on apache tomcat server and after the server is started I am running my web application projewct as web application and checking on local host and getting null.
Help me out guys.
you will have to put username name wither in session, because you are not set the username in request.
put user name in session and on server Side write :-
HttpSession session = request.getSession();
String username = session.getAttribute("username")
I have a Dynamic application in which I have a JSP file which is sending a string to a Servlet which is in another project which is a Web application Project. I am using Tomcat server in JSP project and the server is starting just fine but when I am trying to run the web application on local host I am getting HTTP ERROR 500
Problem accessing /jsptoservlettocloud. Reason: INTERNAL_SERVER_ERROR
This is my JSP FILE
<body>
<%
String str= "Shanx";
URL u = new
URL("http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet");
HttpURLConnection huc = (HttpURLConnection)u.openConnection();
huc.setRequestMethod("GET");
huc.setDoOutput(true);
ObjectOutputStream objOut = new ObjectOutputStream(huc.getOutputStream());
objOut.writeObject(str);
objOut.flush();
objOut.close();
%>
</body>
This is my Servlet Class
public class JSPToServletToCloudServlet extends HttpServlet
{
String str;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
try
{
str= (String) ois.readObject();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
finally
{
ois.close();
}
System.out.println("Servlet received : " + str);
}
}
This is my Web.xml file
<servlet>
<servlet-name>JSPToServletToCloud</servlet-name>
<servlet-class>pack.exp.JSPToServletToCloudServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSPToServletToCloud</servlet-name>
<url-pattern>/jsptoservlettocloud</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
In the url ServletToCloud is the name of the web application project and JSPToServletToCloudServlet is the name of the servlet. Is this url correct.
In your jsp you have http://localhost:8080/ServletToCloud/JSPToServletToCloudServlet but you have /jsptoservlettocloud in your web.xml
Your mapping is wrong.