I want a way where the user enters details through a series of radio buttons. A java class then does some work by looking at the responses and returning a score to the user based on the responses (i.e. a different response can give different feedback). ive written the code for the jsps and now need some way it can link to the java class containing the if statement, go through the if statement and then return the result.
the first jsp where the radio buttons are selected
<form:form action="/HelloSpring/questionTwo" method="post">
<p> What is the correct wrapper class for the primitive int? </p>
<input type="radio" name="radios1" value="Int" path="types" >Int<br>
<input type="radio" name="radios1" value="Enum" path="types">Enum<br>
<input type="radio" name="radios1" value="integer" path="types" >integer<br>
<input type="radio" name="radios1" value="Integer" path="types" >Integer<br>
<input type="submit" value="Next" >
</form:form >
the controller where it should read results and then perform if statement
#RequestMapping(value = "/results", method = RequestMethod.POST)
public String results(Model model, HttpServletRequest request,
HttpServletResponse response){
String radio = (String)request.getParameter("radios1");
request.setAttribute("total", total);
// model.addAttribute("total", total);
if (radio.equals("Int")){
total = total + 0;
}
else if (radio.equals("Enum")){
total = total + 0;
}
else if (radio.equals("integer")){
total = total + 0;
}
else if (radio.equals("Integer")){
total = total + 1;
}
else{
total = total + 0;
}
System.out.println(radio);
return "results";
}
the jsp that should post what result they get. The session.getAttribute bit works just not ${total}
<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose <%= session.getAttribute("q1") %> </p>
<p>For question 2 you chose <%= session.getAttribute("q2") %> </p>
<p>For question 3 you chose <%= session.getAttribute("q3") %> </p>
<p>For question 4 you chose <%= session.getAttribute("q4") %> </p>
<section>
<p>Total score: ${total} /4</p>
Submit the form to a controller, call the if statement and put the result in a ModelAndView, that your controller returns.
#RequestMapping(value = "/results", method = RequestMethod.POST)
public ModelAndView results(Model model, HttpServletRequest request, HttpServletResponse response){
ModelAndView mav = new ModelAndView();
// set name of next view ...
mav.setViewName("results");
// handle if...
// add results to next view ...
mav.addObject("anyNameYouWant", yourObject);
return mav;
}
Related
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 4 years ago.
I have an Jsp page that has the ID text field which takes the input from the user and that input is read in a servlet. I am also validating that input in servlet. If user enters an wrong input I need to give a text message like wrong input below that ID field only in the Jsp.
Here is the servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
services2 reporteeservice = new services2();
services3 jiraservice = new services3();
service4 empid = new service4();
String id = request.getParameter("ManagerId");
int Number = 1;
PrintWriter out1=response.getWriter();
String n = ".*[0-9].*";
String a = ".*[a-z].*";
String c = ".*[A-Z].*";
if( id.matches(n) && id.matches(a) || id.matches(c))
{
out1.println("valid input");
try {
//s.getList(id);
....
}
else
{
out1.println("not a valid input");
}
But if I give else part as above, it will redirect me to next page and prints not a valid upon giving the wrong input. But, I want that to be displayed in the same page under the ID field in the Jsp.
My JSP page:
<form name = "reportees" method = "GET" action="reportsto">
<center>
<h1><font size="20"> Enter the ID to get the Reportees</font></h1>
<label><font size="+2">ID</font></label>
<input name="ManagerId" ype="text" style="font-size:16pt"/>
<input type="submit" value="submit"/>
<button type="reset" value="Reset">cancel</button>
</center>
</form>
See if this helps you.
<script>
function validateForm() {
var mid = document.getElementById("ManagerId").value;
// If manager id is empty
if(mid===""){
alert("Please enter valid manager id.");
return false;
}
}
</script>
<form name = "reportees" method = "GET" onsubmit="return validateForm()" action="reportsto">
<center>
<h1><font size="20"> Enter the ID to get the Reportees</font></h1>
<label><font size="+2">ID</font></label>
<input name="ManagerId" id="ManagerId" ype="text" style="font-size:16pt"/>
<input type="submit" value="submit"/>
<button type="reset" value="Reset">cancel</button>
</center>
</form>
I want to send selected options of a select to controller using following
<form action="/save" method="POST" >
<input type="text" name="name"/>
<label>Subjects</label>
<select name="subjects">
<option value="English">English</option>
<option value="Maths">Maths</option>
</select>
<input type="submit" value="Save">
</form>
In controller while form is posted I check the size of subjects list
#RequestMapping(params={"subjects"}, value = "/save-std", method = RequestMethod.POST)
public String saveStd(#ModelAttribute("std")Student std,
#RequestParam("subjects") List<String> subjects) {
System.out.println("List Size is " + subjects.size() );
return "home";
}
it always shows List Size is 1 in the console, why it happens or any better solution to get all selected options?
Please refer to this link. This may help you.
"Request parameters are a Multimap of String to String. You cannot
pass a complex object as request param."
i am having f.jsp which returns a lists of ages(1..100) and genders(m/f) and a button GO and put it in comboboxes and i have f_m.java which is servlet which took the selected items from comboboxes and select an certain item from database and put it in table in f.jsp .. now my problem is when trying to print the table in f.jsp and HTTP 500 appears so what can i do .. here is my code
f.jsp
<% List<String> sex = (List<String>)request.getAttribute("sexList"); %>
<% List<String> age = (List<String>)request.getAttribute("ageList"); %>
<form method ="GET" action="f_m" >
<html>
<body>
<table>
<tr>
<td>Gender:</td>
<td><select name="sex">
<%for(String item : sexList) { %>
<option value="<%=item%>"><%=item %></option><%}%>
</select>
</td>
<td>age:</td>
<td><select name="age">
<%for(String item : maritalStatus) { %>
<option value="<%=item%>"><%=item %></option><%}%>
</select>
</td>
<td><input type="submit" value="Go" name="Go"></td>
</tr>
</table>
</form>
</body>
</html>
and f_m.java
String gender = request.getParameter("sex");
String age = request.getParameter("age");
if(request.getParameter("Go") != null){
// i want to go to f.jsp to print the table
}
You must set the request attributes in the servlet before forwarding to the jsp. I suppose it could be something like :
// prepare the attributes
int ageList = new int[100];
int sexList = new String[]{"m", "f"};
for (int i=0; i<100; i++) { ageList[i] = i + 1; }
// put them in request
request.setAttribute("ageList", ageList);
request.setAttribute("sexList", sexList);
// and forward to the jsp.
request.getRequestDispatcher("f.jsp").forward(request, response);
You have two lists: sex and age. When you are trying to populate the select, you asked:
<%for(String item : sexList) { %>
Where is declared your sexList? May be you want to iterate through sex list? I mean, try:
<%for(String item : sex) { %>
And the same for second list:
<%for (String item : age) {%>
You must be more explicit what are you trying to do in your Servlet. I assume your main scope is to populate two selects in a form depending on two lists: sex and age. After this you want to take 2 selected values and pass them to servlet, the servlet will make a call to a database depending on these two values and will return a row from the table. After this you want to print this row in your f.jsp. If so, get the values from the select (and populate them right, like i mentioned below) in your servlet:
String sex = request.getParameter("sex");
String age = request.getParameter("age");
//method to call database, i.e List<Persons> list = DBHelper.checkSomething(sex, age);
if(...){
RequestDispatcher rd = request.getRequestDispatcher("f.jsp");
request.setAttribute("list", list);
rd.forward(request, response);
}
And i strongly recommend you to print your data based on a View. If you want to know more, read about MVC patterns.
current controller code:
#RequestMapping(value = "/city", method = RequestMethod.POST)
public String getWeather(#RequestParam("city") int city_id,
#RequestParam("text") String days, //this gives errrors, when i remove this line, then it is okay
Model model) {
logger.debug("Received request to show cities page");
//int city =
// Attach list of subscriptions to the Model
model.addAttribute("city", service.getCity(city_id));
// This will resolve to /WEB-INF/jsp/subscribers.jsp
return "city";
}
this is my JSP file(view):
<form method="post" action="/spring/krams/show/city">
Vali linn
<select name="city">
<c:forEach items="${cities}" var="city">
<option value="<c:out value="${city.id}" />"><c:out value="${city.city}" /></option>
</c:forEach>
</select><br>
Vali prognoos N päeva kohta(kirjuta 1 hetkese ilma jaoks)
<input type="text name="text">
<input type="submit" value="Test" name="submit" />
</form>
i want to get a value from the textbox named TEXT, but when i press the submit button then i get
HTTP Status 400 - The request sent by the client was syntactically incorrect ().
I am adding this answer so that you can accept it, as it was suggested by Bozho :)
There seems to be a problem in the HTML:
<input type="text name="text">
Change it to
<input type="text" name="text"> and try .
I think syntactically incorrect means the names specified in the #RequestParam annotations don't match with the request param names... possibly because of the above error in HTML.
Here is the a function on my servlet to test various things (I'm new to servlets althought I understadn the logic)
public void testParameters(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("\n>>>" + paramName);
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0){
out.print("No Value");
}else{
out.print(paramValue);
}
} else {
System.out.println("Number of parameters "+paramValues.length);
for(int i=0; i<paramValues.length; i++) {
out.print("" + paramValues[i]);
}
}
}
}
(this code I took from a tutorial and tweeked so it might just be something stupid)
I get everything working just fine but I was wandering in what cases does a parameter have several values?
Example: http://myhost/path?a=b&a=c&a=d
The parameter a has values b, c and d.
Example:
<form name="checkform" method="post" action="xxxxx">
Which langauge do you want to learn:<br>
<input type="checkbox" name="langtype" value="JSP">JSP
<input type="checkbox" name="langtype" value="PHP">PHP
<input type="checkbox" name="langtype" value="PERL">PERL
<input type="submit" name="b1" value="submit">
</form>
The form can allow you to select multiple values. If you ticks all check boxes , then the parameter langtype will have the values JSP , PHP and PERL