Form lost Polish characters - java

I lost my mind trying to add Polish characters like "ą, ę, ć, ł" etc. to my MySQL database. Steps I have done :
Set up "Method comparing inscription" to utf8_unicode_ciin my MySQL database.
Set up for all varchar fields Method comparing inscription to utf8_unicode_ci
In application.properties set :
spring.datasource.url: jdbc:mysql://localhost:3306/database?characterEncoding=UTF-8
spring.mandatory-file-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.datasource.sqlScriptEncoding=UTF-8
To be sure in all HTML files add in <head></head> brackets <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
Set the configuration file like this:
#Configuration
public class Config extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
}
}
When I try to add some Polish words in my controller, for example player.setName("ĆŁĘ")- it's OK. The name in the database is correctly inserted.
But when I take the name of player in controller from Thymeleaf, it returns ÄÅÄ instead of CŁĘ. My form attendant Thymeleaf looks like this:
<form action="#" th:action="#{/editPlayer}" th:object="${player}" method="post">
<div class="info">Name:</div>
<div class="error" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"/>
<input type="text" th:field="*{name}" placeholder="Name" th:class="${#fields.hasErrors('name')}? 'error'"/><br/>
<input type="button" id="cancel" class="button2 button-cancel" value="CANCEL"/>
<input type="submit" class="button button-submit" value="SUBMIT"/>
</form>
I have no idea what else I need to do to get correct characters from Thymeleaf.

I found solution. It take me some steps:
Add annotation #EnableWebSecurity to my Config class,
Write http.addFilterBefore(filter, CsrfFilter.class) under filter.setForceEncoding(true)
Create class ApplicationSecurityInitializer
public class ApplicationSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
#Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
super.beforeSpringSecurityFilterChain(servletContext);
FilterRegistration.Dynamic characterEncodingFilter;
characterEncodingFilter = servletContext.addFilter("encodingFilter",
new CharacterEncodingFilter());
characterEncodingFilter.setInitParameter("encoding", "UTF-8");
characterEncodingFilter.setInitParameter("forceEncoding", "true");
characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
}
}
Take a breath and be calm :)

Related

spring security always returning anonymousUser

i have a spring security implementation for the existing spring based application, it always returns anonymous user regardless of what i supply at login page.
#Configuration
#EnableWebSecurity
#EnableGlobalAuthentication
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("bill").password("abc123").roles("ROLE_USER");
auth.inMemoryAuthentication().withUser("admin").password("root123").roles("ADMIN");
auth.inMemoryAuthentication().withUser("dba").password("root123").roles("ADMIN","DBA");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("configure called");
http.authorizeRequests()
.antMatchers("/*").access("hasRole('ROLE_USER')")
//.antMatchers("/*").access("IS_AUTHENTICATED")
.and().formLogin().loginPage("/login")
.usernameParameter("user").passwordParameter("passWord")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
form from login.jsp:
<form action="/Patching/Authen" name="form1" method="POST" onsubmit="return validateForm();"><br><br>
<h1>User Login</h1>
<table>
<tr>
<th>Username</th>
<td><input type="text" name="username" id="user" required/></td>
</tr>
<tr>
<th>Password</th>
<td><input type="password" name="password" required/></td>
</tr>
</table><br><input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<input type="submit"><br><br><br>
</form>
While i do at my controller post the form submit :
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
anonymous authentication is returned.
P.S. I already have a login.jsp where I have the configured user and password parameter.
Help appreciated.
I tried whatever you suggest above...what worked for me is changing the form action on the login.jsp to "login" and modifying configure to
http.authorizeRequests()
.antMatchers("/", "/home").access("hasRole('USER')")
.antMatchers("/resources/**").permitAll()
//.antMatchers("/*").access("IS_AUTHENTICATED")
.anyRequest().authenticated()
.and().csrf().disable().formLogin().loginPage("/login").permitAll()
//.loginProcessingUrl("/Authen")
.usernameParameter("user").passwordParameter("passWord")
.defaultSuccessUrl("/Authen")
.failureUrl("/failedLogin")
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
further I need to work on the flow of the existing implementation along with spring security.
Your config do not mention any authenticated uri pattern.
You need to add
anyRequest().authenticated()

How to make Spring Boot see my images from resources

