I am old to JAVA but very new to the topics of JSPs & Servlets. I am trying to do some jdbc operations by taking the values from JSP into servlet. To do that, I have written a JSP with a drop down list and a submit button.
Jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<div align='left' >
<div align='left' >
<label class="text-white mb-3 lead">Which report do you want to generate?</label>
<select id="reportSelection" data-style="bg-white rounded-pill px-5 py-3 shadow-sm " class="selectpicker w-100" name="reportselection">
<option>Outage</option>
<option>DataQuality</option>
<option>Latency</option>
</select>
</head>
<body>
<p id = "demo"> </p>
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</div>
</div>
</body>
<hr class="colorgraph">
<div class="row">
<div class="col-xs-12 col-md-6"><input type="submit" value="Submit" class="btn btn-primary btn-block btn-lg register" tabindex="7"></div>
</div>
</body>
</html>
And this is how my servlet class looks like.
#WebServlet("/getdata.do")
public class DataServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GetTableColumn gt = new GetTableColumn();
String issue = request.getParameter("reportSelection");
String message;
try {
if ("Latency".equals(issue)) {
message = gt.process("latency");
} else if ("DataQuality".equals(issue)) {
message = gt.process("DataQuality");
System.out.println("Data quality");
} else if ("Outage".equals(issue)) {
message = gt.process("Outage");
}
} catch (SQLException s) {
s.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
I am reading the JSP drop down values in my servlet class and passing a String to method process based on the value received. I looked online to configure the web.xml file as below.
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>DataServlet</servlet-name>
<display-name>DataServlet</display-name>
<description>Begin servlet</description>
<servlet-class>com.servlets.DataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataServlet</servlet-name>
<url-pattern>/parse</url-pattern>
</servlet-mapping>
I am trying to run the code on IntelliJ and here is how I have configured my tomcar server on IntelliJ.
When I run the code, I see the page is generating the jsp as expected.
What I don't understand is how to configure the submit with onclick so that I click on submit and the java program in the backed triggers. I have written the java code just to read values from a database by taking the input from the method process. This was running fine and I was asked to take the input from JSP and display the result back on a JSP.
When I click on submit button, I don't see any progress in the console output. I guess I didn't map it correctly.
Most of the links online contain JSP & JAVA together which is even more confusing.
Could anyone let me know how can I trigger the program by clicking the submit button
Since you are using #WebServlet, you do not need mapping in web.xml. Just add the following line inside body of your JSP:
<form action="getdata.do" method="post">
Look at your JSP file, pay attention at your head and body tag. I think it's a wrong that you have body inside other body and closing head tag inside body.
Other case that can be more important that to send a form by clicking to submit button you should put it inside tag form, something like this.
<form action = "getdata.do" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
Related
<html>
<head>
<title>Report Preview</title>
</head>
<body>
<div class="container">
<h2>Patient Data</h2>
<form action = "reportUpdate" method = "post" >
<input type="text" name="fvalue" value="testingData1"/>
<input type="text" name="svalue" value="testingData2"/>
<input type="submit" value="Submit"/>
</form>
</div>
<script type = "text/javascript" src = "main.js"></script>
</body>
</html>
I have a SpringBootProject and I'm using the above Freemarker code template file(*.ftl). I tried to display some input field with the values(binded), after editing I want to extract the data from HTML input tags(fvalue,svalue) to controller without using any model. How to get the values?
My controller code:
#PostMapping({ "/reportUpdate"})
public String reportToUpdate( ) {
String firstName = ""; // I should get fvalue here
String secondName = ""; // I should get svalue here
//Some other logics which will use above value.
return "Data saved!";
}
By using HttpServletRequest request, HttpServletResponse response we can get the data from HTML form.
Using the below code.
public void getDataFromForm(HttpServletRequest request, HttpServletResponse response) throws ServletException{
// Get the values from the request using 'getParameter'
String name = request.getParameter("name");
}
For more info, you can see this.
I am trying to create a simple registration form and insert the data from the user into mongodb.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link href="/css/main.css" rel="stylesheet">
</head>
<body>
<h2>Sign Up</h2>
<#if user?? >
Your submitted data<br>
Name: ${user.user_id}<br>
Password: ${user.password}<br>
Email: ${user.email}<br>
<#else>
<form action="/form" method="post">
First name:<br>
<input type="text" name="Name">
<br><br>
Pasword:<br>
<input type="text" name="password">
<br><br>
Email:<br>
<input type="text" name="email">
<br><br>
<input type="submit" value="Submit">
</form>
</#if>
<script src="/js/main.js"></script>
</body>
</html>
I have a User class, and I want to create an instance of it, to fetch the data and insert it to mongodb. This is the part I don't know how to do. How do I create the controller to pass the data from HTML to the User instance?
This is what I have so far -
//sign up page
Spark.get(new Route("signup") {
#Override
public Object handle(Request request, Response response) {
StringWriter writer = new StringWriter();
User user = new User(); // create user to fetch results
try{
Template signupTemplate = configuration.getTemplate("signup.ftl");
}catch (Exception e){
e.printStackTrace();
}
}
});
}
How do I go on from here? Can I do that only with freemarker and sparkjava?
To post form data to server, you should define a spark route to listen for POST method.
A spark route comprises of three entities (see doc's),
verb: get, post, put, delete etc.
path: Request path for which the Route applies
callback: Handler class that will be invoked when the incoming request matches the path.
In your case it should be,
Spark.post("/form", new Route() {
#Override
public Object handle(Request request, Response response) {
// process request and return response
}
});
If your working with Java 8, you could simplify the above,
Spark.post("/form", (request, response) -> {
// process request and return response
});
Now to read form data, you could do so by fetching the raw request(HttpServletRequest) and using getParameter() inside the handle method.
HttpServletRequest httpRequest = request.raw();
String name = httpRequest.getParameter("Name");
String email = httpRequest.getParameter("email");
I'don't understand why servlet doesn't pass values to .jsp file. If somebody could explain my, why it works only when a call request.getSession.setAtribute() method. What should i do to avoid creating session.
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
moviesList(request, response);
if (request.getParameter("command").equals("ADD"))
addMovie(request, response);
if (request.getParameter("command").equals("DELETE"))
deleteMovie(request, response);
if (request.getParameter("command").equals("SEARCH_IN_TMDB"))
searchInTmdb(request, response);
} catch (Exception e) {
e.getMessage();
}
}
private void searchInTmdb(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<MovieDb> movieDbs;
String title = request.getParameter("title_themoviedb");
String year = request.getParameter("year_themoviedb");
System.out.println("title " + title + " year " + year);
int year_int = Integer.parseInt(year);
movieDbs = TheMovieDbApiUtil.getInstance().getListFoundMovies(title, year_int);
request.getSession().setAttribute("TMDB_LIST", movieDbs);
RequestDispatcher dispatcher = request.getRequestDispatcher("/movie-list.jsp");
dispatcher.forward(request, response);
}
JSP file:
<div class="row top-buffer">
<form action="ServletMovieController" method="get">
<input type="hidden" name="command" value="SEARCH_IN_TMDB">
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<button type="submit">Szukaj...</button>
<input type="text" name="title_themoviedb" title="title_themoviedb" class="form-control">
<input type="text" name="year_themoviedb" title="year_themoviedb" class="form-control">
<ul class="list-group" id="myList">
<c:forEach var="tempMovieTmdb" items="${TMDB_LIST}">
<li class="list-group-item">${tempMovieTmdb.getTitle()}</li>
</c:forEach>
</ul>
</input>
</div>
<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">
</div>
</form>
</div>
As I mentioned before it works when I use requset.getSession(), but whitout it passed value is null.
I think i've understood what is going wrong and it's a common mistake people make when they first start out with the servlet/jsp request flow.
As someone has already mentioned you need to swap out
request.getSession().setAttribute("TMDB_LIST", movieDbs);
with:
request.setAttribute("TMDB_LIST", movieDbs);
Now the reason why you're getting null, is because you're not running the servlet. You're trying to access the jsp directly and expecting the request variable to be there. That's not how servlet/jsp request flow works. The servlet sets the request variable "TMDB_LIST" and it forwards this variable to the jsp page ("/movie-list.jsp"). Once you go to a different page the variable expires and will be null. If you try and access the jsp directly, it will just be null because you need the servlet to pass the variable to the jsp. I'm guessing this is what you're doing or you have a redirect after reaching the jsp.
Session variables are different in that the variables you set persist across the whole application/website (until you delete them or change them), for as long as the server specifies.
Request variables are only available after the first request. (i.e. servlet passes request variables to the jsp or the jsp passes request variables to the servlet)
if you want to avoid using Session, in your servlet, use
request.setAttribute("TMDB_LIST", movieDbs);
I want create 2 JSP pages. I have Controller:
#Controller
#RequestMapping(value = "/api/web/users")
public class ServletWebController {
#RequestMapping(method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", "message");
return "hello";
}
}
It open first JSP page with form:
<html>
<body>
<form action="main.jsp" method="post">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
When I input data to the form and press submit button, I want to open second JSP page and print data from form:
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
But the second JSP page not opened. So I input http://localhost:4000/api/web/users And i have form. Then I input data and press "Submit". Then I have this link http://localhost:4000/api/web/main.jsp and error:
HTTP Status 404 - /api/web/main.jsp
type Status report
message /api/web/main.jsp
description The requested resource is not available.
Apache Tomcat/8.0.26
I am new in Spring and JSP, how can I open JSP from another JSP?
in your Controller you can do something like this:
#RequestMapping(value="/successpage", method =RequestMethod.POST)
public void successpage(ModelMap model, Users user)
{
model.addAttribute("name", user.getFirstName());
}
#RequestMapping(value="/signupform", method=RequestMethod.GET)
public ModelAndView signupForm()
{
return new ModelAndView("user", "command", new Users()); //Object that contains your getter and setters
}
On your form you can modify your open Form tag to look like this:
<form action="/successpage" method="POST">
In your WEB-INF/jsp folder you will need the 2 pages: signupform.jsp and successpage.jsp
After all is said and done, you can pass the ${name} variable on your successpage.jsp to see the value from the form.
How can I redirect a response of a servlet to the same jsp page from where I get the request. Suppose I have a tab called status on my jsp page
http://localhost:8080/Example/status.jsp. Now when I send a request and when I get a response,it should display the response on the same page, ie. it should show response on
http://localhost:8080/Example/status.jsp. But it is showing me the response in
http://localhost:8080/Example/Statuswhere Status is the url-pattern in web.xml file. Please any help is appreciated. below is my code.
How do I get the response in status.jsp.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException {
try{
String showstatus =req.getParameter("showstatus");
PrintWriter out = res.getWriter();
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\\tools\\server\\util stat -a" );
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(pr.getInputStream()));
BufferedReader input = new BufferedReader(stdInput);
String stat = "";
while((stat = input.readLine()) != null){
out.println(stat);
}
}
catch (Throwable t)
{
t.printStackTrace();
}
finally {
} }
JSP CODE:
<div id= "status" style="display:none;">
<FORM action="status" METHOD="POST">
<input type=submit name=showstatus
id=txtSubmit value=Status />
</FORM>
</div>
WEB.XML:
<servlet>
<servlet-name>Status</servlet-name>
<servlet-class>com.emc.clp.license.Status</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Status</servlet-name>
<url-pattern>/status</url-pattern>
</servlet-mapping>
In your servlet, rather than printing the output of util directly to the response, hold it in memory and pass it to the jsp:
String stat;
StringBuffer utilOutput = new StringBuffer();
while((stat = input.readLine()) != null){
utilOutput.append(stat + "\n");
}
req.setAttribute("utilOutput", utilOutput.toString());
req.getRequestDispatcher("/Example/status.jsp").forward(req, res);
In your jsp, I assume you have a div or something where you want to see the output:
<div id= "status" style="display:none;">
<form action="/status" method="POST">
<input type="submit" name="showstatus" id="txtSubmit" value="Status" />
</form>
</div>
<div id="result">
<pre>
${requestScope.utilOutput}
</pre>
</div>
Notice that I added a forward slash in the form action. If your user is submitting the form from /Example/status.jsp, then the relative path would have the post going to /Example/status, but your servlet only handles requests to /status.
Your request object, req, has a map of attributes, and you can put any relevant objects in it using the setAttribute() method on the request. The request dispatcher forwards your request and response objects on to another resource (your jsp) for processing. The jsp can access these values by name, using the EL notation above.
The display:none in your inline style will always prevent that form from being seen on the page if it loads that way. I think the most apparent way to display it would be with javascript on the client side. You'd need to change the display value when the tab is clicked. You don't mention what your tab elements are, but let's say they're divs. You could write a javascript function to load the form, or you could even do it all inline:
<div id="mytab" onclick="document.getElementById('status').style.display = 'block';">Load the form</div>