Logging page with jsp for spring - java

I got this jsp for logging page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.error {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.msg {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
#login-box {
width: 300px;
padding: 20px;
margin: 100px auto;
background: #fff;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border: 1px solid #000;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>
<h1>Spring Security Custom Login Form (Annotation)</h1>
<div id="login-box">
<h2>Login with Username and Password</h2>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='user' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'>
<input name="submit" type="submit" value="submit" />
</td>
</tr>
</table>
<input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</div>
</body>
</html>
and in the controller:
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
and security config:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}123456").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").access("hasRole('ROLE_USER')").and().formLogin()
.loginPage("/login").permitAll().failureUrl("/login?error").usernameParameter("username")
.passwordParameter("password").and().logout().logoutSuccessUrl("/login?logout").and().csrf();
}
}
After loggin I don't get valid url like: localhost/com.myproject.spring/login?error
or localhost/com.myproject.spring/admin
but I get always:
localhost/com.myproject.spring/j_spring_security_check and error message: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
What is wrong? I've just copied everything from this tutorial: https://www.mkyong.com/spring-security/spring-security-custom-login-form-annotation-example/

Related

Spring Adding Cookies

I am trying to create a shopping cart using cookies in spring boot but the cookie is not being added/displayed. Below are the controller mappings and page htmls, can you let me know what I'm doing wrong?
Screenshots of pages :
Controller Mappings:
#GetMapping("/products/addToCart/{id}")
private String addToCart(#PathVariable("id") long productId, HttpServletResponse response) {
try {
Cookie browserSessionCookie = new Cookie(Long.toString(productId), Long.toString(1L));
response.addCookie(browserSessionCookie);
return "redirect:/products/cart";
} catch (Exception e) {
logger.error(e.getMessage());
return "fail";
}
}
#GetMapping("/products/cart")
public String showCookies(HttpServletRequest request, Model model) {
Cookie[] cookies = request.getCookies();
model.addAttribute("cookies",cookies);
return "/cart";
}
Thymeleaf Page For Products List:
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>All Products</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
table, th, td {
border: 1px solid black;
}
td {
padding: 20px;
}
.topnav {
background-color: #A32638;
overflow: hidden;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #FCB514;
color: white;
}
</style>
</head>
<body>
<div class="topnav">
<a th:href="#{/}">Home</a>
<a class="active" th:href="#{/productsList}">Products</a>
<a th:href="#{/products/cart}">Cart</a>
</div>
<br>
Products
<br>
<br>
<div th:if="${ not#lists.isEmpty(products)}">
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Action</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.name}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.category.name}"></td>
<td>
<a th:href="#{/products/details/{id}(id=${product.id})}">Details</a>
<a th:href="#{/products/addToCart/{id}(id=${product.id})}">Add To Cart</a>
</td>
</tr>
</table>
<br>
</div>
</body>
</html>
Thmeleaf Page For Showing Cookies :
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<br>
<h1>Show cookies</h1>
<dl th:each="cookie : ${cookies}">
<dt th:text="${cookie.getName()}"></dt>
<dd th:text="${cookie.getValue()}"></dd>
</dl>
<h1>Session Data</h1>
<dl th:each="elem : ${sessionElems}">
<dt th:text="${elem.getName()}"></dt>
<dd th:text="${elem.getValue()}"></dd>
</dl>
</body>
</html>
Thank you.
The solution was to set the path of the created cookie to the path of the cart page as below :
browserSessionCookie.setPath("/products/cart");
Thanks for the responses!

Trouble authenticating with Java through HTMLUnit. Debugging issues

