Prepopulate form in Struts1 - forms

I have a jsp as my view, which displays a form for adding a new user/ updating the user, if one is selected. I can't figure out how to prepopulate my form if a user is selected. I read about the solution using 2 actions, with the same form, one of which is just used to populate the fields, and on for submitting the data.
However, this doesn't work for me, as my action (the one defined in action attribute for the form) isn't called when loading the jsp (can't really explain this either, the menu and pages are defined in an xml file). I don't understand how to specify the second action in my jsp, and how to make sure that the action is called when first loading the jsp. I would prefer a solution not involving AJAX, if possible. Thanks.

Why do you want to go for AJAX, when you have the power of Struts. I have a simple example (it is tested) for you.
MyForm.java
package com.tusar.action;
import java.io.Serializable;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import javax.servlet.http.HttpServletRequest;
public class MyForm extends ActionForm implements Serializable{
private static final long serialVersionUID = 1043346271910809710L;
private String fullName = null;
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
/*This method will be called when you press the reset button
or load the form. You may want to populate the form here also*/
public void reset(ActionMapping mapping, HttpServletRequest request){
String reset = (String)request.getAttribute("myForm.reset");
if ((null != reset)|| ("true".equals(reset))) {
fullName = null;
}
}
}
MyFormSetupAction.java
package com.tusar.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class MyFormSetupAction extends Action{
/*Set your form-bean properties here*/
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
MyForm hwForm = (MyForm) form;
hwForm.setFullName("tusar");
return mapping.findForward("success");
}
}
MyFormSuccessAction.java
package com.tusar.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class MyFormSuccessAction extends Action{
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return mapping.findForward("success");
}
}
struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
"http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<!-- ==================== Form Bean Definitions -->
<form-beans>
<form-bean name="myForm" type="com.tusar.action.MyForm">
<form-property name="fullName" type="java.lang.String"/>
</form-bean>
<!-- ============= Global Forward Definitions -->
<global-forwards>
<!-- Default forward to "Welcome" action -->
<!-- Demonstrates using index.jsp to forward -->
<forward name="home" path="/home.do"/>
</global-forwards>
<!-- ===================== Action Mapping Definitions -->
<action-mappings>
<!-- This action will load the form-->
<action path="/home"
type="com.tusar.action.MyFormSetupAction"
name="myForm"
validate="false"
input="/WEB-INF/jsp/home.jsp">
<forward name="success" path="/WEB-INF/jsp/home.jsp" />
</action>
<!-- This action will evalutae the form and pass form data to
success page-->
<action path="/successAction"
type="com.tusar.action.MyFormSuccessAction"
name="myForm"
validate="true"
input="/WEB-INF/jsp/home.jsp">
<forward name="success" path="/WEB-INF/jsp/success.jsp" />
</action>
</action-mappings>
<!-- ============= Message Resources Definitions -->
<message-resources parameter="MessageResources" />
</struts-config>
home.jsp
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%# taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page isELIgnored="false"%>
<html>
<head>
<title>Struts 1</title>
</head>
<body>
<html:form action="/successAction.do">
Name:
<html:text property="fullName"></html:text>
<html:submit value="Next"></html:submit>
<html:reset value="Cancel"></html:reset>
</html:form>
</body>
</html>
success.jsp
<%# taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%# taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%# taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page isELIgnored="false"%>
<html>
<head>
<title>Successful !</title>
</head>
<body>
<h3>Your details:</h3>
Name:
<bean:write name="myForm" property="fullName" />
</body>
</html>
Everytime you call the home.do action, the fullName property is populated with "tusar". Just comment if you need any further association, I'll be happy to help you. Thanks!

There should be an action called when selecting the user. The properties of that user should be copied into the action form before returning the action forward.
Without any configuration information it's difficult to help beyond that.

Related

Why method prefix not working in Struts 2.3.32

