Why does my JSTL if-check doesn't work? - spring-mvc

I am trying to create simple application with log in function, using Spring Security. But i can't achieve desired result.
JSTL tag on my .jsp page doesn't pass test, while scriplet code does which i want to avoid in my application.
My JSP page.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Log in page</title>
</head>
<body>
<form action="<c:url value="/login"/>" method="POST">
<p>
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</p>
<p>
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</p>
<button type="submit" class="btn">Log in</button>
</form>
// This block of code is never executed
<c:if test="${error != null}">
Some test message
</c:if>
// While this one works fine
<%
if (request.getParameter("error") != null) {
out.write("error's value isn't null\n");
}
%>
</body>
</html>
WebSecurityConfigurerAdapter overriden configure method:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.antMatchers("/product")
.access("hasRole('ROLE_MANAGER')");
http.authorizeRequests().and().formLogin()
.loginPage("/login")
.defaultSuccessUrl("/admin")
.failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.and().logout().logoutSuccessUrl("/login?logout");
}
Spring MVC Controller's method for mapping "/login" request.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model,
#RequestParam(value = "error", required = false) String error {
if (error != null) {
model.addAttribute("error", "Username or password is incorrect.");
}
return "login";
}
And this is what I get requesting http://localhost/login?error :
Image

I have changed
<%# page contentType="text/html;charset=UTF-8" language="java"%>
to
<%# page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
As i understood, EL evaluation was deactivated, so i manually activated it.

Related

Set or get html tags value or innerhtml in razor view

