I have a code in Java that uses the Spring framework to call different methods as per form action in JSP. However, it's not working as expected. The two forms work separately i.e. when one is removed. But together it calls the same method whichever is declared first in the form action.
JAVA Method:
package com.example.demo.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.dao.AlienRepo;
import com.example.demo.model.Alien;
#Controller
public class AlienController {
#Autowired
AlienRepo repo;
#RequestMapping("/")
public String home() {
return "home.jsp";
}
#RequestMapping("add")
public String add(Alien alien)
{
repo.save(alien);
return "home.jsp";
}
#RequestMapping("get")
public ModelAndView get(String text)
{
ModelAndView mv = new ModelAndView();
int id = Integer.parseInt(text);
mv.setViewName("show.jsp");
mv.addObject("alien", repo.findById(id));
return mv;
}
}
JSP File:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="get">
<input type="text" name="text"><br>
<input type="submit">
<form/>
<form action="add">
<input type="text" name="aid"><br>
<input type="text" name="aname"><br>
<input type="submit">
<form/>
</html>
I cannot find any error and as I said independently they're working fine. So, all other files should be correct and if needed can be provided. Could you please help me in resolving this starnage issue?
You have to specify what your method params are, since you are using get method so #RequestParam annotation will be used eg:-
#RequestMapping("/add")
public String add(#RequestParam("aid") String aid, #RequestParam("aname") String aname)
{
Alien alien = new Alien();
alien.setId(aid);
alien.setName(aname);
repo.save(alien);
return "home.jsp";
}
and
#RequestMapping("/get")
public ModelAndView get(#RequestParam("text") String text)
{
ModelAndView mv = new ModelAndView();
int id = Integer.parseInt(text);
mv.setViewName("show.jsp");
mv.addObject("alien", repo.findById(id));
return mv;
}
Fixed the jsp file with below code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="get">
<input type="text" name="text"><br>
<input type="submit">
</form>
<form action="add">
<input type="text" name="aid"><br>
<input type="text" name="aname"><br>
<input type="submit">
</form>
</body>
</html>
Related
I understand how to return a string from my controller as demonstrated here
I could modify this to take a text value from a html form.
However, when i try to retrieve number 'salary' from my form, it gives me an error of "There was an unexpected error (type=Not Found, status=404)." What needs to be fixed?
here is my ServingWebContent.java
package com.example.servingwebcontent;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ServingWebContentApplication {
public static void main(String[] args) {
SpringApplication.run(ServingWebContentApplication.class, args);
}
}
here is BudgetingController.java
package com.example.servingwebcontent;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class BudgetingController {
#GetMapping("/greeting")
public String greeting(#RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
#GetMapping("/results")
public int results(#RequestParam(name="salary", required=true) int salary, Model model) {
model.addAttribute("salary", salary);
return salary;
}
}
here is index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org"></html>
<head>
<title>Budgeting Tool</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<form action="/results.html" method="GET">
<div>
<header>
<h3><strong>Monthly Income</strong></h3>
</header></div>
<div>
<label>Monthly Salary:</label>
<input type="number" name="salary" min="0" required>
</div>
<!--- Submits to results.html --->
<input type="submit" value="Submit">
</form>
</body>
</html>
And finally, here is results.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Results</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text=" ${salary} " />
</body>
</html>
The normal form submission method is POST.
This case logic is View->Controller->View. I guess this example from https://spring.io/. So this contact path is "/". You can change index.html and BudgetingController.java as below.
This question already has an answer here:
Servlet send response to JSP
(1 answer)
Closed 3 years ago.
how do i set the jsp file as response in my servlet ?And what kind of expression do i need to use in the jsp page?
this is the form
<html>
<head>
<title>Select your Hobby</title>
</head>
<body>
<form method="POST" action="SelectHobby">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
the servlet
package com.example.web;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HobbyServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
String hobby = request.getParameter("hobby");
}
}
and this is the jsp in wich i want to see the hobby in the body
<html>
<head>
<title>These are your hobbies</title>
</head>
<body>
<%
</body>
</html>
I recomend you to read this post. JSTL will help you. I suppose you mapped your servlet. Here is a quick example:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method="POST" action="testservlet">
<p> Choose a Hobby:
</p>
<select name="hobby" size="1">
<option>horse skiing
<option>extreme knitting
<option>alpine scuba
<option>speed dating
</select>
<br><br>
<center>
<input type="SUBMIT">
</center>
</form>
</body>
</html>
The servlet:
#WebServlet(name = "test", urlPatterns = { "/testservlet" })
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hobby = request.getParameter("hobby");
request.setAttribute("theHobby", hobby);
request.getRequestDispatcher("hobbypage.jsp").forward(request, response);
}
I defined an attribute called theHobby to hold the value from the selected hobby in the first page. I also created a page called hobbypage.jsp where I want to send the value to.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hobby: ${theHobby}
</body>
</html>
With JSTL you can call the attribute through the name you defined like this ${nameOfAttribute}.
I'm learning spring mvc and understand the use of the Model and ModelAttribute. However, I can't retrieve the Model's attribute so I resorted to using the JSP param value. What am I doing wrong? I checked the model still had a value for the attribute using #ModelAttribute("username") User user / user.username and sure enough it does.
Controller
package login.user;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginUser {
#RequestMapping("/")
public String showMenu()
{
return "menu";
}
#RequestMapping("login")
public String loginUser(Model model)
{
User newUser = new User();
model.addAttribute("user", newUser);
return "login-user";
}
#RequestMapping("processUser")
public String processUser(Model model)
{
Option newOption = new Option();
model.addAttribute("option", newOption);
return "process-login";
}
}
User
package login.user;
public class User {
private String username;
private char password[];
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public char[] getPassword() {
return password;
}
public void setPassword(char[] password) {
this.password = password;
}
}
login-user.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<link href="<c:url value="/resources/css/style.css" />" rel="stylesheet" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login User</title>
</head>
<body>
<div>
<form:form action="processUser" modelAttribute="user">
<table>
<tr>
<td>Username:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<form:input type="password" path="password" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="Login" />
</td>
</tr>
</table>
</form:form>
</div>
</body>
</html>
process-login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="option">
<h3>Welcome ${param.username}. Please choose an activity below</h3> <---- changed from ${user.username}
<div>
<form:select path="option">
<form:option value="Email" label="Email"></form:option>
<form:option value="Enter Recipe" label="Enter Recipe"></form:option>
<form:option value="Retrieve Recipe" label="Retrieve Recipe"></form:option>
</form:select>
</div>
</form:form>
</body>
</html>
Just change your last #RequestMapping method as follows:
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user, Model model)
{
Option newOption = new Option();
model.addAttribute("user", user);
model.addAttribute("option", newOption);
return "process-login";
}
Now use ${user.username} in jsp.
The spring model data is stored in the standard Java request scope. If you are trying to get the username, you need to add it in the request scope again. So, you can write the processUser method as follows.
#RequestMapping("processUser")
public String processUser(#ModelAttribute("user") User user,Model model)
{
Option newOption = new Option();
// do stuff with user data
newOption.setUsername(user.getUsername());
model.addAttribute("option", newOption);
return "process-login";
}
So, you should be able to get it in the jsp as ${option.username}.
I am new to Spring MVC. I made a simple form when button is clicked the form values send to the controller and set in the second view. But when i click the button it is giving me the error
The request sent by the client was syntactically incorrect.
Here is my code:
Controller:
#Controller
#RequestMapping(value="/admissionform")
public class StudentAdmissionController {
#RequestMapping(value="/form.html", method = GET)
public ModelAndView getStudentForm() {
ModelAndView model = new ModelAndView("StudentForm");
return model;
}
#RequestMapping(value="/submit.html", method = POST)
public ModelAndView submitStudentForm(#RequestParam("name") String name,
#RequestParam("password") String password) {
ModelAndView model = new ModelAndView("SubmitForm");
model.addObject("msg", "Name is : "+name + " Password is : " + password);
return model;
}
}
StudentForm:
<%# 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>
<title>Student Form</title>
</head>
<body>
<div class="modal-body" id="main-body">
<form action="submit.html" method="post">
<div>
<label>Email address:</label>
<input class="form-control" id="email" name="email">
</div>
<div >
<label for="pwd">Password:</label>
<input id="pwd" name="password">
</div>
<input type="submit" value="Submit"/>
</form>
</div>
</body>
</html>
SubmitForm:
<%# 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>
<title>Form Submitted</title>
</head>
<body>
<div>${msg}</div>
</body>
</html>
Tell me what is the mistake that i am doing in the code. I shall be thankful :)
By default parameters annotated with #RequestParam are mandatory. So, those parameters should be present in client requests. In your submitStudentForm method you have two required parameters named name and password:
#RequestMapping(...)
public ModelAndView submitStudentForm(#RequestParam("name") String name,
#RequestParam("password") String password) { ... }
Then you should pass those parameters with the exact same names in your from. Currently, you're passing the password parameter:
<div>
<label for="pwd">Password:</label>
<input id="pwd" name="password">
</div>
But failing to do so for the unfortunate name parameter. I guess you should rename the email parameter to name:
div>
<label>Email address:</label>
<input class="form-control" id="email" name="name">
</div>
For more info, you can checkout the Spring documentation.
I have a JSP that receives a collection list from an action class. I am iterating through that list and I wish to set the values of that list to another object inside another action class through a form request. When I use the displayMovies.jsp when I use the <s:propertytag in the iterator it displays on the different objects in the collection. I want to save or pass each of those objects in the collection to a different action class.
displayMovies.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.sans.model.Movie" %>
<%# taglib prefix="s" uri="/struts-tags"%>
<!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>
Movie retrieval Page
<br />
<s:iterator value="movieRetrievedArray" var="movieS">
<s:form action="movieDetails.action" method="post" id="movieDetailsForm">
<s:property value="title"/><br />
<s:property value="releaseDate"/><br />
<s:hidden name="movieDetailedInformation.title" value="%{title}" id="hiddenMovie" />
<img src="<s:property value="posterPath" />" onClick="test()">
</s:form>
<br />
<br />
</s:iterator>
<script type="text/javascript">
function test() {
document.getElementById("movieDetailsForm").submit();
}
</script>
</body>
</html>
MovieDetailsActions.java
package com.esi.actions;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sans.model.Movie;
#SuppressWarnings("serial")
#Results({
#Result(name="success", location="/RetrieveMovies/movieDetails.jsp"),
#Result(name="input", location="/RetrieveMovies/movieError.jsp")
})
public class MovieDetailsAction extends ActionSupport {
private Movie movieDetailedInformation = new Movie();
#Action(value="movieDetails")
public String execute() {
System.out.println(movieDetailedInformation.getTitle());
return SUCCESS;
}
public Movie getMovieDetailedInformation() {
return movieDetailedInformation;
}
public void setMovieDetailedInformation(Movie movieDetailedInformation) {
this.movieDetailedInformation = movieDetailedInformation;
}
}
You should use status variable on iterator tag.
<s:form action="movieDetails.action" method="post" id="movieDetailsForm">
<s:iterator value="movieRetrievedArray" var="movieS" status="status">
<s:property value="title"/><br />
<s:property value="releaseDate"/><br />
<s:hidden name="movieDetailedInformationList[%{#status.index}].title" value="%{title}" id="hiddenMovie" />
<br />
<br />
</s:iterator>
<img src="<s:property value="posterPath" />" onClick="test()">
</s:form>
The movieDetailedInformationList is
private List<Movie> movieDetailedInformationList;
public List<Movie> getMovieDetailedInformationList() { return movieDetailedInformationList; }
You don't need to initialize movieDetailedInformationList, because Struts2 populate it with parameters from the post request.
The Movie class should be public and have default constructor, the public setter for title is necessary.