Reload a jsp page from servlet when form data is involved - java

I have a jsp that calls a servlet. This servlet does some tasks and then I want to return to the page I was just at and reload it. This would be simple if I knew the exact url it would be each time using the redirectUrl. However, I can't hard code a value in this as it is dynamically created. Is there a way to do this when the previous url is Not known to me?

I am not sure if I understood you correctly, do you need move from jsp to servlet, and return to the same jsp? If this is what you need, I would put some hidden input in jsp form with path
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
So full solution is below:
page1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${requestScope.dataFromServlet }
<form action="${pageContext.request.contextPath}/HelloWorldServlet " method="POST">
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
<input type="hidden" name="param1" value="value1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
HelloWorldServlet.java
public class HelloWorldServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String jspPath = request.getParameter("jspPath");
if(jspPath == null || "".equals(jspPath))
jspPath = "errorPage.jsp";
request.setAttribute("dataFromServlet", "Hello World");
RequestDispatcher rd = request.getRequestDispatcher(jspPath);
rd.forward(request, response);
}
}

Related

Java Spring - servlets - Uplading file post request does not work for me

I have a Java Application using Spring frame work. I am a new learner in this concept. My apologies for making a question which might be very simple.
From the web page user can browse a an excel file and after hitting submit, the excel file should be uploaded to the server and given as an input to a java function in the back end to process it and create a json object.
here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta content="width=device-width, initial-scale=1.0" name="viewport"></meta>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link href="resource/css/main.css" rel="stylesheet"></link>
<title>My App</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" name="submit"/>
</form>
<button id="processData" type="button" class="btn btn-primary">ProcessData</button>
<br></br>
<br></br>
<script src="js/mainJs.js"></script>
</body>
</html>
Then I have define my Servlet file as following:
/**
* Servlet implementation class UploadServlet
*/
#WebServlet("/UploadServlet")
#MultipartConfig
#Named //we can use dependacy injection
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void init(ServletConfig config) throws ServletException {
//this is an initialization method that servlet calls when the application starts up
super.init(config);
// this sets up our dependancy injection
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
//String fileName = Paths.get(filePart.get).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
TestingPost tp = new TestingPost();
if(request.getParameter("submit") != null) {
tp.method1(fileContent);//in this method I will process the received excel file
}
}
}
and here is my java file that plays as controller
public class ProcessFile {
public void method1(InputStream out) {
//doing some processing }
}
but when I run the application, browse a file and hit submit I get 404 -
Do I need to do some thing in my web.xml ?

using getClass().getResourceAsStream() in servlet to access json file data

Hi I have a json file stored in the project folder "project/file.json". How can I first, access and read the json file's data from the servlet's doGet()method. Second I want to print the returned data in a separate JSP file. I'm posting here as the last resort since I could not find anything on how to do this. here is my files and my attempt so far
here is file.json
{
"person": {
"title": "manager",
"questions": [
"name ?",
"age ?",
"hobby ?"
]
}
}
here is the doGet () method from fileServlet.java
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
response.setContentType("text/json");
/* here I'm accessing the external file JSON file*/
getClass().getResourceAsStream("project/file.json");
/* here is where I run into trouble. the StringReader() only
accepts strings and I cannot figure out how to read the table form
file.json here*/
JsonReader reader = Json.createReader(new StringReader(person));
/*the reader needs to be set inorder to create a JsonObject*/
JsonObject jsonObject = reader.readObject();
}
and finally, the JSP file. I want the file.json items to appear in this form like so
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form>
"name ?" get displayed here <br>
<input type="text" name="firstname" value="">
<br>
"age ?" get displayed here <br>
<input type="text" name="age" value="">
<br>
"hobby ?" get displayed here <br>
<input type="text" name="hobby" value="">
<br><br>
<input type="submit" value="Done">
</form>
</body>
</html>
Any help or tips will be appreciated

Request a variable defined in jsp from servlet? [duplicate]