how to set or get html elements inner text or html controls value in Razor syntax.
i know how we can do this in aspx file using Runat="server" attribute like this
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title><%Response.Write(Page.Title); %></title>
<script runat="server">
protected void Button1_ServerClick(object sender, EventArgs e)
{
p1.InnerText = "Hello " + textbox1.Value; //get textbox value and set in html p tag
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="textbox1" runat="server" /><br />
<input type="button" id="btn" runat="server" value="Click Me" onserverclick="Button1_ServerClick" />
<p id="p1" runat="server">see result here</p>
</div>
</form>
</body>
</html>
Basically something like this...
View (SomeAction.cshtml):
...
<p>ViewBag.SomeValue</p>
...
Controller:
...
[HttpGet]
public ActionResult SomeAction()
{
ViewBag.SomeValue = "Hello";
return View();
}
...
However you should learn much about approach which is used to build applications using ASP.MVC. It's completely different than ASP.NET WebForms. WebForms technology uses events while ASP.MVC uses Model View Controller. You have to change your mindset.

Spring form validation: unable to print errors in jsp

I am working on spring mvc application, there I have a form where a user can change his password. I am validating this form by using default spring form validation (see validator code below).
JSP Page:
<%# taglib uri="http://www.springframework.strong textorg/tags/form" prefix="spring"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!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> Change password </title>
</head>
<body>
<%#include file="index.jsp" %>
<div class="row">
<div class="container" style=" background-color: #F9FFED; ">
<div>
<h4><label>Change password:</label></h4>
</div>
<div class="col-md-12" >
<spring:form commandName="ChangePassword" action="ChangePassword.do" method="post">
<table>
<tr>
<td><label for="current_pwd" >Current Password</label></td>
<td><spring:input path="current_pwd" type="text" class="form-control" placeholder="Name"/></td>
<td><spring:errors path="current_pwd" type="text" cssStyle="color: red;"></spring:errors></td>
</tr>
<tr>
<td>&nbsp</td>
</tr>
<tr>
<td><label for="newpassword" >New Password</label></td>
<td><spring:input path="newpassword" type="text" class="form-control" placeholder="Password"/></td>
<td><spring:errors path="newpassword" type="text" cssStyle="color: red;"></spring:errors></td>
</tr>
<tr>
<td>&nbsp</td>
</tr>
<tr>
<td><label for="confirmPassword" >Confirm Password</label></td>
<td><spring:input path="confirmPassword" type="text" class="form-control" placeholder="Password"/></td>
<td><spring:errors path="confirmPassword" type="text" cssStyle="color: red;"></spring:errors></td>
</tr>
<tr>
<td>&nbsp</td>
</tr>
<tr>
<td>
<button type="submit" class="btn btn-success"> SAVE </button>
Cancel
</td>
</tr>
</table>
</spring:form>
</div>
</div>
</div>
</body>
</html>
Controller get and post methods:
#RequestMapping(value="/ChangePassword",method=RequestMethod.GET)
public String changePassword(ChangePassword chPaswd,BindingResult result,ModelMap model){
chPaswd=new ChangePassword();
model.addAttribute("ChangePassword",chPaswd);
return "ChangePassword";
}
#RequestMapping(value="/ChangePassword",method=RequestMethod.POST)
public String changePasswordPost(ChangePassword chpwd,BindingResult result,ModelMap model,HttpSession session){
String message="";
changepwdValidator.validate(chpwd, result);
chpwd=new ChangePassword();
if(result.hasFieldErrors()){
System.out.println("Has errors");
model.addAttribute("ChangePassword",chpwd);
return "ChangePassword";
}else{
System.out.println("chnage pwd values :"+chpwd.getNewpassword()+","+"current pwd:"+chpwd.getCurrent_pwd());
try{
// some other operations
model.addAttribute("ChangePassword",chpwd);
}catch(Exception e){
message="Failed to process the request, please re-verify the values!";
model.addAttribute("message", message);
}
return "ChangePassword";
}
}
Validator class:
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.knot.pirautomation.models.ChangePassword;
public class ChangePasswordValidator implements Validator{
ChangePassword chngepwd;
public boolean supports(Class clazz) {
return ChangePassword.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
if(target instanceof ChangePassword){
chngepwd=(ChangePassword) target;
System.out.println("----------");
System.out.println("Old pwd:"+chngepwd.getCurrent_pwd());
System.out.println("new pwd:"+chngepwd.getNewpassword());
System.out.println("confirm pwd:"+chngepwd.getConfirmPassword());
System.out.println("----------");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newpassword", "NewPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "ConfirmPassword.required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "current_pwd", "Oldpassword.required");
if( !(chngepwd.getNewpassword().equals(chngepwd.getConfirmPassword()))){
errors.rejectValue("newpassword", "NewPassword.match");
}
if((chngepwd.getNewpassword().length()<8)){
errors.rejectValue("newpassword", "NewPasswordlength.match" );
}
if((chngepwd.getConfirmPassword().length()<8)){
errors.rejectValue("confirmPassword", "ConfirmPasswordlength.match" );
}
String blackListChars = "!'=();<> \"";
char blackListArr[] = blackListChars.toCharArray();
for(int i=0;i<blackListArr.length;i++) {
if(chngepwd.getNewpassword().contains("" + blackListArr[i])) {
errors.rejectValue("newpassword","NewPassword.invalidChars");
break;
}
}
for(int i=0;i<blackListArr.length;i++) {
if(chngepwd.getConfirmPassword().contains("" + blackListArr[i])) {
errors.rejectValue("confirmPassword","ConfirmPassword.invalidChars");
break;
}
}
}
}
}
error.properties file:
Oldpassword.required= Old password is required
NewPassword.required= New password is required
ConfirmPassword.required= Confirm password should be required
NewPassword.match= Confirmation passwords should match
NewPasswordlength.match= New Password should be at least 8 characters
ConfirmPasswordlength.match= Confirm Password should be at least 8 characters
NewPassword.invalidChars=New Password has special characters which are not allowed
ConfirmPassword.invalidChars= Confirm Password has special characters which are not allowed
You can see that when the form has errors, I am returning control back to the same JSP.
My problem is that I am unable to trace the bug/error where my spring form validation is working fine, but when I am trying to display the errors which are defined in my properties file.
You should not explicitly invoke validator. Use this validation method instead:
#Valid #ModelAttribute("forName") FormName formName,
BindingResult bindingResult, Model model,
RedirectAttributes redirectAttributes, HttpSession session

calling different method of one spring controller

In my controller there are different method i want to call them with one form action. i dont know how to map map the request to particular method with different value of submit button , as i run my index page it directly go to controller from their it can render the view from view() of my controller and as the Search .jsp is open i get the by default 0 value on my EmployeeId input field i dont know why its happening plz help me out i m new on spring
here is my controller
package com.nousinfo.tutorial.controllers;
import java.util.List;
import org.springframework.stereotype.Controller;
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.nousinfo.tutorial.model.EmployeeForm;
import com.nousinfo.tutorial.service.impl.EmployeeServiceImpl;
import com.nousinfo.tutorial.service.model.EmployeeBO;
#Controller
#RequestMapping("/search")
public class SearchEmployeeController {
private EmployeeServiceImpl employeeServiceImpl;
public void setEmployeeServiceImpl(EmployeeServiceImpl employeeServiceImpl) {
this.employeeServiceImpl = employeeServiceImpl;
}
#RequestMapping(value = "/searchspring", method = RequestMethod.GET)
public ModelAndView view(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
model.setViewName("Search");
return model;
}
#RequestMapping(value = "/employeeNo", method = RequestMethod.POST)
public ModelAndView searchByEmpNo(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
Long i = employeeForm.getEmployeeNumber();
EmployeeBO employeeBO = employeeServiceImpl.getEmployee(i);
System.out.println(employeeBO);
model.addObject("employeeBO", employeeBO);
model.setViewName("EmployeeDetail");
return model;
}
#RequestMapping(value = "/empByName", method = RequestMethod.POST)
public ModelAndView searchByEmployeeName(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
List<EmployeeBO> employeeBOs = employeeServiceImpl
.findEmployees(employeeForm.getFirstName());
model.addObject("listEmployeeBO", employeeBOs);
model.setViewName("EmployeeList");
return model;
}
#RequestMapping(value = "/empByDeptId", method = RequestMethod.POST)
public ModelAndView searchByDeptId(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
ModelAndView model = new ModelAndView();
model.addObject("employeeForm", employeeForm);
List<EmployeeBO> employeeBOs = employeeServiceImpl
.getAllEmployeeByDeptid(employeeForm.getDepartmentId());
model.addObject("listEmployeeBO", employeeBOs);
model.setViewName("EmployeeList");
return model;
}
}
and this is my index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
response.sendRedirect("/EmployeeWebSpring/search/searchspring");
%>
this is my search.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# 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/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<fmt:setBundle basename="ApplicationResources" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Search Page</title>
</head>
<body>
<form:form action="/EmployeeWebSpring/search/empByName" commandName="employeeForm" method="post">
<table border="0">
<tr>
<td>Employee_ID</td>
<td><form:input path="employeeNumber" /></td>
<td><input type="submit" name="method" value="FindById" /></td>
</tr>
<tr>
<td>Employee_Name</td>
<td><form:input path="firstName" /></td>
<td><input type="submit" name="method" value="FindByName" /></td>
</tr>
<tr>
<td>Employee_Name</td>
<td><form:input path="departmentId" /></td>
<td><input type="submit" name="method" value="FindByDeptNO" /></td>
</tr>
<tr>
<td colspan="2" align="center"><font size=3>For
Searching the employees by<b>Employee Name</b><br />you can use %
match all the records with the given pattern
</font><br /> <font size="2"> <i>e.g <b> for search by</b>EmployeeName<br />
matches alL the employees whose name starts with character <b>S</b></i></font></td>
</tr>
</table>
</form:form>
</body>
</html>
As an alternative to configuring different endpoints for the same form based on the button clicked (using either separate forms in the HTML or changing the form action via JS), you could use the params attribute of the RequestMapping annotation to further narrow the form submission to a specific controller method based on the value of the button (or any other form submitted field). See the Spring documentation on this for more detail.
Using this strategy, your request mappings would look something like this:
#RequestMapping(value = "/employeeSearch", method = RequestMethod.POST, params="method=FindByName")
public ModelAndView searchByEmployeeName(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
...
#RequestMapping(value = "/employeeSearch", method = RequestMethod.POST, params="method=FindByDeptNO")
public ModelAndView searchByDeptId(
#ModelAttribute("employeeForm") EmployeeForm employeeForm) {
...
#RequestMapping(value = "/employeeSearch", method = RequestMethod.POST, params="method=FindById")
public ModelAndView searchByEmpNo(
#ModelAttribute("employeeForm") EmployeeForm employeeForm)
throws Exception {
...
i dont know how to map map the request to particular method with different value of submit button
Have each search in a separate form. Each form mapped to different controller methods. Like this:
<form:form action="empById" method="post" commandName="searchBean">
Employee_ID
<form:input path="employeeNumber" />
<input type="submit" name="method" value="FindById" />
</form:form>
<form:form action="empByName" method="post" commandName="searchBean">
Employee_Name
<form:input path="firstName" />
<input type="submit" name="method" value="FindByName" />
</form:form>
<form:form action="empByDeptNo" method="post" commandName="searchBean">
Employee_Name
<form:input path="departmentId" />
<input type="submit" name="method" value="FindByDeptNO" />
</form:form>
Now different search requests will map to the correct controller method.
i get the by default 0 value on my EmployeeId input field i dont know why its happening
Before you add an instance of EmployeeForm to the model, initialize it to what ever default value you would like to have seen in the search page.

Spring MVC not showing result in jsp

I am new for Spring Framework. In my POC I am not getting the model value in jsp.
below is my code
My Controller is
#Controller
public final class ContactController {
#Autowired
private Validator validator;
public void setValidator(Validator validator) {
this.validator = validator;
}
#RequestMapping(value = "/form", method = RequestMethod.GET)
public String get(ModelMap model) {
// Because we're not specifying a logical view name, the
// DispatcherServlet's DefaultRequestToViewNameTranslator kicks in.
UserMessage Message = new UserMessage();
System.out.println("Hello Get Method");
model.addAttribute("userMessage", Message);
return "form";
}
#RequestMapping(value = "/form", method = RequestMethod.POST)
public String post(#ModelAttribute("userMessage") UserMessage userMsg,
BindingResult result, Model model) {
validator.validate(userMsg, result);
System.out.println(userMsg.getName());
model.addAttribute("userMsg",userMsg);
if (result.hasErrors()) { return "form"; }
// Use the redirect-after-post pattern to reduce double-submits.
return "thanks";
}
My jsp form is as below
<form:form modelAttribute="userMessage">
<div class="form-item">
<div class="form-label">Your name:</div>
<form:input path="name" size="40" cssErrorClass="form-error-field"/>
<div class="form-error-message"><form:errors path="name"/></div>
</div>
<div class="form-item">
<div class="form-label">Your e-mail address:</div>
<form:input path="email" size="40" cssErrorClass="form-error-field"/>
<div class="form-error-message"><form:errors path="email"/></div>
</div>
<div class="form-item">
<div class="form-label">Your message:</div>
<form:textarea path="text" rows="12" cols="60" cssErrorClass="form-error-field"/>
<div class="form-error-message"><form:errors path="text"/></div>
</div>
<div class="form-item">
<input type="submit" value="Submit" />
</div>
</form:form>
Configuration file as below
<bean id="configurationLoader"
class="org.springmodules.validation.bean.conf.loader.annotation.AnnotationBeanValidationConfigurationLoader"/>
<bean id="validator" class="org.springmodules.validation.bean.BeanValidator"
p:configurationLoader-ref="configurationLoader"/>
<!-- Load messages -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource"
p:basenames="errors"/>
<!-- Discover POJO #Components -->
<!-- These automatically register an AutowiredAnnotationBeanPostProcessor -->
<context:component-scan base-package="contact"/>
<!-- Map logical view names to physical views -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/>
after filling the form I want the command Object details back in in jsp page so I write as below (thanks.jsp)
<%# page import="contact.UserMessage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Thank You</title>
</head>
<body>
<h1>Thank You</h1>
Welcome <%= request.getParameter("name") %>
Name is ${userMsg.name}
</body>
</html>
request.getParameter("name") is giving correct result but ${userMsg.name} is printing as it is why?
try to enable EL
<%# page isELIgnored="false" %>
Make sure that you have the taglib definition on the page:
%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

ASP.NET MVC - EntityFramework and Binding to a List

I am currently using the EntityFramework to bind my ASP.NET MVC project to a MySQL database and one of my entities, Product, has an Images property containing a collection of ProductImages. I have built a form to allow the user to modify a given Product and this form includes fields for editing all of the images associated to that Product as well. After reading Phil Haack's and Dan Miser's posts on the matter I have a decent idea of what needs to happen, but I can't seem to make it work for some reason...
Here is my Product form:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KryptonCMS.Models.Product>" %>
<%# Import Namespace="KryptonCMS.Core" %>
<%# Import Namespace="KryptonCMS.Models.ViewModels" %>
<% using (Html.BeginForm())
{%>
<ul class="gallery">
<%
var index = 0;
foreach (var image in Model.ImageList.OrderBy(p => p.Order))
{
%>
<li>
<% Html.RenderPartial("ProductImageForm", image, new ViewDataDictionary(ViewData) { { "index", index } }); %>
</li>
<%
index++;
}
%>
</ul>
<p>
<input type="submit" name="btnSave" value="Save" />
<input type="submit" name="btnCancel" value="Cancel" />
</p>
<% } %>
And here is the definition for ProductImageForm:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<KryptonCMS.Models.ProductImage>" %>
<%# Import Namespace="KryptonCMS.Core" %>
<div>
<%
var fieldPrefix = string.Format("images[{0}]", ViewData["index"]); %>
<%=Html.Hidden(fieldPrefix + "ID", Model.ID) %>
<img src="<%=UtilityManager.GetProductImagePath(Model.Product.ID, Model.FileName, true) %>"
alt="" /><br />
<label for="Description">
Description:</label>
<%=Html.TextBox(fieldPrefix + "Description", Model.Description) %><br />
<label for="Order">
Order:</label>
<%=Html.TextBox(fieldPrefix + "Order", Model.Order)%><br />
</div>
And finally my ProductsController actions:
public ActionResult Edit(int id)
{
var product = productsRepository.GetProduct(id);
if (product == null)
return View("NotFound", new MasterViewModel());
// else
return View(ContentViewModel.Create(product));
}
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public ActionResult Edit(int id, FormCollection formCollection)
{
var product = productsRepository.GetProduct(id);
if (formCollection["btnSave"] != null)
{
if (TryUpdateModel(product) && TryUpdateModel(product.Images, "images"))
{
productsRepository.Save();
return RedirectToAction("Details", new { id = product.ID });
}
return View(ContentViewModel.Create(product));
}
// else
return RedirectToAction("Details", new { id = product.ID });
}
The HTML output for a single ProductImageForm looks like this:
<div>
<input id="images[0]ID" name="images[0]ID" type="hidden" value="1" />
<img src="/Content/ProductGallery/3/thumbs/car1.jpg"
alt="" /><br />
<label for="Description">
Description:</label>
<input id="images[0]Description" name="images[0]Description" type="text" value="FAST CAR" /><br />
<label for="Order">
Order:</label>
<input id="images[0]Order" name="images[0]Order" type="text" value="1" /><br />
</div>
I have tried all sorts of methods of reorganizing my form including taking the Image collection out of the Product form and placing it in its own (which I really don't want to do), but nothing is working. Is there something blatatently wrong with my approach here?
You are missing dots in inputs' names:
<%= Html.Hidden(fieldPrefix + ".ID", Model.ID) %>
<%= Html.TextBox(fieldPrefix + ".Description", Model.Description) %>
<%= Html.TextBox(fieldPrefix + ".Order", Model.Order) %>
Check this blog post: http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

Resources