Redirect-Spring -MVC - how redirect control to home page? - spring

#RequestMapping(value= "/redirect", method=RequestMethod.GET)
public String redirect()
{
return "redirect:onLogin";
}
how to redirect control back to home page? the above code for retrieving admin home page is not working.

This should work:
#RequestMapping(value= "/redirect", method=RequestMethod.GET)
public String redirect(){
return "redirect:/onLogin";
}
You can also pass parameters on redirect to show Login Failure messages, something like this:
#RequestMapping(value= "/redirect", method=RequestMethod.GET)
public String redirect(){
return "redirect:/onLogin?success=false";
}
And then in your login.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:if test="${param.success eq false}">
<div class="alert alert-danger alert-dismissible">
<button class="close" aria-hidden="true" type="button" data-dismiss="alert">×</button>
<h4><i class="icon fa fa-ban"></i> Login Failed!</h4>
</div>
</c:if>

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 ?

How to set the login/logout link visible/invisible with Thymeleaf?

I am a beginner in Spring Framework. I try to make login and logout Thymeleaf pages. Below codes are the Spring Boot login/logout files with Thymeleaf.
First, Login Controllers codes
#Autowired
private HttpSession userSession;
#Autowired
private UserService userService;
#RequestMapping("/users/login")
public String login(LoginForm loginForm) {
return "users/login";
}
#RequestMapping(value="/users/login", method = RequestMethod.POST)
public String loginPage(#Valid LoginForm loginForm, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
userSession.setAttribute("blogLogin", false);
System.out.println("Wrong Input!!");
return "users/login";
}
if(!userService.authenticate(loginForm.getUsername(), loginForm.getPassword())) {
userSession.setAttribute("blogLogin", false);
System.out.println("login failed!!");
return "users/login";
}
userSession.setAttribute("blogLogin", true);
System.out.println("Login succesfully.");
return "redirect:/";
}
And the layout.html codes using thymeleaf.
<header th:fragment="site-header" th:remove="tag">
<header>
<a href="index.html" th:href="#{/}">
<img src="../public/img/site-logo.png" th:src="#{/img/site-logo.png}" />
</a>
Home
Log in
Log out
Register
Users
Posts
Write Post
<div id="logged-in-info"><span>Hello, <b>(user)</b></span>
<form method="post" th:action="#{/users/logout}">
<input type="submit" value="Log out"/>
</form>
</div>
</header>
</header>
The problem is I have no idea how to make login/logout link toggling codes using th:if statement of thymeleaf. As you know login link and logout link can not be displayed simultaneously.
you can check whether user is authenticated or anonymous like below and can make decisions.
<div sec:authorize="#{isAuthenticated()}">
<a th:href="#{/logout}">Log out</a>
</div>
<div sec:authorize="#{isAnonymous()}">
<a th:href="#{/login}">Log in</a>
</div>

Strange behavior observed with Spring 3.1 Controller

I'm using Spring 3.1 and tiles to develop a MVC app.
I have a JSP page (header.jsp) and 2 controllers (HomeController and SignupController).
The header.jsp is like this:
<s:url var="login_url" value="${loginUrl}" />
<s:url var="signup_url" value="${signUpFormUrl}" />
<a class="btn btn-primary" href="${login_url}">Login</a>
<a class="btn btn-default" href="${signup_url}">Signup</a>
The HomeController.java is like this (the /login/form URL is configured to be used by spring security as login page):
#Controller
public class HomeController {
#RequestMapping({"/", "/home"})
public String showHomePage(final Map<String, Object> model) {
return "home";
}
#ModelAttribute("loginUrl")
public String getLoginUrl() {
return "/login/form";
}
......
}
The SignupController.java is like this:
#Controller
public class SignupController {
.....
#RequestMapping(value = "/signup/form")
public String signup(#ModelAttribute SignupForm signupForm) {
return "signup/form";
}
#ModelAttribute("signUpFormUrl")
public String getSignUpFormUrl() {
return "/signup/form";
}
.....
}
What's strange is that like it is presented above I got this result when the page is rendered:
<a class="btn btn-primary" href="/appContext/login/form">Login</a>
<a class="btn btn-default" href="">Signup</a>
So the ended up with empty href value.
BUT when I moved around the signup controller code regarding the signup (the RequestMapping and the ModelAttribute method) to the home controller, it worked as expected:
<a class="btn btn-primary" href="/appContext/login/form">Login</a>
<a class="btn btn-default" href="/appContext/signup/form">Signup</a>
Is it possible to use RequestMapping from different Controller inside a same view?
Can someone has a view on what is going on here?
Thanks in advance. I can supply anything other (config?) needed to understand further the problem.

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";
}
}

Spring MVC: Url path appending when posting the form

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>

Resources