I am having trouble authenticating with HTMLUnit on a webpage. I enter a username and password, and then click sign in, then check the title of the page, and it is still the sign in page. SO I am not signed in properly.
What is going wrong here? I'm trying to use Fiddler and Charles for debugging but I don't see my requests show up there. Does this Java code make sense for authentication with the given website? Any debugging tips?
Please help me! Thank you.
My code:
package com.company;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.*;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.CookieManager;
public class Main {
static WebClient webClient;
static CookieManager cookieManager;
static String username = "MyUsername";
static String password = "MyPassword";
#Before
public static void init() throws Exception {
webClient = new WebClient();
cookieManager = new CookieManager();
cookieManager = webClient.getCookieManager();
cookieManager.setCookiesEnabled(true);
webClient.getOptions().setTimeout(90000);
webClient.setJavaScriptTimeout(90000);
}
#After
public static void close() throws Exception {
webClient.close();
cookieManager.clearCookies();
}
public static void signIn() throws Exception {
//Acquire location for URI, password, username, submitbutton
HtmlPage page1 = webClient.getPage("https://h3c.mlspin.com/signin.asp#ath");
HtmlForm form = page1.getFormByName("loginform");
HtmlTextInput uName = form.getInputByName("user_name");
HtmlPasswordInput passWord = form.getInputByName("pass");
HtmlButton button = form.getFirstByXPath("//*[#id=\"loginForm\"]/table/tbody/tr[7]/td/button");
uName.setValueAttribute(username);
passWord.setValueAttribute(password);
HtmlPage page2 = button.click();
System.out.println("HTMLUNIT UserText : \n" + uName.getText());
System.out.println("HTMLUNIT PassText : \n" + passWord.getText());
System.out.println("Results p2 " + page2.getTitleText());
System.out.println("Results p2 " + page2.getPage());
}
#Test
public static void givenAClient_gatherInfo() throws Exception {
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setRedirectEnabled(true);
webClient.getCache().setMaxSize(0);
}
public static void main(String[] args) throws Exception {
init();
givenAClient_gatherInfo();
signIn();
close();
}
}
<!-- Latest compiled and minified CSS -->
<LINK href="/css/Signin.css" type=text/css rel=stylesheet>
<script language='javascript'>
window.sessionStorage.clear();
</script>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,
shrink-to-fit=no">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<meta http-equiv="expires" content="0">
<title>pinergy - Sign In</title>
<link href="/style.asp" type="text/css" rel="stylesheet">
<script type="text/javascript" src="/shared/scripts/3rdParty/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="/shared/scripts/3rdParty/bootstrap-4.1.1/bootstrap.min.js"></script>
<script type="text/javascript" src="/shared/scripts/cookieConsent.js?v=2"></script>
<script language="JavaScript">
var ath;
ath = {}
;
var isMobile = function() {
return /(iphone|ipod|(android.*mobile)|blackberry|windows ce|palm|symbian|nexus 7|xoom|windows phone)/i.test(navigator.userAgent);
}
;
var isIPad = function() {
return /(ipad)/i.test(navigator.userAgent);
}
function CheckSavePassword() {
if (document.loginform.SavePassword.checked) {
document.loginform.SavePassword.checked = false;
} else {
document.loginform.SavePassword.checked = true;
}
}
function parseQueryString(queryString) {
var QueryString = {};
queryString = queryString.slice(queryString.indexOf("?") + 1);
var qsArray = queryString.split("&");
for (var i = 0; i < qsArray.length; i++) {
var arr = qsArray[i].split("=");
QueryString[arr[0]] = arr[1];
}
return QueryString;
}
if (window != top) {
top.location.href = location.href;
}
</script>
<style>
body {
padding: 0;
}
INPUT.login {
height: 22px;
border: 1px solid #808080;
padding: 2px 4px;
background-image: url('images/bg_input.gif');
}
.mobile {
padding: 6px;
align-content: center;
align-self: center;
width: 90%;
height: auto;
display: none;
text-align: center;
border: 4px solid #E7E7E7;
border-radius: 15px;
color: #444;
margin: auto;
background: -moz-linear-gradient(top, #FFFFFF, #E7E7E7);
background: -ms-linear-gradient(#FFFFFF, #E7E7E7);
background: -webkit-gradient(linear, left top, left bottom, from(#FFFFFF), to(#E7E7E7));
max-width: 25rem;
}
.mobileButton {
font-weight: bold;
border-top: 1px outset grey;
border-left: 1px outset grey;
-moz-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
border-radius: 10px 10px 10px 10px;
-webkit-appearance: none;
-moz-appearance: none;
min-height: 2rem;
/*width:90px;
height:54px;
font-family:Arial;
font-size:x-large;*/
}
.yes {
background-color: #FBAF41;
}
.no {
background-color: #BEBEBE;
}
.mobileCheckTable {
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif !important;
}
.mobileCheckTable td {
vertical-align: top;
}
.textContent {
font-size: .9rem;
text-align: center;
font-weight: 500;
}
.textContent1Child {
white-space: nowrap;
padding-left: .5rem;
}
.mobilecheck {
height: 1.2rem;
width: 1.2rem;
vertical-align: top;
padding: 0;
border: 1px solid rgba(0, 0, 0, 0.3);
}
.mobilequest {
margin: 0 auto;
max-width: 20rem;
box-sizing: border-box;
float: left;
padding-left: .5rem;
padding-bottom: .5rem;
}
div#remember {
font-size: 0.88rem;
}
.mls-bootstrap-font {
font-size: 1rem;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif;
}
.sm-remember {
display: none;
}
#media only screen and (min-width: 476px) {
.mobile {
padding: 15px;
}
.sm-remember {
display: initial;
}
.mobilequest {
padding-bottom: 1rem;
}
.mobilequest,
.textContent1Child {
padding-left: 1rem;
}
}
#media only screen and (min-width: 768px) {
.mobilequest.textContent {
font-size: 1.5rem !important;
}
.textContent1Child {
font-size: 1.2rem !important;
}
}
#media only screen and (min-width: 1024px) {
.mobilequest.textContent {
font-size: 1.6rem !important;
}
.textContent1Child {
font-size: 1.2rem !important;
}
}
</style>
<link rel="icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
<link rel="shortcut icon" href="images/apple-touch-icon-120x120.png" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="css/addtohomescreen.css">
<script src="Scripts/addtohomescreen.js"></script>
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-120x120.png" type="image/x-
icon" sizes="120x120" />
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-152x152.png" type="image/x-
icon" sizes="152x152" />
<link rel="shortcut icon" href="images/apple-touch-icon-152x152.png" type="image/x-icon" sizes="152x152" />
<link rel="apple-touch-icon-precomposed" href="images/apple-touch-icon-57x57.png" type="image/x-
icon" sizes="57x57" />
</head>
<body marginheight="0" marginwidth="0" topmargin="0" leftmargin="0">
<table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="100%" height="100%">
<form name="loginform" id="loginForm" method="POST" action="signin.asp" style="margin:
0px" onsubmit="return signInFn.loginFormOnSubmit();
">
<input name="cxzvvfbvvalideguaueff" value="DT: 8/16/2020 8:18:40 PM" type="hidden"><input name="Page_Loaded" value="DT: 8/16/2020 9:25:16 PM" type="hidden">
<table border="0" cellspacing="0" cellpadding="0" class="mls-login">
<tr>
<td><img src="images/MLSPIN_Logo.jpg" width="240" height="60" /></td>
</tr>
<tr>
<td class="text-left pl-4"><span class="h4">Sign In to</span><img src="images/pinergy-logo.jpg" width="90" height="30" /></td>
</tr>
<tr>
<td class="pl-2"><input class="form-control" type="text" style="width: 220px;" name="user_name" maxlength="8" value="MyUsername" placeholder="Enter Your Agent ID"></td>
</tr>
<tr>
<td class="pl-2"><input class="form-control" type="password" style="width: 220px" name="pass" maxlength="20" placeholder="Password"></td>
</tr>
<tr>
<td class="text-left pl-2">Forgot your password?</td>
</tr>
<tr>
<td class="text-left pl-2 mls-login-rem-me"><input type="checkbox" name="SavePassword" value="Y"><span onclick="CheckSavePassword();">Remember My Password</span></td>
</tr>
<tr>
<td><button class="btn btn-sm btn-primary" type="submit">Sign In</button>
<!--<input class="btn btn-sm btn-primary" type="submit" value="Sign In" name="signin"></td>--></tr>
</table>
</form>
</td>
</tr>
<tr>
<td>
<footer class="mls-site-footer">
<div class="footer-content">
<div class="footer-icon MLSPINlogo mr-1"></div>
<div class="mb-1">©
<span>MLS Property Information Network,
Inc.</span></div>
<div class="vert-bar">|</div>
<div>900 Hartford Turnpike, fakeville, TN 01245 </div>
<div class="vert-bar">|</div>
<div>800-700-3189 </div>
<div class="vert-bar">|</div>
<div class="footer-content-group">
<div class="d-inline">Access Notice</div>
<div class="vert-bar d-inline">|</div>
<div class="d-inline">Privacy Policy</div>
<div class="vert-bar d-inline">|</div>
<div class="d-inline">Copyright Policy</div>
</div>
<div class="vert-bar">|</div>
<div class="footer-user-count">2190 users online right now!</div>
</div>
</footer>
</td>
</tr>
</table>
<div id="cookieConsentBootstrapModal" class="modal mls-bootstrap-font" role="dialog" aria-labelledby="cookieConsentTitle" aria-describedby="cookieConsentDesc" aria-hidden="true" data-backdrop="static" tabindex="-1">
<div class="modal-dialog" role="document">
<!-- Modal content-->
<div class="modal-content mls-modal-bgcolor">
<div class="modal-header">
<h1 class="modal-title h5" id="cookieConsentTitle">This website uses cookies</h1>
</div>
<div class="modal-body" id="cookieConsentDesc">This website uses cookies for a number of purposes, including to enhance your browsing experience. Learn more about our use of cookies in our Privacy Policy. </div>
<div class="modal-footer"><button type="button" class="btn btn-sm btn-primary mls-js-cookie-consent-action" data-dismiss="modal">OK</button></div>
</div>
</div>
</div>
<script language="JavaScript">
document.loginform.user_name.focus();
alert("Incorrect password!\nPlease try again.");
</script>
<script>
if (!window.location.hash.match('ath')) {
addToHome = addToHomescreen({
detectHomescreen: true,
autostart: false,
icon: true,
lifespan: 15,
maxDisplayCount: 1,
appID: 'com.mlspin.MobileWeb'
});
addToHome.show();
window.location.hash = '#ath';
}
</script>
<script type="text/javascript">
var signInFn = (function() {
var _suppressCookieConsent = false;
function _loginFormOnSubmit() {
var isValid = true;
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
isValid = false;
cookieConsentUtil.showCookieBanner();
}
_enableDisableLoginForm();
return isValid;
}
function _enableDisableLoginForm() {
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
document.getElementById("loginForm").action = "signin.asp";
} else {
document.getElementById("loginForm").action = "validate_new.asp";
}
}
function _focusOnFirstElement() {
try {
var focusable = $('button:visible, a[href]:visible, input:visible, select:visible, textarea:visible, [tabindex]:visible:not([tabindex="-1"])');
if (focusable.length > 0) {
var firstFocusable = focusable[0];
firstFocusable.focus();
}
} catch (ex) {}
}
function _docOnReady() {
//_focusOnFirstElement();
cookieConsentUtil.init({
onStoreCookieConsent: function() {
_enableDisableLoginForm();
setTimeout(_focusOnFirstElement, 0);
}
});
cookieConsentUtil.docOnReady();
_enableDisableLoginForm();
}
return {
loginFormOnSubmit: _loginFormOnSubmit,
docOnReady: _docOnReady
};
}
());
$(document).ready(function() {
signInFn.docOnReady();
}
);
</script>
</body>
</html>
Looking in the javascripts there's this section:
if (!_suppressCookieConsent && !cookieConsentUtil.cookieConsentExists()) {
document.getElementById("loginForm").action="signin.asp";
}
else{
document.getElementById("loginForm").action="validate_new.asp";
}
Seems from looking at the http requests validate_new.asp is returning a 302 (redirect) to signin.asp. This might help locate the relevant requests.
I tried looking a bit deeper but I'd need to try running your code which I've not got time to do right now. If I find time I'll come back to this as it should be possible.

