Can's show one login page after logout - spring-boot

My app use frame.
here index.html:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
</head>
<frameset cols="15%,*">
<frame src="navigator" name="navigator" scrolling="no" noresize/>
<frame src="welcome" name="main"/>
</frameset>
</html>
Here login controller:
#Controller
public class LoginController {
#Value("${spring.application.name}")
private String appName;
private static Logger logger = LogManager.getLogger(LoginController.class);
/*-
#RequestMapping("/")
#ResponseBody
public String index() {
return "Hello!";
}
*/
// Login form
#RequestMapping("/login.html")
public String login(Model model) {
logger.info("open_login.html");
model.addAttribute("appName", appName);
return "login.html";
}
// Login form with error
#RequestMapping("/login-error.html")
public String loginError(Model model) {
model.addAttribute("appName", appName);
model.addAttribute("loginError", true);
return "login.html";
}
}
and here result:
and after success login (show frames)
When I press button logout then call my custom logout handler:
public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler implements LogoutSuccessHandler {
private static Logger logger = LogManager.getLogger(CustomLogoutSuccessHandler.class);
#Override
public void onLogoutSuccess(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication)
throws IOException, ServletException {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath() + "/login.html");
}
}
But here result after press Logout
But I need only ONE page (login.html, without frames)

You will have to add below javascript to the login.html.
if ( window.location !== window.parent.location ) {
// We're deeper than one down
window.parent.location=window.location
}

Related

Spring mvc jsp not rendering

Getting started with Spring MVC, when I enter my page it loads the welcome.jsp as plain text(just shows source), I know people asked this 1 million times, But I looked over many of the questions and didn't find my solution as most of them using XML and I use java.. I am still not experienced enough to switch between the two.
conf.class :
public class conf extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/views/");
bean.setSuffix(".jsp");
return bean;
}
}
ServletInitializer.class:
public class ServletInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Demo4Application.class,conf.class);
}
}
welCont.class (Controller) :
#Controller
#RequestMapping("/spring/")
public class welCont {
#RequestMapping(method = RequestMethod.GET)
public String wel(ModelMap model)
{
model.addAttribute("test","testme");
return "welcome";
}
}
welcome.jsp :
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>${test}</h2>
</body>
</html>
I think wrong thing is
#RequestMapping("/spring/")
normally "/spring/" request should go to DispatcherServlet. Not sure in spring boot.
try with this.
#Controller
public class WelCont {
#RequestMapping(value="/foldername_if_avaiable/welcome/", method=RequestMethod.GET )
public ModelAndView wel(
#RequestParam(value="id", required=false) String id,
ModelMap model,
HttpSession session,
HttpServletRequest req) throws Exception {
model.addAttribute("test","testme");
return new ModelAndView("/foldername_if_avaiable/welcome", model);
}
}
reference

Controller registers, but gets 404 when returning data

This is initializer for Spring. I'm not using any .xml files.
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
#Configuration
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{
WebAppConfig.class,
SecurityConfig.class,
DatabaseConfig.class,
DataSourceGenerator.class,
QuartzConfig.class,
QueueConfig.class
};
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addFilter(
"facilityFilter", new FacilityServletFilter()
).addMappingForUrlPatterns(null, false, "/api/*");
servletContext.addFilter(
"hmacFilter", new HmacFilter()
).addMappingForUrlPatterns(null, false, "/api/*");
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
}
This is one of my controllers.
#Controller
#RequestMapping(value = "/install")
public class HelloController {
#RequestMapping(value = "/hi", method = RequestMethod.GET,
consumes = "*/*", produces = "text/html")
public String sayHello(){
return "<html> <head> <title>API</title>" +
"</head> <body> <h1>Welcome to the Eric</h1>" +
"</body> </html>";
}
}
All my other controllers appear to work properly, but this one returns a 404 error when I try to hit the endpoint. The code is hit in the debugger when I invoke it via Postman.
Add #ResponseBody to your controller method, else spring would try to search for an view with the name "<html> <head> <title>API</title>..."
#Controller
#RequestMapping(value = "/install")
public class HelloController {
#RequestMapping(value = "/hi", method = RequestMethod.GET, consumes = "*/*", produces = "text/html")
#ResponseBody
public String sayHello(){
return "<html> <head> <title>API</title>" +
"</head> <body> <h1>Welcome to the Eric</h1>" +
"</body> </html>";
}
}
As suggested by Raplh you can do that but if you plan to have more of these methods might as well just replace #Controller with #RestController

CharResponseWrapper captured content is empty

I have tried the following example to replace some content in my servlet response.
Programming Customized Requests and Responses
test.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"></meta>
<link th:href="#{/css/test.css}" rel="stylesheet"></link>
<title>Test</title>
</head>
<body>
<p class="forbiddenClass">Test!</p>
</body>
</html>
test.css:
.forbiddenClass {
color: red;
}
CharResponseWrapper.java
public class CharResponseWrapper extends HttpServletResponseWrapper {
private final CharArrayWriter output;
public CharResponseWrapper(final HttpServletResponse response) {
super(response);
output = new CharArrayWriter();
}
public String toString() {
return output.toString();
}
public PrintWriter getWriter() {
return new PrintWriter(output);
}
}
ClassReplacementFilter.java
#Component
public class ClassReplacementFilter extends GenericFilterBean {
#Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
final CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, wrapper);
String content = wrapper.toString();
if (StringUtils.isEmpty(content)) {
System.out.println("content is empty for content type: " + response.getContentType());
} else {
content = content.replaceAll("forbiddenClass", "correctClass");
response.setContentLength(content.getBytes().length);
response.getOutputStream().write(content.getBytes());
}
}
}
As you might see, I want to replace the string forbiddenClass with correctClass, but it only works for the html file. The content of test.css does not change and the following message of the filter is printed to output.
content is empty for content type: text/css;charset=UTF-8
Why is the content empty for test.css?
Why is the content empty for test.css?
Because you only captured whatever is written to response.getWriter(), not whatever is written to response.getOutputStream().
You need the HttpServletResponseWrapper implementation as shown in bottom of this answer to a related question: Catch-all servlet filter that should capture ALL HTML input content for manipulation, works only intermittently.

