Struts2 internalization - java

I'm try to internalize my application with the next code:
For the jsp I have this:
<table>
<tr class="trlleno">
<td>
<div id="Panel_cliente">
<s:select label="Selecciona un idioma" name="IdiomaID" id="IdiomaID"
headerValue="--Selecciona un idioma--" headerKey="-1"
list="#{'1':'Español','2':'English','3':'Deutch','4':'Português','5':'русский','6':'Français'}" value="2"/>
</div>
</td>
</tr>
<td class="trboton" colspan="2" align="center">
<input type="submit" name="submit" id="submit" value="CAMBIAR IDIOMA" class="divboton"/>
</td>
</tr>
</table>
</form>
In the action I have this:
public class CambiarIdiomaAction extends ActionSupport implements ServletRequestAware{
private HttpServletRequest servletRequest;
Map session;
#Override
public String execute() throws Exception {
session = ActionContext.getContext().getSession();
int idm=Integer.valueOf(servletRequest.getParameter("IdiomaID"));
System.out.println(idm);
//Trying with English
Locale locale=new Locale("en","EN");
return "SUCCESS";
}
#Override
public void setServletRequest(HttpServletRequest request) {
this.servletRequest = request;
}
public HttpServletRequest getServletRequest() {
return servletRequest;
}
}
When I see if there is a change with the language, I see nothing, no changes. Why?. Thanks so much

You have to set locale in session if you want to change locale.
If you put this code in an Action:
ActionContext context = ActionContext.getContext();
context.setLocale(Locale.ENGLISH);
You will change the locale of your app to English.
In your code you are doing nothing, you only are setting a variable locale put you don't do anything with it.

If you really want to change locale in your action then use
ActionContext.getContext().setLocale(locale)
and to put it in HTTP session
session.put(I18nInterceptor.DEFAULT_SESSION_ATTRIBUTE, locale)
But Struts2 has out of the box localization support. I suggest you to read about localization in Struts2 http://struts.apache.org/2.x/docs/localization.html.

Related

JSP Input value To Java Method -> HttpServletRequest gives NULL value

Hello Guys.
I have simple Storage page whichs display all Products from DB.
I set to each of them with Unique name to change the Amount of product.
When i want to catch this value in Java method its returns me null.
Can you help me what i need to do to corretly catching value's in this text inputs ?
Controller :
#Controller
public class StoragePageController extends HttpServlet {
#GET
#RequestMapping(value = "/storage/subamount/{id}")
public String substractTheAmountValue(#PathVariable("id") int id, Model model, HttpServletRequest request) {
String amount_req = request.getParameter("amount_sub_" + id);
System.out.println(amount_req);
return null;
}
}
JSP fragment :
<c:set var="licznik" value="${recordStartCounter }" />
<div align="center">
<table width="1000" border="0" cellpadding="6" cellspacing="2">
<c:forEach var="u" items="${productList }">
<c:set var="licznik" value="${licznik+1}" />
<tr onmouseover="changeTrBg(this)" onmouseout="defaultTrBg(this)">
<td align="right"><c:out value="${licznik }" /></td>
<td align="left"><c:out value="${u.description }" /></td>
<td align="left"><c:out value="${u.amount }" /></td>
<td align="center"><input type="text" name="amount_sub_${licznik}" id="amount_sub_${licznik}"></td>
<td align="center"><input type="button" value="Substract the value" onclick="window.location.href='${pageContext.request.contextPath}/storage/subamount/${licznik}'"/></td>
</tr>
</c:forEach>
</table>
You should be having your API controller like the one given below given that your UI is posting the data to your API / Controller (assuming you are using the latest version of Spring Boot). You have a #Get mapping which does not accept request payload in the body.
#RestController
public class StoragePageController {
#PostMapping(value = "/storage/subamount/{id}", produces = {"application/json"})
public String substractTheAmountValue(#PathVariable("id") int id, Model model) {
String amount_req = id;
System.out.println(amount_req);
return null;
}
}