Hi I Have such images in resources/static and put them into my index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8"/>
<title>Test</title>
</head>
<body>
<div>
<form method="POST" enctype="multipart/form-data" action="/">
<p>
<img src="../static/image1.png" alt="Image 1"/>
<img src="../static/image2.png" alt="Image 2"/>
<tr>
<td></td>
<td><input type="submit" value="Test"/></td>
</tr>
</p>
</form>
</div>
<div th:if="${success}">
<img src="/static/result.png"/>
</div>
</body>
</html>
Then, in ResourceConfig
#Configuration
#EnableWebMvc
#ComponentScan
public class ResourceConfig extends WebMvcConfigurerAdapter {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/images/",
"classpath:/static/", "classpath:/public/" };
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/webjars/**")) {
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/META-INF/resources/webjars/");
}
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**").addResourceLocations(
CLASSPATH_RESOURCE_LOCATIONS);
}
}
}
The problem is, that application doesn't see my images. I've added resource handler, but it hasn't worked. The output is
Output
This #Override method addResourceHandlers shows Spring Framework where are all you static resources. So... your folder which contains images which are also a static resource must be under your root static resource handler. Set it like this and create this folder under WebContent folder in your project.
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
}
This line in your html template
<div th:if="${success}">
makes me think you are using Thymeleaf as your template engine. If that is that case, you should use this to refer to static content:
<img th:src="#{/result.png}"}/>
if your png file is indeed in the root of your static folder.

Spring Boot CSS Showing up blank / not loading after trying everything

I am really new to Spring Boot, and I am currently going through the book. Spring Boot in action.
I created and complied my first web simple web app fine, expect the css file shows up blank in the console. I have already looked up the following post:
Spring Boot - CSS not loading
Spring Boot CSS Stripped
I am using Thymleaves and my css file is placed within the static folder as the post and book states, but nothing shows up. my current external link, seems to be the correct way too.
<link rel="stylesheet" th:href="#{/main.css}" />
Although, the css appear to show in the resources in console, the css file remains blank. Below are my files and code.
File Structure:
Template:
body {
background-color: #cccccc;
font-family: arial,helvetica,sans-serif;
}
.bookHeadline {
font-size: 12pt;
font-weight: bold;
}
.bookDescription {
font-size: 10pt;
}
label {
font-weight: bold;
}
<html xmlns:th="http://www.springframework.org/schema/data/jaxb">
<head>
<title>Reading List</title>
<link rel="stylesheet" th:href="#{/main.css}" />
</head>
<body>
<h2>Your Reading List</h2>
<div th:unless="${#lists.isEmpty(books)}">
<dl th:each="book : ${books}">
<dt class="bookHeadline">
<span th:text="${book.title}">Title</span> by
<span th:text="${book.author}">Author</span>
(ISBN: <span th:text="${book.isbn}">ISBN</span>)
</dt>
<dd class="bookDescription">
<span th:if="${book.description}"
th:text="${book.description}">Description</span>
<span th:if="${book.description eq null}">
No description available</span>
</dd>
</dl>
</div>
<div th:if="${#lists.isEmpty(books)}">
<p>You have no books in your book list</p>
</div>
<hr/>
<h3>Add a book</h3>
<form method="POST">
<label for="title">Title:</label>
<input type="text" name="title" size="50"></input><br/>
<label for="author">Author:</label>
<input type="text" name="author" size="50"></input><br/>
<label for="isbn">ISBN:</label>
<input type="text" name="isbn" size="15"></input><br/>
<label for="description">Description:</label><br/>
<textarea name="description" cols="80" rows="5">
</textarea><br/>
<input type="submit"></input>
</form>
</body>
</html>
Controller:
package codenotes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;
#Controller
#RequestMapping("/")
public class BookController {
private BookRepository bookRepository;
#Autowired
public BookController(BookRepository bookRepository) {
this.bookRepository = bookRepository;
}
#RequestMapping(value = "/{reader}", method = RequestMethod.GET)
public String readerBooks(
#PathVariable("reader") String reader,
Model model) {
List<Book> readingList =
bookRepository.findByReader(reader);
if (readingList != null) {
model.addAttribute("books", readingList);
}
return "readingList";
}
#RequestMapping(value = "/{reader}", method = RequestMethod.POST)
public String addToReadingList(
#PathVariable("reader") String reader, Book book) {
book.setReader(reader);
bookRepository.save(book);
return "redirect:/{reader}";
}
}
Repository:
package codenotes;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, Long> {
List<Book> findByReader(String reader);
}
I believe you should read this, how to serve static content:
http://docs.spring.io/spring-boot/docs/1.4.2.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content
To sum it up, your browser is caching your static resources, such as CSS files.
In order to break this behavior, try first clean your browser cache, in google chrome you go to settings then clear browsing data.
Secondly, add these lines to your application.properties file in order to bust the cache:
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
or add this instead:
spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/**
spring.resources.chain.strategy.fixed.version=v12
Please make the following changes
1. Move main.css into /static/css folder
2. Change
Let me know if does not work.
If you are using Spring Auth and you're not logged in, you'll also have to make sure that the user has access to see the styling.
In the WebSecurityConfig you just have to add "*/.css" to your list of allowed routes.
#Override
protected void configure(final HttpSecurity http) throws Exception {
...
.authorizeRequests()
//allow requests to all urls that match the pattern
.antMatchers("/", "/signup", "/login", "/*.css", "/*.jpg").permitAll()
//anything else you must be logged in
...
}

Dropdown menu in spring