Thymeleaf don't evaluate custom dialects / processors

I recently add some custom dialects and processor to my spring-boot application, but when I put them in the page like that:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" xmlns:form="http://form" xmlns:field="http://field">
<body>
<form:form>
...
</form:form>
</body>
</html>
and open the page in the browser, the tags is not evaluated to the right value. The FormDialect is this:
public class FormDialect extends AbstractDialect {
public FormDialect() {
super();
}
//
// All of this dialect's attributes and/or tags
// will start with 'hello:'
//
public String getPrefix() {
return "form";
}
//
// The processors.
//
#Override
public Set<IProcessor> getProcessors() {
final Set<IProcessor> processor = new HashSet<IProcessor>();
processor.add(new Form());
return processor;
}
}
and the FormProcessor is that:
public class Form extends AbstractProcessor {
#Override
public ProcessorResult doProcess(Arguments arguments,ProcessorMatchingContext context,Node node) {
Element form = new Element("form");
node.setProcessable(true);
node.getParent().insertBefore(node, form);
return ProcessorResult.OK;
}
#Override
public int getPrecedence() {
return 0;
}
#Override
public IProcessorMatcher<? extends Node> getMatcher() {
return new ElementNameProcessorMatcher("form");
}
}
what I am doing wrong here?
I get the Dialect registered in my web configuration with:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public FormDialect formDialect() {
return new FormDialect();
}
}
For the rest I tried with your code and the Dialect is still registered:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:form="">
<form:form>
...
</form:form>
</html>
Dialect:
import java.util.HashSet;
import java.util.Set;
import org.pgg.photodb.web.thymeleaf.processor.Form;
import org.thymeleaf.dialect.AbstractDialect;
import org.thymeleaf.processor.IProcessor;
public class FormDialect extends AbstractDialect {
#Override
public String getPrefix() {
return "form";
}
#Override
public Set<IProcessor> getProcessors() {
final Set<IProcessor> processor = new HashSet<IProcessor>();
processor.add(new Form());
return processor;
}
}
and Processor
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.dom.Node;
import org.thymeleaf.processor.AbstractProcessor;
import org.thymeleaf.processor.ElementNameProcessorMatcher;
import org.thymeleaf.processor.IProcessorMatcher;
import org.thymeleaf.processor.ProcessorMatchingContext;
import org.thymeleaf.processor.ProcessorResult;
public class Form extends AbstractProcessor {
#Override
public ProcessorResult doProcess(Arguments arguments, ProcessorMatchingContext context, Node node) {
Element form = new Element("form");
node.setProcessable(true);
node.getParent().insertBefore(node, form);
return ProcessorResult.OK;
}
#Override
public int getPrecedence() {
return 0;
}
#Override
public IProcessorMatcher<? extends Node> getMatcher() {
return new ElementNameProcessorMatcher("form");
}
}

Can not populate drop down list using hibernate query in spring mvc

Here is my controller. In this I am using the reference data to send the List to my JSP page. Read the list into countryList which contains list of all country names populated using hibernate query
#SuppressWarnings("deprecation")
public class customerController extends SimpleFormController {
public customerController() {
setCommandClass(customer.class);
setCommandName("customer");
}
private customerDAO customerDAO;
public void setcustomerDAO(customerDAO customerDAO) {
this.customerDAO = customerDAO;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
customer customer = (customer) command;
customerDAO.savecustomer(customer);
return new ModelAndView("customerSuccess");
}
#Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Map referenceData = new HashMap();
List countryList = customerDAO.listCountries();
referenceData.put("country", countryList);
return referenceData;
}
public ModelAndView redirect(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelMap modelMap = new ModelMap();
return new ModelAndView("customer", modelMap);
}
}
Here is my DAO implementation:
public class customerDAOImpl implements customerDAO {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Override
public void savecustomer(customer customer) {
hibernateTemplate.saveOrUpdate(customer);
}
#Override
#SuppressWarnings("unchecked")
public List<customer> listcustomer() {
return hibernateTemplate.find("from customer");
}
#Override
#SuppressWarnings("unchecked")
public List<countries> listCountries() {
return hibernateTemplate.find("from customer.countries");
}
}
Here is my JSP code:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<form:form commandName="customer" name="customer" method="post">
<tr>
<td align="right" class="para">Country:</td>
<td align="left"><span id="spryselect2">
<form:select path="country" id="country">
<form:options items="${country}" itemValue="country_id" itemLabel="name" />
</form:select>
<span class="selectRequiredMsg">Please select country.</span></span></td>
</tr>
But nothing is getting populated into the drop down.
Name the list of countries something representing multiple countries, like, say, "countries".
There's also a customer country property.

Resources