I am trying to use kendo ui gantt chart in a jsp file. I am using spring mvc and maven for the project. I was following the tutorial given in spring demos, but still I am not getting the result. Nothing is getting displayed in the jsp page.
JSP
<%#page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%#page import="java.util.HashMap"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Date"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<kendo:gantt name="gantt" height="700" showWorkDays="false" showWorkHours="false" snap="false">
<kendo:gantt-views>
<kendo:gantt-view type="day" />
<kendo:gantt-view type="week" selected="true" />
<kendo:gantt-view type="month" />
</kendo:gantt-views>
<kendo:gantt-columns>
<kendo:gantt-column field="id" title="ID" width="50" />
<kendo:gantt-column field="title" title="Title" editable="true" />
<kendo:gantt-column field="start" title="Start Time" format="{0:MM/dd/yyyy}" width="100" />
<kendo:gantt-column field="end" title="End Time" format="{0:MM/dd/yyyy}" width="100" />
</kendo:gantt-columns>
<kendo:dataSource batch="false">
<kendo:dataSource-schema>
<kendo:dataSource-schema-model id="id">
<kendo:dataSource-schema-model-fields>
<kendo:dataSource-schema-model-field name="id" type="number" />
<kendo:dataSource-schema-model-field name="orderId" type="number" />
<kendo:dataSource-schema-model-field name="parentId" defaultValue="null" nullable="true" type="number" />
<kendo:dataSource-schema-model-field name="start" type="date" />
<kendo:dataSource-schema-model-field name="end" type="date" />
<kendo:dataSource-schema-model-field name="title" defaultValue="No title" type="string" />
<kendo:dataSource-schema-model-field name="percentComplete" type="number" />
<kendo:dataSource-schema-model-field name="expanded" type="boolean" defaultValue="true" />
<kendo:dataSource-schema-model-field name="summary" type="boolean" />
</kendo:dataSource-schema-model-fields>
</kendo:dataSource-schema-model>
</kendo:dataSource-schema>
<kendo:dataSource-transport>
<kendo:dataSource-transport-read url="/Gantt/tasks/read" dataType="json" type="POST" contentType="application/json" />
<kendo:dataSource-transport-parameterMap>
<script>
function parameterMap(options, type) {
return JSON.stringify(options.models || [ options ]);
}
</script>
</kendo:dataSource-transport-parameterMap>
</kendo:dataSource-transport>
</kendo:dataSource>
<kendo:dependencies batch="false">
<kendo:dataSource-schema>
<kendo:dataSource-schema-model id="id">
<kendo:dataSource-schema-model-fields>
<kendo:dataSource-schema-model-field name="id" type="number" />
<kendo:dataSource-schema-model-field name="predecessorId" type="number" />
<kendo:dataSource-schema-model-field name="successorId" type="number" />
<kendo:dataSource-schema-model-field name="type" type="number" />
</kendo:dataSource-schema-model-fields>
</kendo:dataSource-schema-model>
</kendo:dataSource-schema>
<kendo:dataSource-transport>
<kendo:dataSource-transport-read url="/Gantt/dependencies/read" dataType="json" type="POST" contentType="application/json" />
<kendo:dataSource-transport-parameterMap>
<script>
function parameterMap(options, type) {
return JSON.stringify(options.models || [ options ]);
}
</script>
</kendo:dataSource-transport-parameterMap>
</kendo:dataSource-transport>
</kendo:dependencies>
</kendo:gantt>
Controller
#Controller
public class IndexController {
#Autowired
private GanttTaskDao taskDao;
#Autowired
private GanttDependencyDao dependencyDao;
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(Locale locale, Model model) {
return "index";
}
#RequestMapping(value = "/tasks/read", method = RequestMethod.POST)
public #ResponseBody List<GanttTask> read_tasks() {
return taskDao.getList();
}
#RequestMapping(value = "/dependencies/read", method = RequestMethod.POST)
public #ResponseBody List<GanttDependency> read_dependencies() {
return dependencyDao.getList();
}
}
I also used debug mode to run the project but request is going only till /index method and no request is getting send to /gantt/tasks/read or /gantt/dependency/read methods.
I tried using different url in case there might be some error in that. but its still not working.
I dont know where I went wrong. Anybody knows the answer. Is there anything else which i might be missing?
Okay I had done some silly mistake I forgot to include the js and css files to my jsp. I have include it now. When i use debug mode it is retrieving the tasks and dependencies but it is not showing it in my jsp. I can only see the empty chart window. please somebody help.
Related
I got next problem with my application. I want to internationalize my pages. On first page I have problem, because app translate only first variable. Firstly i added messages_en.properties in src/main/resources.
addGame.form.gameId.label = Game ID
addGame.form.gameName.label = Game name
addGame.form.gamePlatform.label = Game platform
addGame.form.gamePrice.label = Game price
addGame.form.gameDescription.label = Game description
addGame.form.gameCategory.label = Game category
addGame.form.gamesInStock.label = Games in stock
addGame.form.condition.label = Game condition
addGame.form.gameImage.label = Game image
Next step was add choice of language in addGame.jsp. It's work good.
<div class="pull-right" style="padding-right:50px">
angielski
</div>
Next step in DispatcherServlet-context.xml added one bean.
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl"/>
</bean>
And in same file
<mvc:interceptors>
<bean class= "org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="language"/>
</bean>
</mvc:interceptors>
And last what i do was added language to GameController like this.
#InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setDisallowedFields("unitsInOrder", "discontinued");
binder.setAllowedFields("gameId", "gameName", "gamePrice", "gameDescription","gamePlatform", "gameCategory", "gamesInStock", "gameImage", "language");
}
Screen from page
On screenshot you can see my page after click English language. its changing only first variable. Could you tell me why?
Mine code. You can see messages_en.properties up. This is DispatcherServlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven enable-matrix-variables="true"
validator="validator" />
<context:annotation-config />
<mvc:resources mapping="/resource/**" location="/resources/" />
<context:component-scan base-package="com.kk.gamestore" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="json" value="application/json;charset=UTF-8" />
<entry key="xml" value="application/xml;charset=UTF-8" />
<entry key="html" value="text/html;charset=UTF-8" />
</map>
</property>
<property name="defaultViews">
<list>
<ref bean="jsonView" />
<ref bean="xmlView" />
</list>
</property>
</bean>
<bean id="jsonView"
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prettyPrint" value="true" />
</bean>
<bean id="xmlView"
class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.kk.gamestore.domain.Game</value>
</list>
</property>
</bean>
</constructor-arg>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="pl" />
</bean>
<mvc:interceptors>
<bean class="com.kk.gamestore.interceptor.PerformanceMonitorInterceptor" />
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property value="language" name="paramName"/>
</bean>
<bean class="com.kk.gamestore.interceptor.AuditingInterceptor" />
<bean class="com.kk.gamestore.interceptor.PromoCodeInterceptor">
<property name="promoCode" value="PROMOGRY" />
<property name="errorRedirect" value="invalidPromoCode" />
<property name="offerRedirect" value="games" />
</bean>
</mvc:interceptors>
</beans>
There is GameController. I added position language in method - setAllowedFields
package com.kk.gamestore.controller;
import java.io.File;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.kk.gamestore.domain.Game;
import com.kk.gamestore.exception.GameNotFoundException;
import com.kk.gamestore.service.GameService;
#RequestMapping("/games")
#Controller
public class GameController {
#Autowired
private GameService gameService;
#RequestMapping
public String Welcome(Model model) {
model.addAttribute("games", gameService.getAllGames());
return "games";
}
#RequestMapping("/all")
public String allGames(Model model) {
model.addAttribute("games", gameService.getAllGames());
return "games";
}
#RequestMapping("/{platform}")
public String getGamesByPlatform(Model model, #PathVariable("platform") String gamePlatform) {
model.addAttribute("games", gameService.getGamesByPlatform(gamePlatform));
return "games";
}
#RequestMapping("/filter/{ByCriteria}")
public String getGamesByFilter(#MatrixVariable(pathVar="ByCriteria")
Map<String,List<String>> filterParams, Model model){
model.addAttribute("games", gameService.getGamesByFilter(filterParams));
return "games";
}
#RequestMapping("/game")
public String getGamesById(#RequestParam("id") String gameId, Model model){
Game game = gameService.getGameById(gameId);
model.addAttribute("game", game);
return "game";
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAddNewGameForm(Model model) {
Game newGame = new Game();
model.addAttribute("newGame", newGame);
return "addGame";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String processAddNewGameForm(#ModelAttribute("newGame") #Valid Game gameToBeAdded, BindingResult result, HttpServletRequest request) {
if(result.hasErrors()) {
return "addGame";
}
String[] suppressedFields = result.getSuppressedFields();
if (suppressedFields.length > 0) {
throw new RuntimeException("Próba wiązania niedozwolonych pól: " + StringUtils.arrayToCommaDelimitedString(suppressedFields));
}
MultipartFile gameImage = gameToBeAdded.getGameImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
if (gameImage!=null && !gameImage.isEmpty()) {
try {
gameImage.transferTo(new File(rootDirectory+"resources\\images\\"+gameToBeAdded.getGameId() + ".png"));
} catch (Exception e) {
throw new RuntimeException("Blad podczas zapisu okladki gry.", e);
}
}
gameService.addGame(gameToBeAdded);
return "redirect:/games";
}
#InitBinder
public void initialiseBinder(WebDataBinder binder) {
binder.setAllowedFields("gameId", "gameName", "gamePrice", "gameDescription","gamePlatform", "gameCategory", "gamesInStock", "gameImage", "condition" , "language");
}
#ExceptionHandler(GameNotFoundException.class)
public ModelAndView handleError(HttpServletRequest req, GameNotFoundException exception) {
ModelAndView mav = new ModelAndView();
mav.addObject("invalidGameId", exception.getGameId());
mav.addObject("exception", exception);
mav.addObject("url", req.getRequestURL()+"?"+req.getQueryString());
mav.setViewName("gameNotFound");
return mav;
}
#RequestMapping("/invalidPromoCode")
public String invalidPromoCode() {
return "invalidPromoCode";
}
}
And AddGame.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"%>
<%#page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet"
href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<title>Gry</title>
</head>
<body>
<section>
<div class="jumbotron">
<div class="container">
<h1>Gry</h1>
<p>Dodaj gry</p>
</div>
wyloguj
<div class="pull-right" style="padding-right:50px">
<a href="?language=pl" >polski</a>|<a href="?language=en" >angielski</a>
</div>
</div>
</section>
<section class="container">
<form:form modelAttribute="newGame" class="form-horizontal" enctype="multipart/form-data">
<form:errors path="*" cssClass="alert alert-danger" element="div"/>
<fieldset>
<legend>Dodaj nową grę</legend>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameId">
<spring:message code="addGame.form.gameId.label"/>
</label>
<div class="col-lg-10">
<form:input id="gameId" path="gameId" type="text" class="form:input-large" />
<form:errors path="gameId" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameName">Nazwa</label>
<div class="col-lg-10">
<form:input id="gameName" path="gameName" type="text" class="form:input-large" />
<form:errors path="gameName" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gamePrice">Cena</label>
<div class="col-lg-10">
<form:input id="gamePrice" path="gamePrice" type="text" class="form:input-large" />
<form:errors path="gamePrice" cssClass="text-danger"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gamePlatform">Platforma Gry</label>
<div class="col-lg-10">
<form:radiobutton path="gamePlatform" value="PS4" />
Playstation 4
<form:radiobutton path="gamePlatform" value="XBOX ONE" />
Xbox One
<form:radiobutton path="gamePlatform" value="PS3" />
Playstation 3
<form:radiobutton path="gamePlatform" value="XBOX 360" />
Xbox 360
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gameCategory">Kategoria</label>
<div class="col-lg-10">
<form:input id="gameCategory" path="gameCategory" type="text" class="form:input-large" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2 col-lg-2" for="gamesInStock">Liczba gier w magazynie</label>
<div class="col-lg-10">
<form:input id="gamesInStock" path="gamesInStock" type="text" class="form:input-large" />
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gameDescription">Opis</label>
<div class="col-lg-10">
<form:textarea id="gameDescription" path="gameDescription" rows="2"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="condition">Stan</label>
<div class="col-lg-10">
<form:radiobutton path="condition" value="New" />
Nowy
<form:radiobutton path="condition" value="Old" />
Używany
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="gameImage">
<spring:message code="addProdcut.form.gameImage.label"/>
</label>
<div class="col-lg-10">
<form:input id="gameImage" path="gameImage" type="file" class="form:input-large" />
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" id="btnAdd" class="btn btn-primary" value="Dodaj" />
</div>
</div>
</fieldset>
</form:form>
</section>
</body>
</html>
I haven't idea what i doing wrong. Button of changing language working well, but it's translate only first variable no more. On screen you can see en version (not default) and it changed only first variable and next variable name its from default lang. I haven't problems in console when running application just one warning like this.
WARNING: [SetContextPropertiesRule]{Context} Setting property 'source' to 'org.eclipse.jst.jee.server:gamestoreCOPIED' did not find a matching property.
#EDIT:
Hi, after few days coding and repairing errors im back there. I got new informations.
PROBLEM : Application working good.
Locale change button working good. After click on this button application generate link (if english button click: http://localhost:8080/gamestore/games/add?language=en or if polish: add?language=pl)
and language are changing.
When i want change it on english language it translate me only first word of messages_en.properties. When i make english language default - its same situation - only first word its changing.
In console 0 errors only one warning but its nothing in this topic.
Problem is when i try change language on english or use on default english its change only first line of messages_en.properties.
If i change ResourceBundleMessageSource for ReloadableResourceBundleMessageSource(with changing classpath and make it good)
nothing changed.
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
I need this line.
<mvc:annotation-driven enable-matrix-variables="true"
So i can't make mine app with HandlerMapping. But if i do it its not working.
I read a lot of informations and trying find answer in network but nothing work. Anyone got similiar problems in past?
I am trying to implement SimpleCaptcha with Struts 2, so far the image is displaying. However, it is displaying at the top of the <s:form>.
register.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<head>
...
<s:head />
</head>
<body>
<b>REGISTER</b>
<p>Please fill up the form below.</p>
<s:form action="register" method="post">
<s:textfield label="Enter username" key="userId" maxlength="25"
size="30" />
<s:textfield label="Enter email" key="userEmail1" type="email"
placeholder="someone#domain.com" size="30" />
<s:textfield label="Re-enter email" key="userEmail2" type="email"
placeholder="someone#domain.com" size="30" />
<s:password label="Enter password" key="userPassword1" size="30" />
<s:password label="Re-enter password" key="userPassword2"
size="30" />
<img src="<c:url value='simple-captcha.png' />" />
<br />
Cannot read? Refresh page for new CAPTCHA.
<s:textfield label="Enter CAPTCHA" key="captchaAnswer" size="30" />
<s:submit value="Register" />
</s:form>
</body>
How do I make the image appear above the Enter CAPTCHA textfield as specified in the code?
The image should be generated by the captcha action. Then you provide the URL to this action in <img> tag. To implement captcha in your project follow steps below
Add the jar to your web project classpath: simplecaptcha-1.2.1.jar.
Typically inside web-inf/lib folder.
Add new action class RegisterAction
Note: The following code is using convention plugin to map actions and for simplicity DMI is used to invoke some methods of the action class when form is submitted. To turn on DMI use a constant in struts.xml:
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
RegisterAction.java:
public class RegisterAction extends ActionSupport {
private String userId;
private String userEmail1;
private String userEmail2;
private String userPassword1;
private String userPassword2;
private String captchaResponse;
private InputStream inputStream;
//getters and setters
public String create() {
//RegisterAction is the form bean of the current action and captchaResponse is the field of user input
String answer = (String) ActionContext.getContext().getSession().get("CorrectAnswer");
if (answer == null || getCaptchaResponse()==null || !answer.equals(getCaptchaResponse())){
addFieldError("captchaResponse", getText("error.captcha"));
}
return SUCCESS;
}
#Action(value = "captcha", results = {#Result(type="stream", params = {"contentType", "image/jpeg"})})
public String captcha() {
try {
Captcha captcha = new Captcha.Builder(200, 50).addText(new DefaultTextProducer()).gimp(new DropShadowGimpyRenderer()).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//write the image
CaptchaServletUtil.writeImage(outputStream, captcha.getImage());
//store the answer for this in session
ActionContext.getContext().getSession().put("CorrectAnswer", captcha.getAnswer());
//return image
inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
RegisterAction.properties contains the following value for the error key:
RegisterAction.properties:
error.captcha=Invalid value of shown text!
so we check either pass successfully or add to errors error regarding captcha.
Add register.jsp Typically in web-inf\content
register.jsp:
<!DOCTYPE html>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<b>REGISTER</b>
<p>Please fill up the form below.</p>
<s:form action="register" method="post">
<s:textfield label="Enter username" key="userId" maxlength="25"
size="30" />
<s:textfield label="Enter email" key="userEmail1" type="email"
placeholder="someone#domain.com" size="30" />
<s:textfield label="Re-enter email" key="userEmail2" type="email"
placeholder="someone#domain.com" size="30" />
<s:password label="Enter password" key="userPassword1" size="30" />
<s:password label="Re-enter password" key="userPassword2"
size="30" />
<tr><td>
<img id="captchaImg" src="<s:url action='captcha'/>" alt="Captcha Image" height="45">
<img src="<c:url value='/images/reload.jpg' />" alt="Reload" onclick="document.forms[0].captchaImg.src='<s:url action='captcha'/>'+'?id='+Math.random();" style="cursor:pointer"/>
<s:textfield label="Enter CAPTCHA" key="captchaResponse" size="30" requiredLabel="*"/>
<tr><td>
Cannot read? Refresh page for new CAPTCHA.
</td></tr>
<s:submit method="create" value="Register" />
</s:form>
</body>
</html>
This will construct the Captcha and the text field to enter the value and Struts error message to show errors in captchaResponse field, plus the refresh icon.
NOTE: a good trick we used here is the javascript Math.random() function, this way prevent certain browsers like Firefox to cache the URL and keep posting the same Captcha image, this enforce it to get the new value without doing any more effort.
Here is how it will looks like:
For more details refer to the web site : SimpleCaptcha
This is just to show how I went about the solution. I was unaware you can put <tr><td> inside the <s:form>. Thanks to Roman C, I got the CAPTCHA image to display where I wanted it to.
register.jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<head>
...
<s:head />
</head>
<body>
<b>REGISTER</b>
<p>Please fill up the form below.</p>
<s:form action="register" method="post">
<s:textfield label="Enter username" key="userId" maxlength="25"
placeholder="someone" size="30" />
<s:textfield label="Enter email" key="userEmail1"
placeholder="someone#domain.com" size="30" />
<s:textfield label="Confirm email" key="userEmail2"
placeholder="someone#domain.com" size="30" />
<s:password label="Enter password" key="userPassword1" size="30" />
<s:password label="Confirm password" key="userPassword2"
size="30" />
<tr>
<td></td>
<td>
<img src="<c:url value='simple-captcha.png' />" />
<br />
Cannot read? Press F5 to refresh.
</td>
</tr>
<s:textfield label="Enter code" key="captchaAnswer" size="30" />
<s:submit value="Register" />
</s:form>
</body>
RegisterAction.java:
import nl.captcha.Captcha;
...
public class RegisterAction extends ActionSupport implements SessionAware, Message {
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
private String userId;
private String userEmail1;
private String userEmail2;
private String userPassword1;
private String userPassword2;
private String captchaAnswer;
#Override
public String execute() throws Exception {
// business logic to insert user into database
return SUCCESS;
}
#Override
public void validate() {
Captcha captcha = (Captcha) session.get(Captcha.NAME);
if(!captcha.isCorrect(getCaptchaAnswer())) {
addFieldError("captchaAnswer", INCORRECT_CAPTCHA);
}
// other validations
}
#Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
// getters and setters
}
struts.xml:
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="register" class="com.mypackage.action.RegisterAction">
<result name="success">/login.jsp</result>
<result name="input">/register.jsp</result>
</action>
<!-- other actions -->
</package>
</struts>
web.xml:
(The <init-param> is optional.)
<servlet>
<servlet-name>SimpleCaptcha</servlet-name>
<servlet-class>nl.captcha.servlet.SimpleCaptchaServlet</servlet-class>
<init-param>
<param-name>captcha-width</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>captcha-height</param-name>
<param-value>50</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SimpleCaptcha</servlet-name>
<url-pattern>/simple-captcha.png</url-pattern>
</servlet-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
OUTPUT:
I am trying to display a dijit.Dialog as a popup window. This is a new feature addition to an existing project and as I have never woked wth Dojo;s before I am struggling a bit.
I have created the pop up window but it keeps displaying as a seperate page than a popup, what am I doing wrong? Please help!
THe page where the button to show the popup
<input class="style_off pink_button ft_white" onclick='submitOnclick()' id="show_popup" type="submit" name="showPopup" value="Generate PopUp"/>
<span id="validationPopUp" style="display:none;"><c:out value=""/></span>
The script page:
function submitOnclick() {
dojo.xhrPost({
url: "${get_valpopup_url}",
form: dojo.byId("searchResults"),
load: function(data){
//Destroy widget to avoid reallocating it during parse.
if(valDialog) {
valDialog.destroy();
}
dojo.place(data, "validationPopUp", "only");
dojo.parser.parse("validationPopUp");
valDialog = dijit.byId('inputPopUpId');
valDialog.show();
},
error: function(e) {
console.log("Ajax call failed", e);
}
});
return false;
}
the pop up window
<?xml version="1.0" encoding="UTF-8"?>
<div id="inputPopUpId" dojotype="dijit.Dialog" title="${popup_title}"
height="500px;" xmlns:f="http://www.twister.total.com/taglib"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
xmlns:tiles="http://tiles.apache.org/tags-tiles"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:util="urn:jsptagdir:/WEB-INF/tags/util"
xmlns:form="http://www.springframework.org/tags/form"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:s="http://www.twister.total.com/taglib/sessionAttr"
xmlns:spring="http://www.springframework.org/tags" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<spring:message code="random_extract_popup_title" var="popup_title" htmlEscape="false" />
<p>
<spring:message code="random_extract_popup_message" />
</p>
<form:form method="post" modelAttribute="inputPopup" action="reports" enctype="application/x-www-form-urlencoded">
<s:insertSessionConversationId attributeName="searchResults"/>
<s:insertSessionConversationId attributeName="searchDto"/>
<div>
<label for="noOfRecords">
<spring:message code="random_extract_popup_form_label" />
</label>
<input id="noOfRecords" type='text' name='noOfRecords' style="width:150px" />
<spring:message code="random_extract_popup_form_message" var="name_msg" htmlEscape="false" />
<script type="text/javascript">
<c:set var="sec_name_msg">
<spring:escapeBody javaScriptEscape="true">${name_msg}</spring:escapeBody>
</c:set>
Spring.addDecoration(new Spring.ElementDecoration({elementId : "noOfRecords", widgetType : "dijit.form.NumberTextBox", widgetAttrs : {promptMessage: "${sec_name_msg}", required : true, constraints: {pattern: "0, ####"}}}));
</script>
</div>
<br />
<br />
<div class="submit">
<spring:message code="button_extract_random_report" var="extract_random_report" htmlEscape="false" />
<script type="text/javascript">Spring.addDecoration(new Spring.ValidateAllDecoration({elementId:'extract_random_report', event:'onclick'}));</script>
<input class="startLoading style_off pink_button ft_white" id="extract_random_report" type="submit" name="extractrandom" value="${fn:escapeXml(extract_random_report)}"/>
</div>
</form:form>
</div>
The views.xml
<definition extends="empty" name="a/s/validationPopUpId">
<put-attribute name="body" value="validation-dialog.jspx"/>
</definition>
The code in the controller
#RequestMapping(value = "sox/search/reports", params="showPopup", method = RequestMethod.POST)
public String generatePopup(#ModelAttribute(TwisterConstants.SEARCH_RESULTS) AuditSoxListResultsDto searchResults, #ModelAttribute(TwisterConstants.SEARCH_DTO) AuditSoxSearchRequest searchDto,
Model uiModel, Locale selectedLocale, HttpServletRequest request, HttpServletResponse response){
uiModel.addAttribute(TwisterConstants.SEARCH_RESULTS, TwisterConstants.SEARCH_DTO);
addDateTimeFormatPatterns(uiModel,"S-");
return "a/s/validationPopUpId";
}
I try to send url parameter to Action class as described here: How to access url parameters in Action classes Struts 2
If I do like next, it works and I can get pageLevel in Action class
<s:form action="index?pageLevel=99">
<s:checkboxlist label="Select" list="colors" name="yourColor" value="defaultColor" />
<s:submit value="Submit" />
</s:form>
But next does not work
<s:form action="index?pageLevel=<%=level%>">
And this does not work too
<c:set var="pageLevel" scope="page" value="<%=level%>" />
<s:form action="index?pageLevel=${pageLevel}">
I get error
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /start.jsp (line: 86, column: 0)
According to TLD or attribute directive in tag file, attribute action
does not accept any expressions
Jsp page contains
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
How can I do it?
Have a 'level' property in your index action with its getter an setter
Something like:
public class Index extends ActionSupport {
private String level;
public String getLevel() {
return this.getLevel();
}
public void setLevel(String level) {
this.level = level;
}
}
Set 'level' as a hidden parameter in the form.
Assuming your action name is "index" and the request parameter is "pageLevel":
<s:form action="index">
<s:checkboxlist label="Select" list="colors" name="yourColor" value="defaultColor" />
<s:hidden name="level" value="%{#parameters.pageLevel}" />
<s:submit value="Submit" />
</s:form>
Try this
<s:form action="index">
<s:checkboxlist label="Select" list="colors" name="yourColor" value="defaultColor" />
<s:hidden name="pageLevel" value="%{pageLevel}"/>
<s:submit value="Submit" />
</s:form>
I have a problem using ajax with struts
I want to load dependent dropdown list using ajax. I am using struts2.
Below is the code for the jsp.
<%# 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">
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Enter Product</title>
<script type="text/javascript">
var request;
function findindex1()
{
var temp=document.getElementById("country").value;
if(window.ActiveXObject){ request = new ActiveXObject("Microsoft.XMLHTTP"); }
else if(window.XMLHttpRequest){ request = new XMLHttpRequest(); } request.onreadystatechange = showResult;
request.open("POST",'temp.action?index='+temp,true);
request.send(null);
}
function showResult(){
if(request.readyState == 4){
alert(request.responseText+"1");
document.getElementById("text").innerHTML=request.responseText; //Just to test
var val=<%=request.getParameter("index") %> -
/* document.getElementById("city").flush(); */
}
alert(request.responseText+"1");
}
function change(){
var temp=document.getElementById("country").value;
location.href='loadProduct.action';
}
</script>
</head>
<body onload="fill()">
<s:form method="post" action="product.action" name="product" theme="simple">
<table id="table">
<tr><td>Country</td><td><s:select id="country" name="country.countryId" list="countryList" listKey="countryId"
listValue="name" onchange="findindex1()" ></s:select></td></tr>
<tr>
<td>City</td>
<td><s:select id="city" name="city.id" list="cities" listKey="id"
listValue="name" headerKey="city.id" ></s:select></td>
</tr>
<tr>
<td>Product Desc</td>
<td><s:textfield name="product.description"></s:textfield></td>
</tr>
<tr>
<td>Product Name</td>
<td><s:textfield name="product.name"></s:textfield></td>
</tr>
<tr>
<td><s:submit id="search" name="submit" value="Search"></s:submit></td>
<td><s:submit name="submit" value="Create"></s:submit>
</td>
</tr>
<tr>
<td></td>
<td><s:label id="text" name="text">Text to change</s:label>
</td>
</tr>
</table>
</s:form>
</body>
</html>
I have checked the code and it sets the value of the List cities in the action class on changing the value of the country dropdown in the jsp. But i am unable to reflect the changes in the jsp .
The action class function is :
public String temp()
{
String[] id=(String[])getParameters().get("index");
index=Integer.parseInt(id[0]);
cities=(ArrayList<City>)productCreateService.selectCities(Integer.parseInt(id[0]));
for(Iterator<Country> i=countryList.iterator();i.hasNext();)
{
Country c = i.next();
if(c.getCountryId()==Integer.parseInt(id[0]))
{
Country c1= countryList.get(0);
country=c;
break;
}
}
String out="";
for(Iterator<City> i=cities.iterator();i.hasNext();)
{
}
inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
return SUCCESS;
}
All the varibles have getter setters . I know the code is messed up . Initially i testes it for cities tag. When that didnt work i tried testing on a simple tag (here id="text") . But even that didnt work .
The model, Services and DAO(though not here) are all correct.
The struts.xml file is as follows .
<!-- Some or all of these can be flipped to true for debugging -->
<constant name="struts.i18n.reload" value="true" />
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="false" />
<constant name="struts.custom.i18n.resources" value="global" />
<constant name="struts.action.extension" value="action" />
<constant name="struts.serve.static" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />
<constant name="actionPackages" value="com.oxxo.pilot.web.action" />
<package name="default" extends="struts-default" namespace = "/">
<global-results>
<result name="custom_error">/jsp/exception.jsp</result>
<result name="input">/jsp/fail.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="custom_error" />
<action name="temp" class="ProductAction" method="temp">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
Could somebody please tell me what am i doing wrong. If you need any part of the code please let me know . Thanks .