Spring MVC serve static file when submit a form - spring

I'm running through weird behavior in Spring MVC. I try to make custom login page with spring security.
Here is my simple login page with a link to a style sheet login.jsp:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<link href="/resources/css/style.css" rel="stylesheet"/>
</head>
<body>
<h1>Login Form</h1>
<form:form action="/authuser" method="post">
<c:if test="${param.logout != null}">
<i>You have been logout!</i>
</c:if>
<c:if test="${param.error != null}">
<i>Invalid username or password!</i>
</c:if>
<p>
User name: <input type="text" name="username"/>
</p>
<p>
Password: <input type="password" name="password"/>
</p>
<input type="submit" value="Login"/>
</form:form>
</body>
</html>
when I fill out the form and hit submit it redirect me to http://localhost:8080/resources/css/test.css and serves me with stylesheet file!
when I remove the stylesheet link, it works fine and redirects me to the home page.

Related

Attribute modelAttribute invalid for tag form according to TLD

I am trying to create a form:form but every time I have the model Attributr tag I get the following error!
There was an unexpected error (type=Internal Server Error, status=500).
/WEB-INF/views/start.jsp (line: 17, column: 0) Attribute modelAttribute invalid for tag form according to TLD
Here is my JSP code
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Official Sars-CoV3 Test Report</title>
</head>
<body>
<form:form action="addResults" modelAttribute="results">
<label for="tTN">TTN: </label><br>
<input type="text" id="tTN" name="tTN"><br>
<label for="fullname">Full Name:</label><br>
<input type="text" id="fullname" name="fullname">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email">
<label for="age">Age:</label><br>
<input type="text" id="age" name="age">
<label for="gender">Please select Gender:</label>
<input type="submit" value="submit">
</form:form >
Admin Login
</body>
</html>

How to get e.g. registration.jsp view appear correctly in browser?