How to get data from jsp page in struts1

I have below JSP page. Using this I can bind data and its working fine.
I am using logic:iterate for binding data from list.
What I am doing fetch the data from database and set it to list and using this list I can bind data into login iterate.
I am using below VO for bind data:
public class EDCPEmployeeRequestForm extends ActionForm {
private static final long serialVersionUID = 1L;
private String employeeCode ;
private String employeeName;
private String employeeAddress;
private String cardNo;
private String employeeEmailId;
private String employeeContactNo;
private String company;
private String strCompany;
private String employeeWorkCity;
private String employeeWorkLocation;
private String band;
private String status;
private EDCPNomineeDetailsForm[] nomineeDetailsList;
// getter and setter method....
.....
Now I want get the data from list which is use in the login:iterator. Why I need if any user login first time then empty list will generate and empty data all the field in which are used within login:iterate.
When user press the submit button in the the above form then below action class is execute :
public class EDCPEnrollmentAction extends Action {
Logger LOGGER = Logger.getLogger(this.getClass());
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession(false);
EDCPEmployeeRequestForm eDCPEmployeeRequestForm = (EDCPEmployeeRequestForm) form;
LOGGER.info("EDCPRequest Object : "+eDCPEmployeeRequestForm.toString());
}
}
Ouput when user press submit button :
EDCPEmployeeRequestForm [employeeCode=123456, employeeName=Test,
employeeAddress=null, cardNo=null, employeeEmailId=test#gmail.com,
employeeContactNo=124589652, company=null, strCompany=1001,
employeeWorkCity=1001, employeeWorkLocation=10011, band=2D,
status=null, nomineeDetailsList=null]
You can see that nomineeDetailsList=null its showing null.
But now problem is that I am getting the value for nomineeDetailsList field. Every time I am getting null when I am trying to get value from VO.
My HTML file is designed as below :
<html:form action="/eDCPEnrollment" onsubmit="return checkallfields()">
<logic:iterate id="nomineeData" name="eDCPEmployeeRequestForm" property="nomineeDetailsList" indexId="index" >
<table width="709" border="0" align="center" cellpadding="1" cellspacing="0">
<tr>
<td width="162" height=10></td>
<td width="162"></td>
<td width="162"></td>
<td width="163"></td>
<td width="50"></td>
</tr>
<tr>
<td align="right" class="text">Name :</td>
<td align="center"><html:text property="firstName" name="nomineeData"
maxlength="25" styleClass="textfield" indexed="true"></html:text></td>
<td align="center"><html:text property="middleName" name="nomineeData"
maxlength="25" styleClass="textfield" indexed="true"></html:text></td>
<td align="center"><html:text property="lastName" name="nomineeData"
maxlength="25" styleClass="textfield" indexed="true"></html:text></td>
<td></td>
</tr>
<tr><td><html:submit styleClass="button"></html:submit></td></tr>
</table>
</html:form>
I am stuck here. Please correct me if I missing something.

JSP Servlet displaying inexisting data

I created a simple servlet which was printing some message like this:
#WebServlet("/servletExample")
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello there");
}
Everything worked well.
Then i created 2 jsp pages like this:
<body>
<form method="post" action="servletExample">
<table border="0">
<tr>
<td>
First name:
</td>
<td>
<input type="text" name="firstname"/>
</td>
</tr>
<tr>
<td>
Last name:
</td>
<td>
<input type="text" name="lastname"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
</body>
and
<body>
<%
String firstName = (String)request.getAttribute("firstname");
String lastName = (String)request.getAttribute("lastname");
out.println(firstName+ " "+lastName);
%>
</body>
The servlet looks like this now:
#WebServlet("/servletExample")
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
if(firstName == null || lastName==null){
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
request.setAttribute("firstname", firstName);
request.setAttribute("lastname", lastName);
getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
}
}
When i run it i see that form but when i submit i see "Hello there" from the example i did 2 days ago. Whatever i do i see that.
What do i have to clean?
What am i missing?
Edit: I use eclipse and tomcat 7
Assuming you are in Eclipse, stop your Tomcat server, select your project, in Eclipse's menu select Project and Clean and then Build Project. Then restart your Tomcat server and try again.
Eclipse uses the last built project version with Tomcat every time you run. You need to clean up the project and rebuild it for Eclipse and Tomcat to refresh the changes.