I use Struts 2.3.32 and this is the code.
methodPrefix.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:form action="methodPrefix" theme="simple">
name: <br/>
<s:textfield name="name"/>
<br><br>
<s:submit value="Create Person"/>
<s:submit name="method:cancel" value="Cancel"/>
</s:form>
</body>
</html>
MethodPrefixAction.java
public class MethodPrefixAction
{
private String name;
private String message;
public String execute() throws Exception
{
message = name + " create";
return "success";
}
public String cancel() throws Exception
{
message = "cancel";
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.mapper.action.prefix.enabled" value="true" />
<package name="default" extends="struts-default" namespace="">
<action name="goMethodPrefixPage">
<result>/chapter4/methodPrefix.jsp</result>
</action>
<action name="methodPrefix" class="example.chapter4.MethodPrefixAction">
<result>/chapter4/methodPrefixResult.jsp</result>
</action>
</package>
</struts>
when I push Cancel button, It do not call cancel() method, just call execute() method.
I don't know why method: prefix not work.
I searched a lot, and I know method: prefix configuration is false by default in Struts 2.3.32, so I used a constant..... but it did not work
This constant
<constant name="struts.mapper.action.prefix.enabled" value="true" />
works only for action: prefix, not a method: prefix. So you should use the action attribute to submit tag.
<s:submit action="cancel" value="Cancel"/>
Note: If you have DMI turned off the action: prefix is still available.
This tutorial explains it and this tutorial shows how to do validation
Method MethodPrefixAction.execute should return success or cancel string.
In struts.xml you can redirect user to different pages based on return string:
<action name="methodPrefix" class="example.chapter4.MethodPrefixAction">
<result name="success">/chapter4/methodPrefixResult.jsp</result>
<result name="cancel">/chapter4/methodPrefix.jsp</result>
</action>

How to put value in textbox getting as a parameter in request object

I have a textbox whose value I want to set with the value I get as a parameter in the request from user.
For example, the request is :
localhost:8084/quiz/login.jsp?uname=manish
I want to display "manish" in the textbox in the form.
How can I do that?
Here is the full code of my login.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<%
String error=(String)request.getParameter("error");
String uname=request.getParameter("uname");
if(error!=null)
{
if(error.equalsIgnoreCase("no_username_password"))
out.println("Username and password can't be empty");
if(error.equalsIgnoreCase("no_username"))
out.println("Username is required");
if(error.equalsIgnoreCase("no_password"))
out.println("Password is required");
}
%>
<form method="post" action="LoginServlet">
UserName: <input name="Username"><br>
Password: <input name="password"><br>
<input type="submit">
</form>
</body>
</html>
and this is the code of my servlet
package com.util.Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet(description = "Will take username and password from login.html and validate user", urlPatterns = { "/LoginServlet" })
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String username=request.getParameter("Username");
String password=request.getParameter("password");
//PrintWriter out=response.getWriter();
//System.out.println(request.getAttribute("Error"));
//HttpSession session=request.getSession();
if((username=="" || username==null)&&(password=="" || password==null) )
{
response.sendRedirect("Login.jsp?error=no_username_password");
}
else if((username=="" || username==null)&&(password!=""||password!=null))
{
response.sendRedirect("Login.jsp?error=no_username");
}
else if((username!="" || username!=null)&&(password==""||password==null))
{
String url="Login.jsp?error=no_password&uname="+username;
response.sendRedirect(url);
}
}
}
You can get the request parameter value and print it out using the <c:out> taglib. ${param} is request parameter object and uname is your parameter name.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<input name="Username" value="<c:out value="${param.uname}"/>">
Following what you currently have in your JSP file you can do it like:
<input name="Username" value="<%= uname %>">
I'm not an jsp developer but i think you must do something like this in your HTML:
UserName: <input name="Username" value="<%= request.getParameter("uname") %>"><br>

How to post a form in Adobe CQ 5.5?

I am very new to CQ, I have been strugglung with this for a very long time now. What I want to do is "Create a page That accepts username password using regular tag and post the data to a servlet.
The servlet checks username password using str.equals("username") hardcoded and redirects to another page i.e. success or failure"
Please note that I am building a website that will has common users like for example 'People who are registered to a site like stackoverflow etc' These users are not authors who can edit content.
A very basic task but too difficult for me. Here is the code.
I wrote sling Post servlet using CRXDE created bundle sucessfully
package com.example;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#Component(immediate=true, metatype=false, label="EXAMPLE SERVLET")
#Service
#Properties(value = {
#org.apache.felix.scr.annotations.Property(name="sling.servlet.methods", value={"POST"}),
#org.apache.felix.scr.annotations.Property(name="sling.servlet.resourceTypes", value={"sling/servlet/default"}),
#org.apache.felix.scr.annotations.Property(name="sling.servlet.selectors", value={"SELECTORNAME"}),
#org.apache.felix.scr.annotations.Property(name="sling.servlet.extensions", value={"html"})
})
public class ExampleServlet extends SlingAllMethodsServlet {
private static final Logger log = LoggerFactory.getLogger(ExampleServlet.class);
private static final long serialVersionUID = 1L;
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
//String redirect = request.getParameter(":redirect");
log.info("The Sling Post Servlet- Example Servlet has been called !! ");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("oliver")&& password.equals("oliver"))
{
response.sendRedirect("/content/mywebsite/en/products");
}
else
{
response.sendRedirect("/content/mywebsite/en/services");
}
log.info("Sucessfull Response Sent ");
}
}
I get error as
Status
200
Message
OK
Location /example.SELECTORNAME.html
Parent Location /
Path
/example.SELECTORNAME.html
Referer http://localhost:4502/content/mywebsite/en/products.html
ChangeLog
<pre>modified("/example.SELECTORNAME.html/username");<br/
and the jsp is as follows
<%--
My Content Page Componenet component.
General Description
--%><%
%><%#include file="/libs/foundation/global.jsp"%><%
%><%#page session="false" %>
<%
%><%
// TODO add you code here
%>
<%# 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>
<cq:include script="head.jsp"/>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My title</title>
</head>
<body>
<div>My First Page </div>
<form action="/example.SELECTORNAME.html" method="POST">
<input type="text" name ="username"/>
<input type="password" name "password"/>
<input type="submit" value="Login"/>
</form>
</body>
</html>
Thanks in advance!!
Servlet path is missing in your file.
/**
* #scr.component metatype="false"
* #scr.service interface="javax.servlet.Servlet"
* #scr.property name="sling.servlet.paths" values="/bin/login"
*/
public class LoginServlet extends SlingAllMethodsServlet {
......
}
jsp -
form name="frmLogin" id="frmLogin" method="post" action="/bin/login"