Ive checked many similar questions but none of them has a working solution in my case.
I'm trying to make a dropdown selection for my user registration form using spring form:select tag. In my bean, country is set as ManyToOne so I pass a map for selecting the value.
Im bouncing between: Neither BindingResult nor plain target object for bean name 'register' available as request attribute. And: commandName not found blabla...
Help me understand what is going on and how to fix it.
It migth be interesting to know that I'm mounting my views through a MergedOutputModel (uses two redirects to mount the view), hence the Session variables.
Code below(simplified to where the problem is appearing).
Controller class:
#Transactional
#Controller
public class RegisterController {
#Autowired
public CountryDao cDao;
#RequestMapping("register")
public String register(Model model, #ModelAttribute("user") User user, BindingResult result, HttpSession session) {
session.setAttribute("user", user);
session.setAttribute("countryList", cDao.getCountryMap());
return "login/registerForm";
}}
View:
<body>
<h1>
<spring:message code="register.message" />
</h1>
[...]
<form:form action="addUser" commandName="register" method="post">
[...]
<spring:message code="register.country" />
<form:select path="country" items="${countryList}" />
[...]
<input type="submit" value="<spring:message code='register.submit'/>" />
</form:form>
</body>
This may get you closer to what you need. Your flow could be slightly different, so you can adjust the page names as needed.
#Controller
#SessionAttributes("countryList") //add whatever session attributes as needed
public class RegisterController {
#RequestMapping("/registerForm", method = RequestMethod.GET)
public String registerGet(Model model) {
model.addAttribute("user", myUserService.createUser());
model.addAttribute("countryList", countryDao.getCountryMap());
return "login/registerForm";
}
#RequestMapping("/registerVerify", method = RequestMethod.POST)
public String registerPost(#ModelAttribute("user") User user,
Errors result) {
if (result.hasErrors()) {
FormValidationLogger.log(log, result);
return "login/registerForm";
}
//persist, send emails, or do whatever
return "registerVerify"; //or whatever page
}
#Autowired
private CountryDao countryDao; //put these at the bottom so we don't have to scroll as much to get to the meat of the code
}
I don't readily see the need for #Transactional in the code you posted. I would expect that in your service or DAO layer.
<body>
<h1>
<spring:message code="register.message" />
</h1>
[...]
<form:form modelAttribute="user" action="/registerVerify" method="post">
[...]
<spring:message code="register.country" />
<form:select path="country" items="${countryList}" />
[...]
<input type="submit" value="<spring:message code='register.submit'/>" />
</form:form>
</body>
This assumes that country is a property of user. You also may want to change the method name to something like getCountries() instead of getCountryMap().

Including css and javascript files in spring 4 project

I'm making a web app using Spring 4, the Spring security module and tomcat 8. I'm trying to include some css files and js files in a .jsp file, but it's not working. When I check in the sources tag in Chrome the content of the css seems to be a log in form. I suspect that it may have something to do with spring security.
My css file is included like this in the .jsp
<link href="<c:url value='resources/css/materialize.min.css' />" rel="stylesheet"
type="text/css"></link>
This is the WebConfig file
#Configuration
#ComponentScan(basePackages = "mypackage")
#EnableWebMvc
#EnableTransactionManagement
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Autowired
#Bean
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory){
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
This is the SecurityConfig file
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/js/**", "/resources/css/**", "/resources/img/**", "/resources/font/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/signin")
.failureUrl("/signin?param.error=bad_credentials")
.and().logout().logoutUrl("/signout")
.and().authorizeRequests()
.antMatchers("/favicon.ico", "/resources/css/**", "/resources/font/**",
"/resources/js/**", "/auth/**", "/signin/**", "/signup/**", "/disconnect/facebook").permitAll()
.antMatchers("/**").authenticated()
.and()
.rememberMe().
and().csrf();
}
}
According to other answers here in stackoverflow it should work with the code that I have but the css only returns this:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:social="http://spring.io/springsocial"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="content" >
<form id="signin" action="signup" method="post">
<input type="hidden" name="" value=""/>
<div class="formInfo">
</div>
<fieldset>
<label for="login">Email</label>
<input id="login" name="email" type="text" size="25"></input>
<label for="Nombre">Email</label>
<input id="nombre" name="nombre" type="text" size="25"></input>
<label for="password">Password</label>
<input id="password" name="contrasena" type="password" size="25"></input>
</fieldset>
<button type="submit">Sign In</button>
<p>Or you can signin with a new account.</p>
</form>
</div>
All my css and js files are inside WebContent/resources
I solved the problem, apparently there was an ambiguous routing in one of my controllers, so when I tried to access a url that started with "/resources" it routed it to the controller, and thus returned a .jsp instead of the css/js/image. My original controller binded the url in the #Controller, and left the #RequestMapping without indicating the route.
#Controller("/signup")
public class SignUpController {
#RequestMapping(method=RequestMethod.GET)
public String signUpForm(){
...
}
#RequestMapping(method=RequestMethod.POST)
public String crearUsuario(HttpServletRequest request){
...
}
So I changed the #Controller annotation, and put the url in each #RequestMapping like this:
#Controller
public class SignUpController {
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signUpForm(){}
#RequestMapping(value="/signup",method=RequestMethod.POST)
public String crearUsuario(HttpServletRequest request){}
}

Categories