Binding problems using Spring MVC

I am using Spring MVC 3.1 to develop a Java web app. I have a JSP that has two paired radio buttons, an entry field, and a dropdown select box. I need these values to be available to my mapped controller, via a model class' fields.
The security and URL mapping works fine, as I've seen in debugger before. The issue is that when I tried to get the JSP data values populating my model, I get an error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'cccForm' available as request attribute
Here is part of my JSP:
<c:url var="cccUrl" value="/registers/default/ccPreauth/authorize" />
<div class="mainWrapper">
<form:form id="cccForm" action="${cccUrl}" method="post" modelAttribute="cccForm">
...
<table>
<tbody>
<tr>
<th>Select an option.</th>
</tr>
<tr>
<td>
<div class="field-input">
<form:radiobutton id="paymentOption" path="paymentOption" value="authorizeCC" />
Collect Credit Card Information
</div>
<div class="field-input">
Authorization Amount $
<form:input path="authAmount" maxlength="10" size="10" class="extendWidth"/>
<span class="instructions">
<spring:message code="label.authorization.note" />
</span>
</div>
<div class="field-input">
<form:radiobutton id="paymentOption" path="paymentOption" value="cancelAuth" />
Choose a Reason and Cancel Credit Card Collection
</div>
<div class="field-input right">
<form:select id="selectedReason" path="selectedReason" >
<c:forEach items="${reasonList}" var="reason">
<option value=${reason.reasonText}>${reason.reasonText}</option>
<br />
</c:forEach>
</form:select>
</div></td>
</tr>
</tbody>
</table>
</div>
<div class="right">
<button class="btnBlue" id="submitButton" type="submit">
Here is part of my controller:
#Controller
#RequestMapping(value = "/registers/default/ccPreauth")
#SessionAttributes(ControllerConstants.DEFAULT_REGISTER_ATTR_NM)
public class CCCaptureController {
...
#RequestMapping(value="/authorize" )
public ModelAndView authorize(
final Authentication auth,
final #ModelAttribute("ccCapturePaymentRequest") CCCapturePaymentForm ccCapturePaymentRequest,
final BindingResult result,
final HttpServletResponse response) {
final ModelAndView mav = new ModelAndView(CC_PREAUTH_PAYMENT_VIEW);
return mav;
}
and finally, here is my model class:
public class CCCapturePaymentForm implements Serializable {
private static final long serialVersionUID = 6839171190322687142L;
#NumberFormat(style = Style.CURRENCY)
private BigDecimal authAmount;
private String selectedReason;
private String paymentOption;
public BigDecimal getAuthAmount() {
return authAmount;
}
public void setAuthAmount(BigDecimal authAmount) {
this.authAmount = authAmount;
}
public String getSelectedReason() {
return selectedReason;
}
public void setSelectedReason(String selectedReason) {
this.selectedReason = selectedReason;
}
public String getPaymentOption() {
return paymentOption;
}
public void setPaymentOption(String paymentOption) {
this.paymentOption = paymentOption;
}
}
Can anyone tell me what I need to get this to work correctly? Please don't stop at just the reason for the exception above - please verify and correct my code as I am on a tight schedule as usual and have little experience with Spring MVC. Thanks!
You have this in your form:
modelAttribute="cccForm"
So you should have this in your controller:
#ModelAttribute("cccForm") CCCapturePaymentForm ccCapturePaymentRequest
That's how you bind the form backing object with the model attribute.
I found the answer for those Spring MVC newbies...
I had to set the "cccForm" to a new instance of my next page's form inside the controller search method (that then tries to being up the page that was getting the error).
In a nutshell: I had to set the empty backing bean value in the preceding controller method so that the follow-on method and JSP page have it to work with.
Hope this helps someone else avoid my mistake.
Mark

Create a form with multiple checkboxes in spring

I have a game and a developer. The game has a set of developers. I want to create a form where I can add a game to the database. In the form I enter the name, price and check the developers. So i create a checkbox for every developer. However when I check those the page just seems to refresh. When I debug it seems that my controller never gets to the doSubmitAction function. When I leave out the checkboxes everything works as it is supposed to.
Is spring unable to create the collection? I don't understand fully what is happening behind the scenes of Spring. This is my first project I'm creating using spring.
Here is my form:
<form:form method="POST" commandName="game" >
<table>
<tr>
<td>
Name
</td>
<td>
<form:input path="gameNaam" size="20" />
</td>
</tr>
<tr>
<td>Choose Developers</td>
<td>
<form:checkboxes id="selectdeveloper" items="${developers}" path="developers" itemLabel="naam" />
</td>
</tr>
<tr>
<td>
Price
</td>
<td>
<form:input path="prijs" size="10" />
</td>
</tr>
<tr>
<td>
<input type="submit" value="Add" />
</td>
<td></td>
</tr>
</table>
</form:form>
And the formController:
public class GameFormController extends SimpleFormController {
private GameOrganizer gameOrganizer;
public GameFormController() {
setCommandClass(Game.class);
setCommandName("game");
setFormView("AddGame");
setSuccessView("forward:/Gamedatabase.htm");
}
public void setGameOrganizer(GameOrganizer gameOrganizer){
this.gameOrganizer=gameOrganizer;
}
#Override
protected Object formBackingObject(HttpServletRequest request) throws Exception {
Game game = null;
long id = ServletRequestUtils.getLongParameter(request, "id");
if(id<=0){
game = new Game();
}else{
game = gameOrganizer.getGame(id);
}
return game;
}
#Override
protected void doSubmitAction(Object command) throws Exception {
Game game = (Game) command;
if(game.getId()<=0){
gameOrganizer.addGame(game);
}else{
gameOrganizer.update(game);
}
}
#Override
protected Map referenceData(HttpServletRequest request) throws Exception {
Set<Developer> developers = gameOrganizer.getAllDevelopers();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("developers", developers);
return map;
}
}
Ok so apparently I had to make a propertyEditor for Developer.
There is a good explanation on this site:
http://static.springsource.org/spring/docs/2.0.x/reference/validation.html
Edit extra information:
So apparently when you check a checkbox it will give you the value as a string.
Ofcourse the Collection had to be made with developer objects.
So I created a developerEditor:
package domainmodel;
import java.beans.PropertyEditorSupport;
public class DeveloperEditor extends PropertyEditorSupport {
private GameOrganizer gameOrganizer;
public void setGameOrganizer(GameOrganizer gameOrganizer) {
this.gameOrganizer = gameOrganizer;
}
#Override
public void setAsText(String id) {
long id2 = Long.parseLong(id);
Developer type = gameOrganizer.getDeveloper(id2);
setValue(type);
}
}
And with the checkboxes I gave as itemvalue the id of the object
<form:checkboxes id="selectdeveloper" items="${allDevelopers}" itemValue="id" path="developers" itemLabel="name" />
Then in the formcontroller I override the initBinder method.
So that when I Spring has to fill in a developer object it will first convert it from string to a Developer Object using my editor.
private DeveloperEditor developerEditor;
public void setDeveloperEditor(DeveloperEditor developerEditor){
this.developerEditor = developerEditor;
developerEditor.setGameOrganizer(gameOrganizer);
}
#Override
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
binder.registerCustomEditor(Developer.class, developerEditor);
}
That's it folks.
If anyone has any questions I will be glad to answer them.

Categories

Resources