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
Related
In theory when the AMPByExample server receives the POST request
from the login page, if the credentials are correct, it will redirects
the request to the URL of returnURL and the parameter is added
success = true. Once done, the AMP execution time can finally
authorize the page.
The login page is the following:
login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form method="post" action="loginauthorization">
Correo Electronico: <input type="text" name="correo"><br>
ContraseƱa: <input type="password" name="clave"><br>
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=https%3A%2F%2Fampbyexample.com%2Fplayground%2F">
<input type="submit" value="Ingresar">
</form>
</body>
</html>
As you can see, in the returnurl it is the same login URL ofAmpByExample and it does not work.
I already tried to make my own url in the following way:
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=http%3A%2F%2Flocalhost%3A8084%2Fmypage%2Fpanel.jsp">
And it doesn't work either.
In the servlet loginauthorization.java I receive thatreturnurl and I add the # success = true (supposedly I must verify username and password, but I want to make it work first).
loginauthorization.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class loginauthorization extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
//I get the parameters
String email = request.getParameter("correo");
String password = request.getParameter("clave");
String url = request.getParameter("pageurl");
int ridini = url.indexOf("rid=")+4;
int ridend = url.indexOf("&url=");
String rid = url.substring(ridini, ridend);
String returnurl = request.getParameter("returnurl");
//assuming that the username and password are correct, add to the returnurl success true
returnurl= returnurl + "#success=true";
//create a session
HttpSession session=request.getSession();
session.setAttribute("umail",email);
session.setAttribute("upass",password);
session.setAttribute("rid",rid);
session.setAttribute("returnurl",returnurl);
//redirect after login with the success = true
response.sendRedirect(returnurl);
}catch(Exception exp){
System.out.println(exp);
}
}
}
The configuration of the panel is as follows:
panel.jsp
<script id="amp-access" type="application/json">
{
"authorization": "http://localhost:8084/mypage/jsonauthorization",
"noPingback": "true",
"login": {
"sign-in": "/mypage/login.jsp?rid=READER_ID&url=CANONICAL_URL&return=RETURN_URL",
"sign-out": "/mypage/endsession"
},
"authorizationFallbackResponse": {
"loggedIn": false
},
"type": "server"
}
</script>
The jsonauthorization prints{"loggedIn": true}or{"loggedIn": false}:
jsonauthorization.java
import java.io.*;
import javax.servlet.http.*;
public class jsonauthorization extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("application/json");
response.setHeader("AMP-Access-Control-Allow-Source-Origin", "http://localhost:8084/mypage");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
if(session != null){
String email=(String)session.getAttribute("umail");
if(email==null){
session.invalidate();
pwriter.print("{\"loggedIn\":false}");
}else{
String rid;
rid = (String) session.getAttribute("rid");
Cookie AmpCookie = new Cookie("authorized",rid);
AmpCookie.setPath("/");
AmpCookie.setDomain("/mypage");
response.addCookie(AmpCookie);
pwriter.print("{\"loggedIn\":true}");
}
}else{
pwriter.print("{\"loggedIn\":false}");
}
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
I appreciate the answers, if the error is not in the returnurl please tell me where :P
I am also trying to figure out AMP integration with login/registration. Not sure if this will help, but I found that the return url is automatically added to the url param, so you don't necessarily have to add it to your sign-in url within your initialization json object.
I figured out, it is not necessary to configure the return url. Simply add the hidden input inside the html in order to close the login window and read the json url approving the login.
Just like this:
<input name = "returnurl" type = "hidden" value = "https://cdn.ampproject.org/v0/amp-login-done-0.1.html">
Then, if the json url aproves the login it will works.
Actually the code is fine, the problem was in the json generator file.
CORS problems. Is necessary to set the header "AMP-Access-Control-Allow-Source-Origin" right.
I am trying to pass an attribute from a java servlet to jsp and write this attribute on jsp file. However it does not redirect to jsp file url but it writes the content of the jsp file. Here is my related codes:
Control.java:
#WebServlet("/Control")
public class Control extends HttpServlet{
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Key key = MacProvider.generateKey();
long time = System.currentTimeMillis();
try{
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject("username")
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+6000000))
.claim("password","password")
.compact();
req.setAttribute("jwt", jwt);
req.getRequestDispatcher("/Home.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
}
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
${jwt}
</body>
</html>
Here, browser stays on http://localhost:8080/Control but it writes the content of Home.jsp file which is just a java web token result string.
2) My second question is when I tryed to store this jwt result string in browser local storage and then write it in jsp file in order to check if it stored in browser or not. But it does not prints anything. To do this, I just changed the Home.jsp file as follow:
(I took both of the code snippets from here)
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script>
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.write(jjwt);
</script>
</body>
</html>
Another try:
<html>
<head>
<script>
function myFunction() {
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.getElementById("myText").innerHTML = jjwt;
}
</script>
</head>
<body onload="myFunction()">
<span id="myText"></span>
</body>
</html>
Where am I doing wrong?
1) When you use RequestDispatcher.forward(request,response), your servlet will still have control but your jsp page will be loaded so this is nothing to worry about.
If you want your browser URL to show your JSP page URL, do response.sendRedirect("URL TO LOAD");
2)Since you are using JSP, try accessing the request variables like below and print it
<% String jwt = (String) request.getAttribute("jwt");%>
We need to set it as
localStorage.setItem('jwt', <%=jwt%>);
I am trying to log a json response from my servlet in my ajax call. Now, here is the thing, I tried experimenting with logging string response in my ajax and things seemed to work fine but then I try to log the json response, I see nothing in my console. I am wondering if I am missing out on something.I tried calling my servlet from POSTMAN and I got the proper json response.
HomeServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> options = new LinkedHashMap<>();
String text = "some text";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
options.put("value1", n);
options.put("value2", nm);
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
Home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<!--
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit"> -->
<br>
<input type="submit" id="check" name="check" value="Check">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
console.log("I was clicked");
$.get("HomeServlet", function(responseText) {
console.log("response",responseText);
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
});
</script>
</body>
</html>
You will need to write a callback, this will be fired when your ajax call completes, try like below
function success(data) {
console.log( data );
}
function failure(err) {
console.error( err );
}
ajax( "http://some.url.1", success, failure );
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!!
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.