Spring MVC: Url path appending when posting the form - spring

i am new to spring mvc. i created a simple login application. but in my case the first time the for posting url and calling controller method correctly. in second time it's appending path with one more time of controller. first time post:
//localhost:8090/springmvc/account/login secong time in same page: //localhost:8090/springmvc/account/account/login. how do i fix this redirecting problem?
this my controller page:
#Controller
#RequestMapping("account")
public class AccountController {
AccountService service = new AccountService();
#RequestMapping(value = "account/default", method = RequestMethod.GET)
public ModelAndView RegisterUser() {
return new ModelAndView("/Account/Index","command",new User());
}
#RequestMapping(value = "/registeruser", method = RequestMethod.POST)
public ModelAndView RegisterUser(User user) {
user.setMessage(service.Register(user));
return new ModelAndView("/Account/Index", "command", user);
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView RegisterUer(User user) {
user.setMessage(service.Register(user));
return new ModelAndView("/Account/create", "command", user);
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView LoginUser(User user, ModelMap model) {
String msg = service.isAuthendicated(user) ? "Logged in" : "Failed";
user.setMessage(msg);
return new ModelAndView("/Account/Index", "command", user);
}
}
this my jsp page:
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:genericpage>
<jsp:body>
<h2>Login</h2>
<div>
${command.message} </div>
Register
<form:form action="account/login" method="post">
<div>
<form:input path="username" />
</div>
<div>
<form:input path="password" />
</div>
<input type="submit" value="Login">
</form:form>
</jsp:body>
</t:genericpage>
i used the tag library for common page:
<%#tag description="Master Page" pageEncoding="UTF-8"%>
<html>
<body>
<div id="pageheader">
<h2>WElcome</h2>
</div>
<div id="body">
<jsp:doBody />
</div>
<div id="pagefooter">
<p id="copyright">Copyright</p>
</div>
</body>
</html>

Depending on which version of Spring you're using, here are some options:
Spring 3.1 and lower OR Spring 3.2.3 and higher
You should have your urls/actions root-relative specific to your context path.
<form:form action="${pageContext.request.contextPath}/account/login" method="post">
Note: Spring 3.2.3 introduced servletRelativeAction but I've never used it.
Spring 3.2
Don't do anything, context path is prepended - this was actually a breaking change and eventually rolled back.
<form:form action="/account/login" method="post">
//will produce action="/springmvc/account/login"

Start your form action with a /.
<form:form action="/account/login" method="post">
By not doing it, you're telling the browser to append the action to the already existing URL on the address bar.
And where you have such links directly in HTML (by not using Spring's form:form), try to use c:url to properly construct the URL including the context path etc. This takes a lot of pain away from building proper relative URLs.
Register

Use ../ to get URL of your current context root:
<form:form action="../account/login" method="post">
from here

I tried with the spring tag bysetting only the relative path, it appends automatically the context path like:
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html lang="en">
<head>
<!-- ... -->
<spring:url value="/account/login" var="loginUrl" />
<form:form action="${loginUrl}" method="post">
The context path is set in application.properties as bellow:
server.servlet.contextPath=/MyApp
In the jsp page, it produces:
<a class="nav-link" href="/MyApp/account/login"> <i class="fas fa-play"></i> <span>Click here</span></a>

Related

How to get and display data on HTML when using Spring Json

I'm using Spring to get json data, and then i want to display data on HTML page.
This is my class:
#RequestMapping(value = "/selectCountNotification.do")
public ResponseEntity<List<EgovMap>> selectCountNotification(#RequestParam Map<String, Object> params, ModelMap model) throws Exception {
System.out.println("########################################");
System.out.println("####################check log####################");
System.out.println("########################################");
List<EgovMap> countNotification = orderDetailService.selectCountNotification(params);
model.addAttribute("countNotification", countNotification);
return ResponseEntity.ok(countNotification);
}
This is my header.jsp
<li>
<div class="notification" style="top: -5px;left: -40px;height: 36px;">
<i class='far fa-bell' style='font-size:20px'>
<div id="not">
<%# include file="/WEB-INF/jsp/sales/order/countNotify.jsp"%>
</div>
</i>
</div>
</li>
this is my countNotify.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<p>data: </p>
<c:forEach items="${countNotification}" var="comm">
<p><c:out value="${comm.countNotify}"/></p>
</c:forEach>
when i call by url:
http://localhost:8080/sales/order/selectCountNotification.do
I get data value from my database following as:
12
but when i run my jsp is countNotify.jsp, it cannot get any value, So how i can fix the problem ?

Why do am I getting error "java.lang.IllegalStateException" after putting <form:form> tag in jsp file of spring?

I have 2 tables, city and hotel_details in my database. I am trying to fetch the data from these tables and populating inside a form for registering the customer. But I am getting "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute" as error.
JSP file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<head>
<title>Search Hotels</title>
</head>
<body>
<h4>Search Hotels</h4>
<form:form action="search">
<table>
<tr>
<td>City:</td>
<td>
<form:select path="cities">
<form:options items="${cities}" />
</form:select>
</td>
</tr>
<tr>
<td>Hotel:</td>
<td>
<form:select path="hotels">
<form:options items="${hotels}" />
</form:select>
</td>
</tr>
<tr>
<td>Date:</td>
<td>
<input type="date" id="date" name="date">
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Check Availability">
</td>
</tr>
</table>
</form:form>
Controller
#Controller
public class HomeController {
//need a controller method to show the initial HTML form
#Autowired(required=true)
private CityDAO cityDAO;
#Autowired(required=true)
private HotelDetailsDAO hotelDetailsDAO;
#RequestMapping("/")
public String showCheckAvailablityForm(Model theModel) {
// get customers from the dao
//List<City> theCities = cityDAO.getCities();
List<String> theCities = cityDAO.getCities();
Set<String> theHotels = hotelDetailsDAO.getHotels();
// add the customers to the model
theModel.addAttribute("cities", theCities);
theModel.addAttribute("hotels", theHotels);
//printing the data fetched
System.out.println("In HomeController showCheckAvailability method where city name is being fetched from city table");
theCities.forEach((n) -> System.out.println(n));
System.out.println("printing hotels");
for (String temp : theHotels) {
System.out.print(temp + " ");
}
return "checkAvailability-form";
}
#RequestMapping("/search")
public String searchResult(#RequestParam("cityName") String theCityName, #RequestParam("hotelName") String theHotelName,Model model) {
System.out.println("processed successfully");
return null;
}
}
When you use <form:form> attribute, it requires you to specify model object that should be bound to form tag. If you don't specify any model attribute default name is used as command.
Following is the description of form:form tag from spring-form.tld -
<attribute>
<description>Name of the model attribute under which the form object is exposed.
Defaults to 'command'.</description>
<name>modelAttribute</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<description>Name of the model attribute under which the form object is exposed.
Defaults to 'command'.</description>
<name>commandName</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
As you don't have any model object bound to form, try removing form:form tag and use HTML form tag and also make sure you match input parameter names with method parameter names. i.e -
<form action="search">
...
</form>

Simple search in Spring MVC

I'm new to Spring MVC, and I'm trying to do a simple search.
Here's my Controller and View. How do I make the search to actually work?
The findTeamByName is already implemented from a interface and the Teams are already populated in memory.
Thank you in advance guys!
#Controller
public class SearchController {
#Autowired
SuperPlayerService sp;
#RequestMapping(value="/search")
public ModelAndView Search(#RequestParam(value = "searchTerm", required = false)
String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
}
JSP:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<t:MasterTag>
<jsp:attribute name="pageTitle"><c:out value="Search"/></jsp:attribute>
<jsp:attribute name="currentMenuName"><c:out value="Search"/></jsp:attribute>
<jsp:body>
<div class="row">
<div class="small-3 columns">
<input type="text" id="txt" name="searchString">
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search Teams</button>
</div>
</div>
<div class="row">
<div>
${searchTerm}
</div>
</div>
you can return your values i.e in a ModelAndView
#RequestMapping(value="/search/{searchTerm}")
public ModelAndView Search(#PathVariable("searchTerm") String pSearchTerm) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
This field can be accessed in your search.jsp by ${searchTerm}
EDIT:
if you want so search like: search?searchTerm=java then you can do it with:
#RequestMapping(value="/search")
public ModelAndView Search(#RequestParam(value = "searchTerm", required = false) String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
Spring MVC Controller method can accept a wide range of arguments and one of them is org.springframework.ui.Model.
You can add values to the Model which will become available in your JSP at requestScope.
In your case, your Java code would look like this
#RequestMapping(value = "/search")
public String Search(#RequestParam("searchString") String searchString, Model model) {
if(searchString != null){
Object searchResult = sp.findTeamByName(searchString);
model.addAttribute("searchResult", searchResult);
}
return "search";
}
In your JSP, you could then access the result as usual object in requestScope like ${searchResult}
Your JSP needs to look like:
<%# page contentType="text/html" pageEncoding="UTF-8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="t" tagdir="/WEB-INF/tags" %>
<t:MasterTag>
<jsp:attribute name="pageTitle"><c:out value="Search"/></jsp:attribute>
<jsp:attribute name="currentMenuName"><c:out value="Search"/></jsp:attribute>
<jsp:body>
<div></div>
<div class="row">
<form method="get" action="/search">
<div class="small-3 columns">
<input type="text" id ="txt" name="searchString" >
</div>
<div class="small-5 columns end">
<button id="button-id" type="submit">Search Teams</button>
</div>
<div>
${player.superTeam}
</div>
</form>
</div>
And your controller would be:
#Controller
public class SearchController {
#Autowired
SuperPlayerService sp;
#RequestMapping(value = "/search")
public String Search(#RequestParam("searchString") String searchString) {
if(searchString != null){
sp.findTeamByName(searchString);
}
return "search";
}
}

Pre-populate the Form field by formBackingObject method using standard html code in spring web

I just trying to pre-populate the form field in user form by formBackingObject.
I am using simple html code not spring tags to create the field.
Actually I'v tried with spring tag but spring tags for input filed is not working so I moved to simple html code but spring tags works for <form:form action=**> but not for <form:input path="name" />
I'v check taglib import segment but its fine and I don't understand if <form:form />
is working then why <form:input path="name" /> is not working.
I'm describing this because somewhere and someone from StackOverflow said that for getting benefit of formBackingObject, I'v to use spring tags for input field but in my case its not working.
Here I'm considering of formBackingObject only for pre-populating form field that what my question title suggest. Anyhow I'v to do it soon.
I'v gone through about 30-40 page link for finding of this solution but .....
I need a very simple example of it where jsp field getting value of object that is return by formBackingObject
I'm not familiar with annotation
Here is my tried and failed example
contact_form.jsp
<form:form action="edit.htm" commandName="contact" method="POST">
Name:<input type="text" name="name" value=${contact.name} /><br>
Address:<input type="text" name="address" value=${contact.address}/><br>
<input type="submit" value="Submit"/><br>
EditController
public class EditController extends SimpleFormController {
private static Contact cont = new Contact();
static {
cont.setAddress("aaa");
cont.setName("bbb");
}
#Override
protected void doSubmitAction(Object command) throws Exception {
System.out.println("In do submit method");
}
#Override
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
System.out.println("In FormBackingObject");
return cont;
}
spring-servlet.xml
<bean id="/edit.htm" class="tryPack7.EditController">
<property name="CommandClass" value="tryPack7.Contact" />
<property name="commandName" value="contact" />
<property name="formView" value="contact_form" />
<property name="successView" value="success" />
</bean>
Thanks in advance
Assuming you have specified handler mapping in your confog xml file:
Make sure you have jsp on similar lines as below:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<form:form commandName="contact" method="POST">
<table>
<tr >
<td>Name:<form:input path="name"/></td>
</tr>
<tr >
<td>Address:<form:input path="address"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Also, rather than using static way, I would suggest to initialize contact form in formBackingObject as shown below:
public class EditController extends SimpleFormController {
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Contact contact=(Contact)formBackingObject(request);
return new ModelAndView("contact_form","contact",contact);
}
public Object formBackingObject(HttpServletRequest req)
{
Contact contact = new Contact();
contact.setAddress("aaa");
contact.setName("bbb");
return contact;
}
}

Pass selected value from a select tag to an action using Struts2 and Dojo

I'm trying to pass the selected value of a select tag to an action through ajax when the onchange event is triggered but, for some reason, the action receives the parameter as null.
Here is the code of the jsp:
<%#taglib prefix="s" uri="/struts-tags" %>
<%#taglib prefix="sx" uri="/struts-dojo-tags" %>
<div id="navegacion_proyectos">
<s:select name="id_proyecto_actual" id="proyecto_actual_select" list="proyectos" listValue="titulo_proyecto" listKey="id_proyecto"/>
<s:url id="cambiar_proyecto_actual_url" value="/cambiar_proyecto_actual.action" />
<sx:bind sources="proyecto_actual_select" events="onchange" href="%{cambiar_proyecto_actual_url}" />
</div>
And here is the code of the action:
public class BLProyecto extends ActionSupport {
private String id_proyecto_actual;
public String cambiarProyectoActual() {
Map sesion = ActionContext.getContext().getSession();
sesion.put("proyecto_actual", id_proyecto_actual);
return SUCCESS;
}
public String getId_proyecto_actual() {
return id_proyecto_actual;
}
public void setId_proyecto_actual(String id_proyecto_actual) {
this.id_proyecto_actual = id_proyecto_actual;
}
}
I'm debbuging the code and the id_proyecto_actual parameter is shown as null. What do you think is the problem?
Thank you all, i found the answer. Instead of following an url when the event is triggered, i just submit a form. Like this:
<%#taglib prefix="s" uri="/struts-tags" %>
<%#taglib prefix="sx" uri="/struts-dojo-tags" %>
<div id="navegacion_proyectos">
<s:form id="cambiar_proyecto_actual_form" action="cambiar_proyecto_actual">
<s:select name="id_proyecto_actual" id="proyecto_actual_select" list="proyectos" listValue="titulo_proyecto" listKey="id_proyecto"/>
</s:form>
<sx:bind sources="proyecto_actual_select" formId="cambiar_proyecto_actual_form" targets="pantalla_principal" events="onchange" />
</div>

Resources