This question already has an answer here:
Authentication filter and servlet for login
(1 answer)
Closed 6 years ago.
The username of the person who logs in is present on the index page and the code works fine. But trying to access the variable username from the servlet is proving hard. Any ideas?
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title><%=request.getParameter("username")%> - Cloud</title>
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<header class="page-header">
<% String username = request.getParameter("username");%> // How can i get this variable?
<h1 align="center" class="inline"><%=username%> - Files</h1>
</header>
<body>
Servlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
}
?
You have to call the servlet through the jsp page
How to call servlet through a JSP page
This is an official example from oracle of how to do that:
Jsp2Servlet.jsp
<HTML>
<HEAD> <TITLE> JSP Calling Servlet Demo </TITLE> </HEAD>
<BODY>
<!-- Forward processing to a servlet -->
<% request.setAttribute("empid", "1234"); %>
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
</BODY>
</HTML>
MyServlet.java
public class MyServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out= response.getWriter();
out.println("<B><BR>User:" + request.getParameter("user"));
out.println(", Employee number:" + request.getAttribute("empid") + "</B>");
this.getServletContext().getRequestDispatcher("/jsp/welcome.jsp").
include(request, response);
}
}
welcome.jsp
<HTML>
<HEAD> <TITLE> The Welcome JSP </TITLE> </HEAD>
<BODY>
<H3> Welcome! </H3>
<P><B> Today is <%= new java.util.Date() %>. Have a nice day! </B></P>
</BODY>
</HTML>
The key is in the line:
<jsp:include page="/servlet/MyServlet?user=Smith" flush="true"/>
In this example a jsp call a servlet a that servlet call another jsp. The example is from this page:
https://docs.oracle.com/cd/A87860_01/doc/java.817/a83726/basics4.htm

Why URL is changing

I have a simple servlet like this:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "root";
private final String password = "root";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
rd.include(request, response);
}
}
Also I have login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
In browser I start my app http://localhost:8080/LoginCookie/ and browser shows login.html. Then I click "Login" button and URL is changing to http://localhost:8080/LoginCookie/LoginServlet.
How do I disable it?
Instead of including your HTML, you could instead redirect to your login.html
Consider using
response.sendRedirect("login.html");
instead of rd.include()
Redirecting has the nice side-effect that reloading the page will reload login.html instead of triggering your servlet again.
If you want to stay on the same page, leave the action attribute empty into your form tag
<form action="" method="post">
But then, you have to make sure that your Servlet will receive your form. LoginServlet will not receive the form request anymore, it will be sent to Servlet mappend with the URL of your current position. So you'll have to make a Servlet receiving this info.

for loop on ArrayList change the object

I have a jsp page (says , MyJspPage.jsp) -
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%
ArrayList<Person> ownerList = (ArrayList<Person>) request
.getAttribute("ownerList");
//set again ..
request.setAttribute("ownerList",ownerList) ;
%>
</head>
<body>
<%
//itr on all the persons ..;
for (Person person : ownerList) {
%>
// some HTML code..
<%
}
%>
<form action="servlet123" method="POST">
// some fields ..
<input type="submit" value="join" />
</form>
</body>
</html>
And a servlet -
#WebServlet("/servlet123")
public class servlet123 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get the then set ..
ArrayList<Person> ownerList = (ArrayList<Person)request.getAttribute("ownerList");
request.setAttribute("ownerList", ownerList);
// forward to `MyJspPage.jsp`
dispather.forward(request, response);
}
}
Firstly another servlet forward to MyJspPage.jsp and it work fine , then there is like ping pong between MyJspPage.jsp and servlet123 . The problem is that when at the 2nd time reachs to MyJspPage.jsp it throws an exception -
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error (java.lang.NullPointerException) that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
It should be noted that when I omit the for loop from MyJspPage.jsp and change it to be -
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%
ArrayList<Person> ownerList = (ArrayList<Person>) request
.getAttribute("ownerList");
//set again ..
request.setAttribute("ownerList",ownerList) ;
%>
</head>
<body>
<form action="servlet123" method="POST">
// some fields ..
<input type="submit" value="join" />
</form>
</body>
</html>
all the relation between MyJspPage.jsp and servlet123 returns work fine .
This is one approach.
JSP Code is as follows
Instead of setting the arraylist again in the request, you can set it in session as follows
session.setAttribute("ownerList",ownerList) ;
You can check for the arraylist to be NOT null before using it in the for loop.
if (ownerList != null)
{
for (Person person : ownerList) {
%>
// some HTML code..
<%
}
}
%>
In the servlet you can write the code as
HttpSession session = request.getSession(false);
ArrayList<Person> ownerList = (ArrayList<Person)session.getAttribute("ownerList");
request.setAttribute("ownerList", ownerList);
session.setAttribute("ownerList", null); // toremove unnecessary code from the session
There could be other approach also. This one is just closer to the one you chose.

Categories

Resources