Spring MVC -- Handle multiple forms in a single jsp

I have been searching around for reason why I have error Neither BindingResult nor plain target object for bean name 'addItemForm' available as request attribute but can't understand.
The page is loading fine but if I click on Add new item button, a lightbox containing a form appears, I click on Add item and I got same error as above but bean name is searchForm.
The controller looks fine, I think there is a binding problem between the view and the form. Can someone explain please?
Also, it is able to add new items to database, so the POST method is working, but the view returns errors ..
JSP:
<%# 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 prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Admin View</title>
<style type="text/css">
body{margin:0, padding:0}
#body{
text-align: center;
top: 3%;
}
.table2{
border-spacing: 5%;
}
.table1 {
border-collapse: collapse;
width: 80%;
}
.table1 tr:nth-child(odd) td{
background-color: #ffffff;
}
.table1 tr:nth-child(even) td{
background-color: #4da6ff;
}
.table1 td, th {
text-align: left;
border: 1px solid green;
}
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="body">
<h3>This is the Administrator View</h3>
<p>From here, you can search for items in the database, view, add new items and delete items from database</p>
<table align="center">
<tr>
<td>
<form:form action="AdminView" method="POST" commandName="searchForm">
<form:input path="KeyWordSearch" size="40"/>
<input type="submit" name="search" value="Search Store"/>
</form:form>
</td>
<td><button onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Add new item</button></td>
</tr>
</table>
<br>
<c:if test="${not empty itemList}">
<table class="table1" align="center">
<tr>
<th>Item Name</th>
<th>Date added</th>
<th>Item Description</th>
<th>View Details</th>
</tr>
<c:forEach var="item" items="${itemList}">
<tr>
<td>${item.itemName}</td>
<td>${item.itemAdded}</td>
<td>${item.itemDescription}</td>
<td>View</td>
</tr>
</c:forEach>
</table>
</c:if>
</div>
<div id="light" class="white_content">
<h2 align="center">Add new item to Store</h2>
<form:form action="AdminView" method="POST" commandName="addItemForm">
<table align="left">
<tr>
<th style="border:0">Item name</th>
<td><form:input path="ItemName"/></td>
</tr>
<tr>
<th style="border:0">Item location</th>
<td><form:input path="ItemLocation"/></td>
</tr>
<tr>
<th style="border:0">Item Description</th>
<td><form:textarea path="ItemDescription"/></td>
</tr>
<tr>
<td><input type="submit" name="add" value="Add Item"/></td>
</tr>
</table>
</form:form>
Close
</div>
<div id="fade" class="black_overlay"></div>
</body>
</html
This is the Controller:
package com.test.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.test.forms.AddNewItemForm;
import com.test.forms.SearchForm;
import com.test.models.items.ItemIF;
import com.test.transaction.TransactionFactory;
/**
* Handles requests for Admin View page
* #author Trung
*
*/
#Controller
#RequestMapping (value = "/AdminView")
public class AdminViewController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView adminForm(Model model){
SearchForm searchForm = new SearchForm();
model.addAttribute("searchForm", searchForm);
AddNewItemForm addItemForm = new AddNewItemForm();
model.addAttribute("addItemForm", addItemForm);
return new ModelAndView("AdminView");
}
#RequestMapping (params = "search", method = RequestMethod.POST)
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, Model model){
List<ItemIF> relatedItems = null;
TransactionFactory transaction = new TransactionFactory();
relatedItems = transaction.retrieveItemByName(searchForm.getKeyWordSearch());
if (relatedItems.isEmpty()){
System.out.println("okay, there isn't any item that is matched your criteria");
} else {
model.addAttribute("itemList", relatedItems);
}
return "AdminView";
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView addNewItemForm(#ModelAttribute("addItemForm") AddNewItemForm addItemForm){
TransactionFactory transaction = new TransactionFactory();
String itemName = addItemForm.getItemName();
String itemLocation = addItemForm.getItemLocation();
String itemDescription = addItemForm.getItemDescription();
transaction.insertItem(itemName, itemLocation, itemDescription);
return new ModelAndView("AdminView");
}
}
You need a BindingResult as parameter in both post methods after the #ModelAttribute parameter, like this:
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, BindingResult result, Model model){

jsp:useBean duplicate id checking

In my jsp page i have following code snippet. This page is coming recursive way during my flow. I am getting a duplicate bean id error while execution of the jsp in the middle of the flow. Can you anyone help me how to check whether bean id already exist or not for the following code?
The full code has been given
code.jsp
<%# page language="java" %>
<%# page import="com.ubsw.risk.AUT_Authenticator.*" %>
<%
String path= System.getProperty("dev_property_path");
System.out.println("dev_property_path----->"+path);
%>
<jsp:useBean id="orbinfra" scope="session" class="com.ubsw.risk.Creation.web.OrbinfraBean" >
<jsp:setProperty name="orbinfra" property="propertiesFile" value="<%=path%>"/>
<%
System.out.println("B4 init of Orbinfra");
try {
orbinfra.init();
System.out.println("after init of Orbinfra");
} catch( Exception ex ) {
System.out.println("error in Orbinfra"+ex);
ex.printStackTrace();
%>
<html>
Caught exception while creating orbinfra <%= ex %>
</html>
<%
}
%>
</jsp:useBean>
<jsp:useBean id="security" scope="session" class="com.ubsw.risk.Creation.web.AuthenticatorBean" >
</jsp:useBean>
<%
boolean showLogin;
showLogin = true;
boolean additionalMessage = false;
String message = "Warning - Users login has expired";
boolean hasAdminRights = false;
// is there a command being sent
String checkcommand = request.getParameter("command");
// does user want to login
if( checkcommand != null ) {
if( checkcommand.equals("login") ) {
try {
String authenticatorModuleLookupValue= System.getProperty("authenticatorModuleLookupValue");
String cookieNamevalue= System.getProperty("cookieNamevalue");
System.out.println(request.getParameter("User_Name"));
System.out.println(request.getRemoteAddr());
System.out.println(request.getLocalAddr());
System.out.println("hello P");
//HttpSession session1 = request.getSession(true);
System.out.println(authenticatorModuleLookupValue+":"+cookieNamevalue);
security.setloginInfo(authenticatorModuleLookupValue,cookieNamevalue);
security.logon(request.getParameter("User_Name"), request.getParameter("Password"), request.getRemoteAddr(), response );
System.out.println("what happened?");System.out.println(security);
showLogin = false;
} catch( LogonFailure le ) {
additionalMessage = true;
message = "Logon failed : " + le.reason;
} catch( Exception ex ) {
additionalMessage = true;
message = "Failed, caught an exception : " + ex;
}
}
}
if( showLogin ) {
try {
showLogin = !security.hasPermission( request );
if( ! showLogin ) {
hasAdminRights = security.hasAdminPermission( request );
}
} catch( TicketIsExpired te ) {
additionalMessage = true;
message = "Warning - Users login has expired";
} catch( Exception ex ) {
additionalMessage = true;
message = "Exception - " + ex;
}
}
//System.out.println("showLogin"+showLogin);
// do we need to show login or not
if( showLogin ) {
%>
<html>
<body>
<FORM NAME="loginForm" ACTION="index.jsp" METHOD="post">
<center>
<%
if( additionalMessage ) {
%>
<b> <%= message %> </b><br>
<%
}
//System.out.println("showLogin"+showLogin);
%>
<br>
<br>
<center>
<table cellspacing="0" cellpadding="0" border="2" bordercolor="#60A0A0">
<INPUT TYPE='hidden' NAME='command' VALUE='login'>
<body>
<tr bgcolor="#60A0A0">
<td align="left" height="17"><font face="Verdana" color="white"><span
style="color: white; font-weight: bold; font-variant: normal; font-size: 10pt; text-align: left">
<center>
Creation Web Application
</center>
</span></font></td>
</tr>
<tr bgcolor="#60A0A0">
<td align="left" height="17"><font face="Verdana" color="white"><span
style="color: white; font-weight: bold; font-variant: normal; font-size: 10pt; text-align: left">Please
Login</span></font></td>
</tr>
<tr>
<td align="left" height="166">
<table border="0" height="116" width="460">
<tbody>
<tr>
<td height="16" width="70"></td>
<td height="16" width="87"></td>
<td height="16" width="164"></td>
<td height="16" width="136"></td>
</tr>
<tr>
<td height="25" width="70"></td>
<td height="25" width="87"><span
style="color: black; font-style: normal; font-family: Verdana; font-weight: bold; font-size: 10pt; text-align: center">Username:</span></td>
<td height="25" width="164"><input type="text"
name="User_Name" maxlength="20"
style="height: 25px; font-family: Verdana; width: 153px"></td>
</tr>
<tr>
<td height="1" width="70"></td>
<td height="1" width="87"></td>
<td height="1" width="164"></td>
<td height="1" width="136"></td>
</tr>
<tr>
<td height="25" width="70"></td>
<td height="25" width="87"><span
style="color: black; font-style: normal; font-family: Verdana; font-weight: bold; font-size: 10pt; text-align: center">Password:</span></td>
<td height="25" width="164"><input type="password"
name="Password"
style="height: 25px; font-family: Verdana; width: 153px"
maxlength="25"></td>
<td height="25" width="136"></td>
</tr>
<tr>
<td height="19" width="70"></td>
<td height="19" width="87"></td>
<td height="19" width="164"></td>
<td height="19" width="136"></td>
</tr>
<tr>
<td height="27" width="70"></td>
<td height="27" width="100"></td>
<td height="27" width="136">
<center><input type="submit" name="Login"
value="Login"
style="height: 25px; bottom: auto; right: auto; font-family: Verdana; background-color: #60A0A0; width: 62px; top: auto; left: auto"></center></td>
</tr>
<tr>
<td height="1" width="70"></td>
<td height="1" width="87"></td>
<td height="1" width="164"></td>
<td height="1" width="136"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</center>
</FORM>
</body>
</html>
<%
return;
}
%>
As you are saying This page is coming recursive way during my flow.
Try changing scope="page" to scope="request"
Or try renaming beanId to "orbinfra1"
<jsp:useBean id="orbinfra1" scope="session" class="com.ubsw.risk.Creation.web.OrbinfraBean" >
<jsp:setProperty name="orbinfra1" property="propertiesFile" value="<%=path%>"/>
</jsp:useBean>

how to access static resources on Spring Security application using annotations?

I'm trying to access static content on a login page jsp and I'm failing to do so.
The security config method I'm using is:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**","/images/**")
.access("hasRole('ADMIN')").and().formLogin()
.loginPage("/user/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/403");
}
The login page that fails to load images and static resources is:
<%#include file="../include/include.jsp"%>
<%#include file="../decorators/tbs_imports.jsp"%>
<html>
<head>
<title><s:message code="title"></s:message></title>
<style>
html,body {
background-color: #eee;
}
body {
padding-top: 5px;
}
.content {
width: 300px;
}
/* The white background content wrapper */
.container>.content {
background-color: rgba(113, 121, 225, .15);
padding: 15px;
margin: 0 -20px;
-webkit-border-radius: 10px 10px 10px 10px;
-moz-border-radius: 10px 10px 10px 10px;
border-radius: 10px 10px 10px 10px;
-webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
-moz-box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
}
.login-form {
margin-left: 70px;
}
</style>
<script type="text/javascript">
window.onload = function() {
document.login.j_username.focus();
}
function changeFlag() {
var lang = $("#langDrop option:selected").text();
if (lang == 'Portugues') {
$('#flag').attr('src', '../images/br.png');
}
if (lang == 'English') {
$('#flag').attr('src', '../images/en.png');
}
if (lang == 'Espanol') {
$('#flag').attr('src', '../images/es.png');
}
}
</script>
</head>
<body>
<div style="display: block; margin-left: auto; margin-right: auto"
class="container">
<div style="padding-bottom: 5px">
<img
style="padding-top: 10px; display: block; margin-left: auto; margin-right: auto"
src="${pageContext.request.contextPath}/images/logo_pims_scf_grande.png" />
</div>
<c:if test="${not empty duplicated_user}">
<div
style="display: block; margin-left: auto; margin-right: auto; text-align: center"
class="content alert alert-error">
<strong><s:message code="login-duplicate-user" /></strong>
</div>
</c:if>
<br /> <br />
<c:if test="${not empty session}">
<div
style="display: block; margin-left: auto; margin-right: auto; text-align: center"
class="content alert alert-error">
<strong><s:message code="session-maxLimitReached" /></strong>
</div>
</c:if>
<c:if test="${not empty corrupted}">
<div
style="display: block; margin-left: auto; margin-right: auto; text-align: center"
class="content alert alert-error">
<strong><s:message
code="session-value-corrupted-in-the-database" /></strong>
</div>
</c:if>
<c:if test="${empty session}">
<c:if test="${empty corrupted}">
<div style="display: block; margin-left: auto; margin-right: auto"
class="content">
<div class="row">
<div class="login-form">
<h4 style="padding-bottom: 10px">Login</h4>
<form id="j_acegi_security_check" onsubmit="return true;"
name="login"
action="${pageContext.request.contextPath}/j_acegi_security_check"
method="POST">
<fieldset>
<div class="clearfix">
<input style="height: 25px;" id="username" name="j_username"
type="text" placeholder="Username">
</div>
<div class="clearfix">
<input style="height: 25px;" name="j_password" id="password"
type="password" placeholder="Password">
</div>
<br>
<button class="btn btn-primary" type="submit">
<s:message code="join" />
</button>
</fieldset>
</form>
</div>
</div>
</div>
</c:if>
</c:if>
</div>
</body>
</html>
The WebContent folder structure is:
WebContent
- css
- images
- js
- META-INF
- WEB-INF
- classes
- jsp
- lib
- tags
- index.jsp
- web.xml
Since this application is annotations driven, the web.xml file is blank. And index.jsp redirects to /jsp/user/login.jsp.
Any ideas how to solve this issue?
Thanks in advance.

Categories