GWT codeserver parameter

i've encountered an issue on GWT codeserver parameter in a simple scenario below,
Project structure
myapp
+src
++mypkg
---MainWindow.gwt.xml
---NextWindow.gwt.xml
+++client
----MainWindow.java
----NextWindow.java
+war
--MainWindow.html
--NextWindow.html
MainWindow.gwt.xml
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='mainwindow'>
<inherits name='com.google.gwt.user.User'/>
<entry-point class='mypkg.client.Mainwindow'/>
<source path='client'/>
</module>
MainWindow.java
package mypkg.client;
import com.google.gwt.core.client.*;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.ui.*;
public class MainWindow implements EntryPoint {
#Override
public void onModuleLoad() {
Button button = new Button("NextWindow!");
button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.open("/NextWindow.html", null, null);
}
});
RootPanel.get().add(button);
}
}
MainWindow.html
<!doctype html>
<html>
<head>
<title>MainWindow</title>
<script type="text/javascript" language="javascript"
src="mainwindow/mainwindow.nocache.js"></script>
</head>
<body>
<h1>Hi, MainWindow!</h1>
</body>
</html>
NextWindow.gwt.xml
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='nextwindow'>
<inherits name='com.google.gwt.user.User'/>
<entry-point class='mypkg.client.NextWindow'/>
<source path='client'/>
</module>
NextWindow.java
package mypkg.client;
import com.google.gwt.core.client.*;
import com.google.gwt.user.client.ui.*;
public class NextWindow implements EntryPoint {
#Override
public void onModuleLoad() {
RootPanel.get().add(new Label("Hi, NewLabel!"));
}
}
NextWindow.html
<!doctype html>
<html>
<head>
<title>NextWindow</title>
<script type="text/javascript" language="javascript"
src="nextwindow/nextwindow.nocache.js"></script>
</head>
<body>
<h1>Hi, NextWindow!</h1>
</body>
</html>
On Devmode launch the compiled myapp from the link,
http://127.0.0.1:8888/MainWindow.html?gwt.codesvr=127.0.0.1:9997
Click on button "NextWindow" then GWT browser plugin pops up a complaint window,
Module NextWindow need be (re)compiled!
Confirm it then a new browser window is open from the link on Prodmode,
http://127.0.0.1:8888/NextWindow.html
instead of the desired link on Devmode,
http://127.0.0.1:8888/NextWindow.html?gwt.codesvr=127.0.0.1:9997
Consequently it displays only,
Hi, NextWindow!
But the very anticipated content below doesn't show up,
Hi, NewLabel!
If we trail GWT codeserver parameter ?gwt.codesvr=127.0.0.1:9997 to the source code, the problem could be solved by sacrificing the consistency on source level between Devmode and Prodmode.
What are the preferable solutions indeed?
You can use if(GWT.isProdMode()) to check for Prodmode and Devmode, and trail the parameter if it is devmode.
That doesn't affect production mode - the gwt compiler is smart enough to just ignore devmode-code, so the devmode-block never makes it into the compiled javascript.

Return UTF-8 encoding from an Action in Struts 2

I'm trying to output a list of strings to a jsp page using struts 2. The template file is something like this:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<s:iterator value="vars">
<p><s:property /></p>
</s:iterator>
</body>
</html>
The corresponding java action file is:
public class TestAction extends ActionSupport {
private static final long serialVersionUID = 1L;
List<String> vars = null;
public List<String> getVars() { return vars; }
public void setVars(List<String> vars) { this.vars = vars; }
#Override
public String doExecute() throws Exception {
vars = new ArrayList<String>();
vars.add("Users");
vars.add("Organizações");
vars.add("Eventos");
vars.add("Locais");
return SUCCESS;
}
}
The problem is that, the result is:
Users
Organizações
Eventos
Locais
(source code)
<p>Users</p>
<p>Organizações</p>
<p>Eventos</p>
<p>Locais</p>
which I believe it means that I'm receiving the strings encoded with something that's not UTF-8. Any ideas on how to solve this?
This is very late reply, but I want to update this to help, somebody who stuck with this bug. Add following lines to your jsp to resolve the issue.
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<s:property escapeHtml="false"/>
Depending on your version of struts 2
Older: (this is deprecated in newer versions)
<s:property escape="false"/>
Newer: (not sure which version this was introduced)
<s:property escapeHtml="false"/>