Everything is working fine else why RequestDispatcher showing source code of page?
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uName=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
try{
DBConnection con=new DBConnection();
if(con.login(uName, uPass)){
HttpSession on = req.getSession();
on.setAttribute("u_id", uName);
res.sendRedirect("dashboard.jsp");
}
else{
RequestDispatcher dis= getServletContext().getRequestDispatcher("/login.jsp");
PrintWriter write = res.getWriter();
write.println("Wrong Username or Passowrd");
dis.include(req, res);
}
}catch(ClassNotFoundException | SQLException e){}
}
}
Page redirecting fine to given url /login.jsp and also showing the error message, but why as source code?
Wrong Username or Passowrd
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="LoginServlet" method="POST" />
<input type="text" name="uEmail" />
<br /><br />
<input type="text" name="uPass" />
<br /><br />
<input type="Submit" name="Register" value="Register" />
<br /><br />
</form>
</body>
</html>
direct link to login.jsp works fine.
from http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
The include method of Request Dispatcher gets the content of the resource that why you are getting the source code in browser.
I think what you want to do is forward the request to login.jsp so use forward method of request dispatcher.
As #JBNizet mentioned in his comment due to your message from Servlet, HTML is going to be invalid.
before dis.include(req,res);
add this line res.setContentType("text/html); it
I was facing the same issue when I used RequestDispacther method and try to return and String massage along with html page then i have found you have to put some kind of tag to the String massage like then use include method
so if my code was
out.println("Terms & Condition not accepted");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
i changed it to "
out.println("<h1>Terms & Conditions not accepted </h1>")
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
"
You need to set the content type of the response.
Add the below line in your doPost method.
response.setContentType("text/html;charset=UTF-8");
Hope it works for you!!
Related
I have a simple servlet 'Login' deployed in Server A tomcat
Index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Login</h1>
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
</body>
Validate.java
doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
else
{
PrintWriter out = response.getWriter();
out.println("Wrong password!!!");
}
}
Welcome.Java
doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Welcome"+user);
}
This set up works fine.
Now what I want to try is to create another Servlet 'Validate' which would be deployed in another Server B tomcat with a different IP. I need to pass the parameters from Servlet 'Login' to Servlet 'Validate' which will then validate the credentials and send back the validation message, a String, to the Servlet 'Login' which will then display the same on its index.jsp page.
Please provide some help on this. Let me also add that I have no prior experience in servlets.
I know similar questions have been asked earlier but for some reason it is not working. I am just trying to check if user has entered both the fields on the login page or not. If not, then I want to display the message on jsp saying that they need to enter both the credentials. Here is my JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<h2>Some App</h2>
<form action="login" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="pass" name="pass"></td>
</tr>
</table>
<br> <input type="button" value="Submit">
</form>
<c:out value= "${error}"/>
</body>
</html>
Then here is the servlet:
#WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//Getting values from the form
String username = request.getParameter("uname");
String password = request.getParameter("pass");
System.out.println("Username is: "+ username);
System.out.println("Password is: "+ password);
//User user = new User();
if((username.equals(""))|| password.equals("")){
String message = "Please enter both the credentials";
request.setAttribute("error", message);
//RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
//rd.forward(request, response);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
else{
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//Setting values in the session
session.setAttribute("username", username);
session.setAttribute("password", password);
}
}
Since I am trying to experiment with maven, here is my pom.xml file with dependency added for jstl jar:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
Why does that c:out tag not print anything? What am I doing wrong? Any help will be appreciated. Thank You.
You are mixing two styles of returning a response to the client. Try passing the error message using this code:
if((username == null)|| password == null) {
String message = "Please enter both the credentials";
request.setAttribute("error", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
The rule of thumb is that you have to use request.setAttribute() with forward() and request.getSession().setAttribute() with response.sendRedirect().
try ${sessionScope['error']} instead of ${error}. If that worked then you may have another attribute in another scope with the same name 'error'
You should also check if username or password are empty. i.e. (username != null && username.trim().isEmpty())
Suggestions from everyone was very valuable. There were a few things that I was doing wrong: incorrect servlet mapping (#WebServlet fixed it), changed code to what #NaMaN and #bphilipnyc replied and the biggest mistake due to which I wasn't able to reach servlet was that I had input type as button in jsp. I changed it to input type submit, and then it worked. Thank you guys for replying. Really appreciate it.
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
It's my first day trying servlets. It's just a simple login function, but I get an error that doesn't explain what I'm doing wrong. It just says
404: The requested resource is not available.
Here's my servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String key = "ole";
String username = request.getParameter("username");
String password = request.getParameter("password");
response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
And here's my login page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body>
Enter username and password below.
<form method=get action="hej">
<input type="text" user="username" /> <input type="password"
user="password" /> <input type="submit" value="Login" />
</form>
</body>
</html>
There is a file called secret.jsp as well, but there's nothing interesting in there. I don't understand why it's returning 404. When I have remove the if statement it works... only then, there's not much function.
As you say it works without IF-ELSE then I guess your web.xml entry is correct.
First change this to
<input type="password" user="password" />
this
<input type="password" name="password" />
input tag does not have any user attribute , it's name.
Next mistake is , you are using session.getAttribute to access parameters that you have not set, yet.
Your code should be
if (username.equals(key)
&& password.equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
session.getAttribute can only be used when you have in your code session.setAttribute
example session.setAttribute("username","ole");session.setAttribute("password","ole");.
Then only you could get a value with session.getAttribute("username") OR session.getAttribute("password"). But right now it only returns NULL. So code won`t work.
You could add this code in your existing code and it will work.
session.setAttribute(username,username);
session.setAttribute(password,password);
Your complete code should be
String username = request.getParameter("username");
String password = request.getParameter("password");
session.setAttribute(username,username);
session.setAttribute(password,password);
//response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
Replace user="... by name="... in your HTML and it will work.
Replace user="... by name="... in your HTML and it will work. NullPointerException is thrown because because of the wrong HTML the request parameters are NULL and these are used for the session lookup.
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 3 years ago.
I have a JSP which will let a user register for an account at my website. If the user submits wrong or illegal info into the JSP, then I want to return the same JSP with an appropriate error message next to/above each wrongly filled (form) fields.
If possible, highlight the wrongly filled form field - this feature is not necessary though.
I have given a sample below to show what I need. I understand that the sample must be using something like javascript, but I don't know all that client side scripting. I only want to use JSP to do it. As I said, I want to sort of return the JSP form to the user after marking all the mistakes and how to correct them.
How do I do this ? I only need some initial direction. I will make the code myself and post it here later.
Thanks.
EDIT - I don't want the drop down box. I don't want red borders around wrongly entered fields. I only want to display the error messages (in red color) next to the relevant fields.
Here is some sample code -
<%# page language="java" contentType="blah..." pageEncoding="blah..."%>
<!DOCTYPE html PUBLIC "blah...">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user"><br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
RegServlet -
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;
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static String okUser = "loser";
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(user.equalsIgnoreCase(okUser) == false){
//Do something MAGICAL to set an error next to username field of Form.jsp, then forward.
RequestDispatcher view = request.getRequestDispatcher("/jsp/Form.jsp");
view.forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Validation</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- or download to a directory -->
<!-- <script src="js/jquery-1.9.1.js"></script> -->
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#user').change(function() {
var userName = jQuery(this).val();
jQuery.ajax({
type : 'GET',
url : 'AjaxUserCheck',
data : {user:userName},
dataType : 'html',
success : function(data) {
if(jQuery.trim(data)=='1')
{
jQuery("#userLabel").html("Sorry! username is taken");
//write other stuff: border color ...
}
else if(jQuery.trim(data)=='0')
jQuery("#userLabel").html("user name available");
else
alert(data); //possible error
},
error : function(xhr,status,error){
console.log(xhr);
alert(status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user" id="user">
<label id="userLabel"></label>
<br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
---------Servlet------
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
//if(dao.isUserExist(user)){
if(user.equals("java")){ // check for db if userid exists in DB print '1' else '0'
out.print("1");
}
else
out.print("0");
have the page post to itself, like this login.jsp fragment:
<div class="error">
<%
String usrName = "" + request.getParameter("username");
String usrPass = "" + request.getParameter("password");
if (isValid(usrName,usrPass){
openUserSession(usrName); //here you open a session and set the user, if the session doesn't have an user redirect to login.jsp
response.sendRedirect("index.jsp"); //user ok redirect to index (or previous page)
} else {
out.print("Invaid user or password");
}
%>
</div>
<form action="login.jsp" method="POST"> <!-- login.jsp post to itself -->
<input type="text" name="username" id="username"/>
<input type="password" name="password" />
<input type="submit" value="login" name="login" />
<input type="submit" value="register" name="register" />
</form>
I am working with resteasy with war file deployed on jboss (6.0.2 EAP)
I have the following workflow :
URL hit calls a servlet(doGet() method)
this servlet is supposed to deliver a jsp page to the client
JSP page resides in WebContent/customFolder
I use the requestDispatcher().forward() method to invoke the JSP
The path given in forward("/customFolder/name_of_jsp")
the jsp has a form, whose action attribute points to another servlet
the problem is , once the forward() method is called, the browser returns a 404 resource not found error.
I have followed some questions already posted on this forum and was not able to solve this issue.
Can anyone please guide me.
Edit:
JSP page :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="javax.servlet.*,java.lang.String"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Password Reset Page</title>
</head>
<body>
<form method="GET" action="Resteasy">
<%!String userId;%>
<%userId = (String)getServletContext().getAttribute("userid"); %>
<p>User Id:<%= userId %></p>
Password: <input type="password" name="pwd" id="pass">
<br>
Confirm Password: <input type="password" name="rePwd" id ="c_pass" onblur="confirmPass()"><br>
<script type="text/javascript">
function confirmPass() {
var pass = document.getElementById("pass").value
var confPass = document.getElementById("c_pass").value
if(pass != confPass) {
alert('Wrong confirm password !');
document.getElementById("c_pass").focus();
}
}
</script>
<input type="submit" value="Submit">
</form>
</body>
</html>
The servlet which has to deliver the jsp :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.info("Received request for popup jsp page");
String userId = request.getParameter("userid");
String utc = request.getParameter("utc");
log.info("Recieved userid = "+ userId);
log.info("Received utc is = "+ utc);
ServletContext requestContext = request.getServletContext();
requestContext.setAttribute("userid", userId);
requestContext.setAttribute("UTC", utc);
String htmlfileName = null;
try {
htmlfileName = new DeltaPropertyHandler(
DeltaConstants.LINK_HTML_FILE).getPropertyValue(DeltaConstants
.USER_PASSWORD_RESET_HTML);
File file = new File(requestContext.getRealPath(htmlfileName));
if(file.exists()){log.debug("file exists!!");}
else{log.warn("file does mot exist");}
} catch (Exception e) {
log.error("failed to present the jsp page " + e.getMessage());
}
log.info("File name is "+htmlfileName);
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
rd.forward(request, response);
}
your code:
RequestDispatcher rd = requestContext.getRequestDispatcher(htmlfileName);
you should change:
RequestDispatcher rd = requestContext.getRequestDispatcher(programname.jsp);
if your using the get method as following as:
RequestDispatcher view=request.getRequestDispatcher(forward);
view.forward(request, response);
if your using the post method like as:
private static String LIST_USER="/listUser.jsp";
RequestDispatcher view=request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
User will be reference from this format. And just look at the simple format are following as:
A.jsp> conntroller.java > dao.java>dbUtil.java
you want the reference for that list as following link to click