How to post a form in Adobe CQ 5.5? - aem

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"

Related

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>

Create a simple Login page using jsp and session

I have created a simple login page in which user will give an username and password , and then it will be stored in session. After clicking on submit button it will show welcome user or the name. And if the user waits for few seconds then the session will expire and it automatically return back to the login page.
Here is my login page
<%# page import="java.io.*,java.util.*" 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">
<jsp:useBean id="user" class="user.LoginUser" scope="session"></jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login</title>
</head>
<body>
<h1><center>Give your login details</center></h1>
<form method="post" action="check.jsp">
Username:<input type="text" name="username" size="20" value="<%=user.getUser() %>" > <br>
Password:<input type="password" name="password" size="20" value=<%=user.getPassword() %> ><br>
<input type="submit">
</form>
</body>
</html>
now in check.jsp i am doing my checking part for username and password
<%# page import="java.io.*,java.util.*" 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">
<jsp:useBean id="user" class="user.LoginUser" scope="session"></jsp:useBean>
<jsp:setProperty name="user" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login checking</title>
</head>
<body>
<%
String USER=user.getUsername();
int PASSWORD=user.getPassword();
if(USER.equals("abhirup"))
{
if(PASSWORD==54321)
{
pageContext.forward("display.jsp");
}
else
{
out.println("Wrong password");
pageContext.include("login.jsp");
}
pageContext.include("login.jsp");
}
%>
</body>
</html>
and then finally i am displaying it in display.jsp
<%# page import="java.io.*,java.util.*" 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">
<jsp:useBean id="user" class="user.LoginUser" scope="session" ></jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Display</title>
</head>
<body>
<% String title="Welcome : successful login";
out.println(title);%>
<h3><center>Your Name:Abhirup Parui</center></h3><br>
Username<%=user.getUsername()%><br>
<%session.setMaxInactiveInterval(20);
pageContext.include("login.jsp");
%>
</body>
</html>
and also this is my LoginUser.java file
package user;
public class LoginUser {
String username;
int password;
public void setUsername(String value)
{
username=value;
}
public void setPassword(int value)
{
password=value;
}
public String getUsername(){return username;}
public int getPassword(){return password;}
}
I am using Eclipse IDE and Tomcat server. Eclipse has shown not a single error in any of the pages but still when i run my login.jsp page.
I am getting this error on running login.jsp
i have followed this link
please help me to find my errors.
Update
I can successfully run my login page.
I am getting this error now, but could not figure out where is the error.
last part of the error is this
how to fix these error . help
Because you're trying to access login.jsp directly from the browser you have to move it out of the WEB-INF directory - files in WEB-INF are not publicly accessible. If you move login.jsp up one directory and enter http://localhost:8088/abhirup/login.jsp in your browser it should pull up the page. However, it is a fairly common practice to put jsp pages under WEB-INF/jsp or something similar and use a servlet to intercept and process requests and then have the servlet forward to the appropriate jsp page.
You have a syntax error on line 1, column 46 of display.jsp because you have the word page before your language declaration. Change this:
<%# page import="java.io.*,java.util.*" page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
to this:
<%# page import="java.io.*,java.util.*" language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
I also tried the same code and I found some error in two JSP files
My login.jsp corrected code is as given below:
<%# page import="java.io.*,java.util.*" language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="user.LoginUser"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="user" class="user.LoginUser" scope="session"></jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login page</title>
</head>
<body>
<h1><center>Give your login details</center></h1>
<form method="post" action="check.jsp">
User name:<input type="text" name="username" size="20" value="<%=user.getUsername() %>"><br>
Password:<input type="password" name="password" size="20" value="<%=user.getPassword()%>" ><br>
Submit <input type="submit">
</form>
</body>
</html>
Corrected check.jsp code is as follows:
<%# page import="java.io.*,java.util.*" language="java" contentType="text/html;charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%# page import="user.LoginUser"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="user" class="user.LoginUser" scope="session"></jsp:useBean>
<jsp:setProperty name="user" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login checking</title>
</head>
<body>
<%
String USER=user.getUsername();
String PASSWORD=user.getPassword();
if(USER.equals("admin"))
{
if(PASSWORD.equals("admin"))
{
pageContext.forward("display.jsp");
}
else
{
out.println("Wrong password");
pageContext.include("login.jsp");
}
pageContext.include("login.jsp");
}
%>
</body>
</html>
Corrected display.jsp code:
<%# page import="java.io.*,java.util.*" language="java" contentType="text/html;charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%# page import="user.LoginUser"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="user" class="user.LoginUser" scope="session" ></jsp:useBean>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Display</title>
</head>
<body>
<% String title="Welcome : Successful Login";
out.println(title);%>
<h3> <center> Your Name : Reneesh </center> </h3><br>
User name : <%=user.getUsername()%><br>
<%session.setMaxInactiveInterval(20);
%>
</body>
</html>
My Java file LoginUser.java corrected code is as follows:
package user;
public class LoginUser {
String username;
String password;
public void setUsername(String value)
{
username=value;
}
public void setPassword(String value)
{
password=value;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
}
Kindly try with this code, I made some changes in the code by assigning String valuue for Password. I also used Eclipse juno IDE and Apache Tom Cat v 7.0 for running this Dynamic web project. Hope you will try and let me know if there is further error.

Populating Spring MVC form

I have created the following Controller class:
package com.bilitutor.cct.control;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.ModelAndView;
import com.bilitutor.cct.bean.*;
import com.bilitutor.cct.service.*;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
UserService userService;
#ModelAttribute("user")
public User getUserObect() {
return new User();
}
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Landing page. Just return the login.jsp
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(ModelMap model) {
logger.info("home() called");
model.addAttribute("emailErrorMessage", "Please enter Email");
return "login";
}
/**
* New User signup. If user already exists, send back the error, or send an email and forward to the email validation page
*/
#RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(ModelMap model, #ModelAttribute("user")User user, BindingResult result) {
logger.info("signup() : email="+user.getEmail()+" pass="+user.getPassword()+" accessCode="+user.getAccessCode());
try {
userService.addUser(user);
} catch (DataIntegrityViolationException e) {
logger.info("Email already exists");
model.addAttribute("emailErrorMessage", "Email already exists");
}
return "login";
}
}
And the following JSP
<%#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/core" prefix="c"%>
<html>
<body>
<form:form id="mainForm" method="post" commandName="user">
<table id="mainTable">
<tr id="emailRow"><td rowspan="2" class="lrPadding">Email</td><td class="lrPadding"><form:input id="email" path="email" class="editable"/></td></tr>
<tr id="emailErrorRow"><td id="emailError" class="errorMessage">${emailErrorMessage}</td></tr>
</table>
</form:form>
</body>
</html>
When I load the page for the first time, I can see the message "Please Enter Email" on my login.jsp . Upon hitting the /signup method with an existing email, I can see the "Email already exists" log message on the login page thus returned, but the message "Please Enter Email" stays. Can someone figure out the reason. Is it possible that the login.jsp is compiled only once and gets cached somewhere when I call it for the first time, and what I am seeing as a result of hitting /signup is the cached page. If so, how can I get around this.
The html of the login page that appears after hitting the signup() method is:
<html style="background-image:url('/cct/resources/images/wallpaper.jpg')">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="/cct/resources/css/master.css" type="text/css" media="screen" />
<script type="text/javascript" src="/cct/resources/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/cct/resources/js/login.js"></script>
<title>BiliTutor Content Creator Toolkit</title>
</head>
<body>
<h3> emailErrorMessage = Please enter Email</h3>
<form id="mainForm" action="/cct/" method="post">
<table id="mainTable" class="contents roundBox">
<tr id="logoRow"><td colspan="2" style="text-align:center;padding:20px;width:300px;height:100px"><img id="imgLogo" src="/cct/resources/images/logo.png"></td></tr>
<tr id="emailRow"><td rowspan="2" class="lrPadding">Email </td><td class="lrPadding"><input id="email" name="email" class="editable" type="text" value=""/></td></tr>
<tr id="emailErrorRow"><td id="emailError" class="errorMessage">Please enter Email</td></tr>
<tr id="passwordRow"><td rowspan="2" class="lrPadding">Password</td><td class="lrPadding"><input id="password" name="password" class="editable" type="password" value=""/></td></tr>
<tr id="passwordErrorRow"><td id="passwordError" class="errorMessage">Password should be atleast 8 char long</td></tr>
<tr id="confirmPasswordRow"><td rowspan="2" class="lrPadding">Confirm<br/>Password</td><td class="lrPadding"><input id="confirmPassword" type="password" class="editable"/></td></tr>
<tr id="confirmPasswordErrorRow"><td id="confirmPasswordError" class="errorMessage">Passwords dont match</td></tr>
<tr id="accessCodeRow"><td rowspan="2" class="lrPadding">Access<br/>Code</td><td class="lrPadding"><input id="accessCode" name="accessCode" class="editable" type="text" value=""/></td></tr>
<tr id="accessCodeErrorRow"><td id="accessCodeError" class="errorMessage">Access Code must be atleast 8 char long</td></tr>
<tr id="buttonsRow"><td colspan="2"><table style="margin:0px;margin-top:1em;padding:0px;width:100%"><tr>
<td><div id="btnNewUser" class="button" style="float:left">New Tutor<br/>Signup</div></td>
<td><div id="btnForgotPassword" class="button">Forgot<br/>Password</div></td>
<td><div id="btnLogin" class="button" style="float:right">Tutor<br/>Login</div></td>
</tr></table></td></tr>
</table>
</form>
</body>
</html>
and my IDE looks like:
I would change the method signature to
public String signup(ModelMap model, #ModelAttribute("user")User user, BindingResult result) {
add your error directly to the model
} catch (DataIntegrityViolationException e) {
logger.info("Email already exists");
model.addAttribute("emailErrorMessage", "Email already exists");
}
return "login";
and then access it like so in the jsp
<tr id="emailErrorRow"><td id="emailError" class="errorMessage">${emailErrorMessage}</td></tr>
I would recommend to use BindingResult result instead of an own error map:
bindingResult.rejectValue("email", "errorMessageCode", "Email already exists");

Prepopulate form in Struts1

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.

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"/>