I am following this tutorial for a login and registration functionality in a Spring Boot web application: https://hellokoding.com/registration-and-login-example-with-spring-security-spring-boot-spring-data-jpa-hsql-jsp/
I can't get the views to display properly - instead of e.g. the registration.jsp view page, I see the following string on screen, which is returned by my GET registration controller method: https://ibb.co/XXXtdSZ
I am new to Java, Spring Boot and even newer to JSP.
I am using IntelliJ Community Edition 2017.3.5 and I had a notification that .jsp files are not supported. Following this, https://stackoverflow.com/a/36572413/11451547, I went to Settings - File Types - HTML under Recognized File Types, and I added a new registered pattern, .*jsp, overriding the already existing registered pattern for JSP Files (syntax Highlighting Only). The message that .jsp was not supported disappeared but I still don't see the view pages properly.
In my registration.jsp I see a lot of 'namespace e.g.'form' is not bound' notifications. In my login.jsp, which has the same display issue (on screen I see the string 'login' instead of the login view), I have one notification - 'Namespace 'c' is not bound'.
Could you help with some ideas on how to display the views correctly?
Thank you!
This is the respective part of my controller (maybe I am wrong in adding #ModelAttribute to GET registration twice, this is part of the amendments I did to the tutorial code but e.g. my GET login controller method is the same as in the tutorial):
#GetMapping("/registration")
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
#PostMapping("/registration")
public String registration(#ModelAttribute("userForm") User userForm, #ModelAttribute("roleId") Long roleId, BindingResult bindingResult) { //diff w tutorial
userValidator.validate(userForm, bindingResult);
// userValidator.validate(roleId, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.saveUser(userForm, roleId);
securityService.autoLogin(userForm.getUserName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#GetMapping("/login")
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and/or password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#GetMapping({"/", "/welcome"})
public String welcome(Model model) {
return "welcome";
}
My registration.jsp:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Create an account</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form:form method="POST" modelAttribute="userForm" modelAttribute="roleId" class="form-signin">
<h2 class="form-signin-heading">Create Your Account</h2>
<spring:bind path="userName">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="userName" class="form-control" placeholder="Enter your username"
autofocus="true"></form:input>
<form:errors path="userName"></form:errors>
</div>
</spring:bind>
<spring:bind path="password">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="password" path="password" class="form-control" placeholder="Enter your password"></form:input>
<form:errors path="password"></form:errors>
</div>
</spring:bind>
<spring:bind path="passwordConfirm">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="password" path="passwordConfirm" class="form-control"
placeholder="Confirm your password"></form:input>
<form:errors path="passwordConfirm"></form:errors>
</div>
</spring:bind>
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</form:form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
My login.jsp:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log in with your account details</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form method="POST" action="${contextPath}/login" class="form-signin">
<h2 class="form-heading">Log In</h2>
<div class="form-group ${error != null ? 'has-error' : ''}">
<span>${message}</span>
<input name="userName" type="text" class="form-control" placeholder="Enter your username"
autofocus="true"/>
<input name="password" type="password" class="form-control" placeholder="Enter your password"/>
<span>${error}</span>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
<h4 class="text-center">Create an Account</h4>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
My welcome.jsp:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<c:if test="${pageContext.request.userPrincipal.name != null}">
<form id="logoutForm" method="POST" action="${contextPath}/logout">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<h2>Welcome ${pageContext.request.userPrincipal.name} | <a onclick="document.forms['logoutForm'].submit()">Logout</a></h2>
</c:if>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
The respective part of my application.yml file:
spring:
main:
banner-mode: 'off'
datasource:
url: jdbc:mysql://localhost:3306/inspire_me_db?useSSL=false
username: springuser
password: ThePassword
jpa:
hibernate:
ddl-auto: update
flyway:
baselineOnMigrate: true
mvc:
view:
prefix: /
suffix: .jsp
messages:
basename: validation
The respective part of my pom.xml:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
My package structure:
https://ibb.co/Qr2dmNr
Can you try registering your jsp view resolver as follows :
#Configuration
#EnableWebMvc
#ComponentScan
public class MvcConfiguration implements WebMvcConfigurer
{
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}
Or you can also specify jsp as the view resolver in Spring-boot by providing the following in application.properties or yml :
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
Verify that the prefix provided points to the correct directory in which the jsp files reside.Usually the jsp files are put under src/main/WEB_INF/view .
Also since you are using spring-boot , if you don't have the appropriate dependencies to compile the jsp add the following to the pom :
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

Using Spring Security, how to stay on the login page after a successful login?

Using Spring Security, how can I stay on the login page after a successful login?
This part of my Spring config file:
<http auto-config="true" use-expressions="true">
<form-login authentication-failure-url="/index.jsp?failed=true" default-target-url="/index.jsp" />
<logout logout-success-url="/index.jsp" />
</http>
And I have a jsp fragment file /WEB-INF/jsp/subhead.jspf:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<c:url var="postLoginUrl" value="j_spring_security_check" />
<c:url var="logoutUrl" value="j_spring_security_logout"/>
<c:if test="${param.failed == true}">Login Failed...</c:if>
<security:authorize access="isAnonymous()">
<form action="${postLoginUrl}" method="post">
Username: <input type="text" name="j_username"/>
Password: <input type="password" name="j_password" />
<input type="submit" value="Log in"/>
</form>
</security:authorize>
<security:authorize access="isAuthenticated()">
Hi, <security:authentication property="principal.username"/> Log out
</security:authorize>
I have a page say test.jsp:
<html>
<body>
<%# include file="/WEB-INF/jsp/subhead.jspf" %>
</body>
</html>
How can I make
login success
login failed
logout
all redirect back to the login page (test.jsp)?
For now, they will all redirect to /index.jsp.

"HTTP Status 405 - Request method 'POST' not supported" on form submit

Trying to do a very simple form in Spring/Hibernate. It should be adding an entry to the database. This is based off an example which worked for me, so it's weird that I would be getting this error. But it is what it is.
Here's the page with the form:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head><title>Add Owned Game</title></head>
<body>
<h1>Add Owned Game</h1>
<br />
<br />
<c:url var="saveGameeUrl" value="/games/save.html" />
<form:form modelAttribute="game" method="POST" action="${saveGameUrl}">
<form:label path="title">Game Title:</form:label>
<form:input path="title" />
<br />
<input type="submit" value="Add Game" />
</form:form>
</body>
</html>
And here's the relevant controller method:
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView saveGame(#ModelAttribute("game") Game game,
BindingResult result) {
gameService.addOwnedGame(game);
return new ModelAndView("redirect:/games/owned.html");
}
If you need to see anything else, let me know.
It looks like your are posting to the HTML page (which should be static) instead of the /save page which would route to a controller. Also, is it a typo? The c:url is named saveGameeUrl with two Es whereas the action only has one e on Game.
<c:url var="saveGameeUrl" value="/games/save.html" />
<form:form modelAttribute="game" method="POST" action="${saveGameUrl}">

Struts2 ajax theme problem in IE9

We have an running application that is developed in struts-2.0.14. In this we used Ajax theme for displaying contents.
This ajax theme is running properly in all browsers except IE9 browsers, In IE9 this ajax theme making problem . The result is showing in new tab instead of showing in target element(div) specified by targets property.
Parent Page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<s:head theme="ajax" debug="false" />
</head>
<body>
<s:url id="changePwd" action="changePassword" />
<s:div theme="ajax" id="pwdDiv" executeScripts="true" href="%{changePwd}" loadingText="Loading..."/>
</body>
</html>
Inner page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<s:form action="changePassword" id="resetPassword" name="resetPassword">
<s:textfield name="username" id="username" />
<s:password showPassword="true" name="newpassword" id="newpassword" value="%{newpassword}"/>
<s:password showPassword="true" name="confirmpassword" id="confirmpassword" value="%{confirmpassword}"/>
<s:submit value="Confirm" showLoadingText="false" onclick="clearMsg();" theme="ajax" targets="pwdDiv" executeScripts="true" cssClass="userbutton" />
</s:form>
When Submitting the form in Inner Page the resulting page is popup into new tab. actually it should replace the content of pwdDiv.
Note: the same working properly in other browsers including (IE7,8)
Update:
making showLoadingText as true making the request as Ajax but the values are passed as null (password,confirm password ect,. -all fields)
Adding type="button" in s:submit button solve the problem. Don't know what is behind this !
<s:submit **type="button"** value="Confirm" showLoadingText="false" onclick="clearMsg();" theme="ajax" targets="pwdDiv" executeScripts="true" cssClass="userbutton" />

Resources