I am studying Managed Beans right now. I need to use html file to get the data and post them on the next page. I need to use ManagedBean. I am required to use .html file. I can't use JSF because we haven't began to study it yet.
Question: How can I set the value first name in the Voter.java class and then post it the new page?
I tried to use:
First Name:<input action="UserInfo.setFirstName()" type="text" name="fname" maxlength="30"
value="" pattern="[a-zA-Z]{1,30}" title="Please enter first name! Min 1
letter"required/><br>
but it doesn't work after I deploy the program.
welcome.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome Form</title>
</head>
<body>
<div style="text-align:center">
<h1>Welcome</h1>
<form action="summary.html">
<fieldset>
<legend>Form:</legend>
<fieldset>
<legend>Personal Information:</legend>
First Name:<input action="UserInfo.setFirstName()" type="text" name="fname" maxlength="30"
value="" pattern="[a-zA-Z]{1,30}" title="Please enter first name! Min 1
letter"required/><br>
</fieldset>
<p></p>
<input type="submit" value="Submit" />
</fieldset>
</form>
</div>
</body>
</html>
summary.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html>
<head><title>Thank you</title></head>
<body>
<h1>Information Summary</h1>
<li action="SubmissionController.getFirstName()"><b>First Name:</b>
</body>
</html>
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="userinfo")
#SessionScoped
public class UserInfo {
private String fname;
public UserInfo() {}
public String getFirstName() {
return fname;
}
public void setFirstName(String fname) {
this.fname = fname;
}
}
So the answer is yes I can use simple HTML with ManagedBeans.
I just used Java Servlets, HTML and CDI managed beans. I had to use #Inject the reference of class type where is the bean and I used it in the class where I use Servlets. In the bean class I used Named and SessionScoped beans. So the beans store the info that is submitted by the user.
Related
I'm currently working on a Docker-deployed Spring application with an nginx-reverse proxy and want to access a subdomain via #GetMapping & #PostMapping.
What is the correct way to access e.g. the /entity/add subdomain?
Is this a code error or might my server be malconfigured? Is there anything else needed in order to correctly review this problem? I'll gladly add it.
I've looked up the official documentation, guides, other StackOverflow posts etc., but none of them seem to work.
Controller.java:
public class EntityController {
private Repository repository;
#ModelAttribute("entity")
public Entity newEntity() {
return new Entity();
}
// Overview.
#GetMapping("/entity")
public String index(Model model) {
final Iterable<Entity> all = repository.findAll();
model.addAttribute("all", all);
return "index";
}
// New entity.
#GetMapping("/entity/add")
public String loadAddPage(Model model) {
model.addAttribute("entity", new Entity());
return "add";
}
#PostMapping("/entity/add")
public String submitEntity(#Valid #ModelAttribute Entity entity, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "add";
}
repository.save(entity);
return "redirect:/index";
}
index.html:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Overview</title>
<meta charset="UTF-8" />
</head>
<body>
<div class="container">
<h2>Entities</h2>
<form action="/entity/add" method="get">
<input type="submit" value="New Entity"/>
</form>
<div class="content" th:each="entity: ${all}">
<h2 th:text="${entity.name}">Name</h2>
<form th:href="#{/entity/details?id={entityId}(entityId=${entity.id})}">
<input type="submit" value="Edit"/>
</form>
<!--<button><a th:href="#{/entity/update?entityId={entityId}(entityId=${entity.id})}"></a></button>-->
</div>
</div>
</body>
</html>
add.hmtl:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>New entity</title>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
</head>
<body>
<div class="container">
<form action="/entity/add" method="post" th:object="${entity}">
<table>
<tr>
<td><label for="name">Name</label></td>
<td><input id="name" type="text" th:text="Name" th:field="*{name}" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
I expect that a click on the /entity/add-form in index.html correctly links me to entity/add, but it just displays a 404 error. Same with other tested subdomains.
Edit 01: Title updated. (access subdomains -> access URLs)
I understand your question as you need to submit the form to this action url "/entity/add" with method POST. Consider using the Thymeleaf view templates for rendering the server side actions. Check with the following
Change the HTML action attribute to th:action attribute.
Provide the Submit action button to submit the form.
Check this url for more information: https://spring.io/guides/gs/handling-form-submission/
Disclaimer: This is my comment for your question. As I don't have the reputation, I am posting as answer.
I suppose you are using thymeleaf for templating.
Add following in application.properties file:
spring.application.name: my-app-context-path
In Controller :
#GetMapping({"/", "/index"})
public String defaultPage(final Model model, final Locale locale) throws MyException {
addGameInfo(model);
return "index";
}
#GetMapping({"/match/{gameId}"}){
--------
------
}
In view:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
....
....
<h1 class="text-primary">Featured Games</h1><a class="btn btn-flat btn-primary" th:href="#{/match/2944107874}">Game Info 2944107874</a>
....
.....
</html>
You should checkout Thymeleaf Standard URL Syntax
So your url will be resolved to
1.http://localhost:2223/my-app-context-path/
2.http://localhost:2223/my-app-context-path/match/2944107874
It depends on your context path, if you are not providing one, you can access mappings directly.
I found similar problem: Checking a checkbox based on a database entry on a JSP page
I have a Faculty entity and a Subject entity. Every faculty has a list of preliminary subjects.
So also I have a faculty edit page where I have a checkbox with all subjects.
Let's say I have two collections. One with all the subjects and another with subjects that needed for this faculty.
And when user wants to edit faculty at the start he gets edit page with checked values on subjects where value from faculty subjects equals to value from collection of all subjects.
How this can be achieved ? Or maybe there is a simpler way ?
EDIT:
My project is based on jsp and servlets. I have one servlet which is a Front Controller and Command Pattern design. So controller calls appropriate Command, that performs some work and then returns a path to resource. My Model is dao and transfer objects, they interact with MySQL database.
My facultyEdit.jsp page:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${faculty.name}</title>
</head>
<body>
<h1>${faculty.name}</h1>
<form id="edit_faculty" action="controller" method="POST">
<input type="hidden" name="command" value="editFaculty" /> <input
type="hidden" name="oldName" value="${requestScope.name}" /> <input
type="hidden" name="show" value="false" />
<fieldset>
<label for="name">Faculty name:</label> <input name="name"
type="text" value="${requestScope.name}" /> <label
for="budget_seats">Budget seats:</label> <input name="budget_seats"
type="text" value="${requestScope.budget_seats}" /> <label
for="total_seats">Total seats:</label> <input name="total_seats"
type="text" value="${requestScope.total_seats}" />
<p>
<label>Preliminary subjects:</label>
</p>
?????
<input type="submit" value="Edit" />
</fieldset>
</form>
</body>
</html>
So the question what to put instead of ????? to make some of the subjects ckecked.
This question already has answers here:
How do I call a specific Java method on a click/submit event of a specific button in JSP?
(4 answers)
Closed 1 year ago.
Jsp with two buttons
<%# 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>
<body style="background-color:black;">
<p>
<p><input type="button" name="good" value="Pen" onclick="location.href='hello';"> </p>
<p><input type="button" name="good" value="Paper" onclick="location.href='hello';">
</p>
</body>
</html>
This is the servlet
package pack.exp;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
#SuppressWarnings("serial")
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
String val=req.getParameter("good");
if("Pen".equals(val))
{
resp.setContentType("text/plain");
resp.getWriter().println("Pen was clicked" );
}
else if("Paper".equals(val))
{
resp.setContentType("text/plain");
resp.getWriter().println("Paper was clicked");
}
}
}
My code is not giving the correct output on clicking the buttons. I want when i click Pen then it should enter in if() and print the text and i want same for the paper button.
write this code in jsp, it will be helpful to you
<html>
<body style="background-color:black;">
<p><form method="post" action="hello">
<p><input type="submit" name="good" value="Pen" > </p>
<p><input type="submit" name="good" value="Paper" >
</p></form>
</body>
</html>
Add two hidden field.
<form id="my form" >
<input type="hidden" name="myPen" />
<input type="hidden" name="myPaper" />
<input type="button" name="good" value="pen" on click="{document.myform.mypen.value=this.value;location.href='hello';}"
<input type="button" name="good" value="paper" on click=" {document. myform. mypaper.value=this.value;location. href='hello';}" />
</form>
In Servlet
String val=req.getParameter('mypen');
String val1=req.getParameter("mypaper");
At time there is only one value other is null. You can do this with null check.
Use jQuery to do your task.
Change your html code to these lines of code.
<form method="post" action="#" name="Form" id="Form" >
<input type="button" value="one" id="One"/>
<input type="button" value="two" id="Two"/>
</form>
And add these lines in your script
$('input:button').click(function() {
alert($(this).val());
var value=$(this).val();
var url='hello?good=';
url+=value;
$("#Form").attr("action",url);
$("#Form").submit();
});
You can use jQuery 1.7.1 and above.
Encode the button's value into button's name.
In HTML:
<p><input type="button" name="good:Pen" onclick="location.href='hello';"> </p>
<p><input type="button" name="good:Paper" onclick="location.href='hello';">
In servlet: iterate over all parameters, look for parameter which startsWith("good") and if yes, subtrack the prefix good:. If there are no other submit buttons in your page, you can simply name your buttons just Pen and Paper and check the presence of these parameters as well. There is no javascript needed for this task.
I have two JSP pages. In first page I have given fields to fill personal details and I have written request.getRequestDispatcher("second.jsp") and forwarded the the request. But When I run the "first.jsp" on server in eclipse, it is directly going to "second.jsp" but in URL it is shopwing "first.jsp". What might be the problem?
First.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>
<br>
<h2>Enter Your Personal Details</h2>
<form action="personal.jsp" method="get">
<table>
<tr><td>Name: </td><td> <input type="text" name="name" /><br /><br /></td></tr>
<tr><td>Email-ID: </td><td><input type="text" name="email" /><br /><br /></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dob" /><br /><br /></td></tr>
<tr><td>Password: </td><td><input type="text" name="pass" /><br /><br /></td></tr>
<tr><td>Age: </td><td><input type="text" name="age" /><br /><br /></td></tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
<%!
String uname=null,pass=null,email=null;
String age=null,dob = null;
%>
<%
uname= request.getParameter("name");
session.setAttribute("username",uname);
pass= request.getParameter("pass");
session.setAttribute("password",pass);
age = request.getParameter("age");
session.setAttribute("age",age);
email = request.getParameter("email");
session.setAttribute("email",email);
dob = request.getParameter("dob");
session.setAttribute("dob",dob);
response.sendRedirect("academic.jsp");
%>
</body>
</html>
Second.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>
<br>
<h2>Enter Your Academic Details</h2>
<form action="academic.jsp" method="get">
<table><tr><td>
MID: </td><td> <input type="text" name="mid" /><br /><br /></td></tr>
<tr><td>Marks: </td><td> <input type="text" name="marks" /><br /><br /></td></tr>
<tr><td>Salary: </td><td><input type="text" name="salary" /><br /><br /></td></tr>
<tr><td>Stream:</td><td><select name="stream"><option>Java</option><option>dotNET</option><option>Testing</option></select><br /><br /></td></tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
<%
out.println(session.getAttribute("name"));
%>
</body>
</html>
You need to do response.sendRedirect() to make the effect in url.
request#forward
Silently passes the control to your another resource,And happens on server side,browser doesn't know about it.
Forward():
For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.
sendRedirect()
Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.
Highlighting Luggis comment,that move your business logic to Controller and try to avoid scriplets too if possible.
Though,it is not recommended,If you want to change the URL and still want to access the data in second page,one possibility is that put data in session and access in second jsp.
The problem is generated because you have a direct call of forward method in a scriptlet, this might look like this
request.getRequestDispatcher("second.jsp").forward(request, response);
By your question edit, this is generating the problem:
response.sendRedirect("academic.jsp");
Note that using scriptlets is highly discouraged.
Make sure all your data processing and navigation is handled in a Servlet or another controller classes provided by a MVC framework like JSF managed beans or Spring MVC #Controller decorated classes.
More info:
How to avoid Java code in JSP files?
StackOverflow's Servlet wiki, here you can find a real world basic example about how to handle data processing and manipulation from a view to a servlet and then navigating to another view.
The actual problem lies in first.jsp line response.sendRedirect("academic.jsp"); which is inside a JSP Declaration and not JSP Scriptlet, as per the doc variables and methods in JSP declarations become declarations in the JSP page’s servlet class which explains why when you hit the first.jsp its getting redirected to another page without any action and as other suggested its not advisable to use JSP scriptlets, or declarations in your JSP.
As described in the title I need to pass data from my JSP page to my servlet.
I load data out of a database into a form of my JSP page.
Now the user should be able to change that data.
So I have to send the changed data back to my servlet to update my database.
Therefore I want to use the doPost() method in my servlet
This is my JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="content-script-type" content="text/javascript" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="content-language" content="de" />
<link href="../resources/css/basic.css" type="text/css" rel="stylesheet" />
<title>Edit Movie</title>
</head>
<body>
<div id="wrapper">
<h2 id="title">Edit Person</h2>
<br></br>
<br></br>
<form id="1" class="appnitro" method="post" action="">
<ul>
<li id="li_1" >
<label class="description" for="element_1">Name</label>
<div>
<input id="element_1" name="element_1" class="element text large" type="text" maxlength="255" value="${requestScope.person.name}"/>
</div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Deparment</label>
<div>
<input id="element_2" name="element_2" class="element text large" type="text" maxlength="255" value="${requestScope.person.department}"/>
</div>
</li>
<li id="li_3" >
<label class="description" for="element_3">Job</label>
<div>
<input id="element_3" name="element_3" class="element text large" type="text" maxlength="255" value="${requestScope.person.job}"/>
</div>
</li>
<li id="li_4" >
<label class="description" for="element_4">Biographie</label>
<div>
<textarea id="element_4" name="element_4" class="element textarea medium">${requestScope.person.biography}</textarea>
</div>
</li>
<li class="buttons">
<input type="hidden" name="form_id" value="652973" />
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
And this is my Servlet without the doPost() method:
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;
import de.hof.university.spj.model.People;
import de.hof.university.spj.model.PeopleDAO;
public class SinglePersonEditServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PeopleDAO peopleDao = new PeopleDAO();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String name = "id";
String value = request.getParameter(name);
int id = Integer.parseInt(value);
People people = peopleDao.getPerson(id);
request.setAttribute("person", people);
RequestDispatcher reqDispatcher = request.getRequestDispatcher("../jsp/singlePersonEdit.jsp");
reqDispatcher.forward(request, response);
}
}
After the submit button was pressed I want to send the changed
data to my servlet so I can store it in my database.
Why String name = "id";
String value = request.getParameter(name); ? I can't seem to find any input in your JSP that's name = "id" ...
In the servlet, you should have this (for example), this :
String element_1_value = request.getParameter("element_1") ;
Either you forgot the input with id name or I am missing something. In any case, this is what you need to fix within your code.
Not to mention that you forgot inserting the name of the servlet in the action attribute of the form tag, so you had this :
<form id="1" class="appnitro" method="post" action="">
Which should become this :
<form id="1" class="appnitro" method="post" action="SinglePersonEditServlet">
Finally, your action method is "post" (as shown in the above two code lines), in the piece of servlet of your question you work with doGet, you ought to put your code in doPost unless that's done, otherwise it's sufficient to call doGet inside doPost.
I am a beginner myself, so I recognize one when I see it, we all started somewhere and I would recommand you this totu or any good search about "handling form data with servlet".
Note : duplicate of this, check it out for further learning :).
Regards.