Send attribute in Struts 2 Action class - java

I have a screen which contains dojo sx:div. The action class who manage the loading of the div is different that the principal. but when i click on my link i would like refresh the sx:div with parameter input in the main form. How can I do that ?
JSP File :
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sx" uri="/struts-dojo-tags"%>
<script language="javascript">
function refreshDiv() {
var td = element.parentNode;
document.getElementById('idSubFamily').value = td.getAttribute('id');
dojo.event.topic.publish("/listQuestionTopic", "0", "1");
}
</script>
<table class="board" width="100%">
<tr class="titre">
<td class="titleFamily" width="30%" height="32"><s:property
value="getText('resultat.sous_famille.question.label')" /></td>
<s:if test="%{displayWeight}">
<td class="titleFamily" width="30%" height="32"><s:property
value="getText('question.weight.label')" /></td>
</s:if>
</tr>
<s:if test="%{subFamilyItem.size != 0}">
<s:iterator value="subFamilyItem" status="rowstatus">
<s:if test="#rowstatus.odd == true">
<s:set name="trClass" value="%{'even'}"></s:set>
</s:if>
<s:else>
<s:set name="trClass" value="%{'odd'}"></s:set>
</s:else>
<tr class="<s:property value="#trClass"/>">
<td class="family_<s:property value="#trClass"/>"><s:a
cssClass="board" onclick="refreshDiv()">
<s:property value="%{getText(traductionCode)}" />
</s:a></td>
<s:if test="%{displayWeight}">
<td class="family_<s:property value="#trClass"/>"><s:property
value="%{weight}" /></td>
</s:if>
</tr>
</s:iterator>
</s:if>
</table>
<sx:div id="listQuestions" href="Question.do" formId="idFormQuestion"
listenTopics="/listQuestionTopic" theme="ajax" preload="false">
<s:hidden id="idFamily" name="idFamilySelected"></s:hidden>
</sx:div>
PrinciaplAction class :
package com.omb.controller;
import java.util.ArrayList;
import java.util.List;
import com.omb.ui.SubFamilyItem;
import com.opensymphony.xwork2.ActionSupport;
public class PrincipalAction extends ActionSupport {
private List<SubFamilyItem> subFamilyItem = new ArrayList<SubFamilyItem>();
#Override
public String execute() throws Exception {
subFamilyItem.add(new Item("1", "Family 1"));
subFamilyItem.add(new Item("2", "Family 2"));
return SUCCESS;
}
public List<Item> getSubFamilyItem() {
return this.subFamilyItem;
}
public void setSubFamilyItem(List<Item> subFamilyItem) {
this.subFamilyItem = subFamilyItem;
}
}
DivAction class :
package com.omb.controller;
import com.opensymphony.xwork2.ActionSupport;
public class DivAction extends ActionSupport {
Service myService;
// From the principal screen
Long idFamilySelected;
/**
*
* #see com.opensymphony.xwork2.ActionSupport#execute()
*/
public String execute() {
MyObject object = myService.findObject(idFamilySelected);
return SUCCESS;
}
public String getMyService() {
return this.subFamilySelected;
}
public void setMyService(Service myService) {
this.myService = myService;
}
public String getidFamilySelected() {
return this.idFamilySelected;
}
public void setidFamilySelected(Service idFamilySelected) {
this.idFamilySelected = idFamilySelected;
}
}

Related

PropertyEditor does not pass the default data

I have created some form with spring mvc Framework but I am facing Problem when clicking the submit button, the studentName is not being bound with the other data in the AdmissionSuccess.jsp file. I do not know what I am doing wrong in the StudentNameEditor class. The setAsText method is being called but the value of studentName is not being rendered in the AdmissionSuccess.jsp.
How can I get it to work?
StudentAdmissionController
package com.stack;
import java.sql.Date;
import java.text.SimpleDateFormat;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class StudentAdmissionController {
#InitBinder
public void iniBinder(WebDataBinder binder){
//binder.setDisallowedFields(new String[] {"studentMobile"});
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
binder.registerCustomEditor(Date.class, "studentDOB", new CustomDateEditor(dateFormat, false));
//add to handle a specific data.
binder.registerCustomEditor(String.class,"studentName", new StudentNameEditor());
}
#RequestMapping(value = "/admission.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
// Aded
// This method is being called by every request.
#ModelAttribute
public void addingCommonObjects(Model model1) {
model1.addAttribute("headerMessage", "University of Lübeck, Germany ");
}
#RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(#ModelAttribute("student1") Student student1, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
ModelAndView model = new ModelAndView("AdmissionSuccess");
return model;
}
}
StudentNameEditor class
package com.stack;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
public class StudentNameEditor implements PropertyEditor {
/*
* (non-Javadoc) when you will submit the admission form, Spring mvc will run
* serAsText function this class before performing data binding task for
* studentName property of student.
*/
#Override
public void setAsText(String studentName) throws IllegalArgumentException {
if(studentName.contains("Mr.") || studentName.contains("Ms.")){
setValue(studentName);
}else{
studentName = "Ms." + studentName;
setValue(studentName);
}
}
#Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
// TODO Auto-generated method stub
}
#Override
public String getAsText() {
// TODO Auto-generated method stub
return null;
}
#Override
public Component getCustomEditor() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getJavaInitializationString() {
// TODO Auto-generated method stub
return null;
}
#Override
public String[] getTags() {
// TODO Auto-generated method stub
return null;
}
#Override
public Object getValue() {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean isPaintable() {
// TODO Auto-generated method stub
return false;
}
#Override
public void paintValue(Graphics gfx, Rectangle box) {
// TODO Auto-generated method stub
}
#Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
// TODO Auto-generated method stub
}
#Override
public void setValue(Object value) {
// TODO Auto-generated method stub
}
#Override
public boolean supportsCustomEditor() {
// TODO Auto-generated method stub
return false;
}
}
AdmissionForm.jsp
<!-- Added -->
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<body>
<h1>${headerMessage}</h1>
<h1>Student admission form for Engineeering courses</h1>
<!-- Added -->
<form:errors path="student1.*" />
<form action="/FirstSpringMVCProject/submitAdmissionForm.html"
method="post">
<table>
<tr>
<td>Student's Name:</td>
<td><input type="text" name="studentName" /></td>
</tr>
<tr>
<td>Student's Hobby:</td>
<td><input type="text" name="studentHobby" /></td>
</tr>
<tr>
<td>Student's Mobile:</td>
<td><input type="text" name="studentMobile" /></td>
</tr>
<tr>
<td>Student's DOB:</td>
<td><input type="text" name="studentDOB" /></td>
</tr>
<tr>
<td>Student's Skill set:</td>
<td><select name="studentSkills" multiple>
<option value="Java Core">Java Core</option>
<option value="Spring Core">Spring Core</option>
<option value="Spring MVC">Spring MVC</option>
</select></td>
</tr>
</table>
<table>
<tr>
<td>Student's Address:</td>
</tr>
<tr>
<td>county: <input type="text" name="studentAddress.country" />
</td>
<td>city: <input type="text" name="studentAddress.city" />
</td>
<td>street: <input type="text" name="studentAddress.street" />
</td>
<td>pincode: <input type="text" name="studentAddress.pincode" />
</td>
</tr>
</table>
<input type="submit" value="Submit this form by clicking here" />
</form>
</body>
</html>
AdmissionSuccess.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>
<h1>${headerMessage}</h1>
<h3>STUDENT ADMISSION FROM ENGINEERING COURSES</h3>
<h2>Detials submitted by you::</h2>
<table>
<tr>
<td>Student Name:</td>
<td>${student1.studentName}</td>
</tr>
<tr>
<td>Student Hobby:</td>
<td>${student1.studentHobby}</td>
</tr>
<tr>
<td>Student Mobile:</td>
<td>${student1.studentMobile}</td>
</tr>
<tr>
<td>Student DOB:</td>
<td>${student1.studentDOB}</td>
</tr>
<tr>
<td>Student skills:</td>
<td>${student1.studentSkills}</td>
</tr>
<tr>
<td>Student Adress:</td>
<td>${student1.studentAddress.country}
${student1.studentAddress.city}
${student1.studentAddress.street}
${student1.studentAddress.pincode}</td>
</tr>
</table>
<body>
</body>
</html>
so I had StudentNameEditor implements PropertyEditor and it must be StudentNameEditor extends PropertyEditorSupport. With the code below it works fine.
package com.stack;
import java.beans.PropertyEditorSupport;
public class StudentNameEditor extends PropertyEditorSupport {
/*
* (non-Javadoc) when you will submit the admission form, Spring mvc will run
* serAsText function this class before performing data binding task for
* studentName property of student.
*/
#Override
public void setAsText(String studentName) throws IllegalArgumentException {
if(studentName.contains("Mr.") || studentName.contains("Ms.")){
setValue(studentName);
}else{
studentName = "Ms." + studentName;
setValue(studentName);
}
}
}

how to bind data to list in spring form

I have a spring form with having backing object for it. The form is like this-
<sf:form cssClass="form-horizontal" commandName="campaignModel" method="post">
<sf:input path="campaign.name" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
</sf:form>
Model class(Form backing Object) -
CampaignModel.java
public class CampaignModel {
private Campaign campaign = new CampaignImpl();
private List<LandingPageModel> landingPageModels = new Arraylist<LandingPageModel>;
public Campaign getCampaign() {
return campaign;
}
public void setCampaign(Campaign campaign) {
this.campaign = campaign;
}
public List<LandingPageModel> getLandingPageModels() {
return landingPageModels;
}
public void setLandingPageModels(List<LandingPageModel> landingPageModels) {
this.landingPageModels = landingPageModels;
}
LandingPageModel.java is -
public class LandingPageModel {
private LandingPage landingPage = new LandingPageImpl();
private List<LandingPageParameterImpl> landingPageParameters = new ArrayList<LandingPageParameterImpl>();
public LandingPage getLandingPage() {
return landingPage;
}
public void setLandingPage(LandingPage landingPage) {
this.landingPage = landingPage;
}
public List<LandingPageParameterImpl> getLandingPageParameters() {
return landingPageParameters;
}
public void setLandingPageParameters(List<LandingPageParameterImpl> landingPageParameters) {
this.landingPageParameters = landingPageParameters;
}
}
LandingPage.java is -
public class LandingPageImpl extends EntityImpl implements LandingPage {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} }
So i want that i can insert many objects of landingPage (having their own url property) in landingPageModels list. That means i can have mulitple input tag having url property like this -
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
<sf:input path="landingPageModels.landingPage.url" class="form-control" />
But when executing this code, spring gives me error that landingPage property of landingPageModels has not getter setter method. How to solve it and how to take multiple value like this ?
In order to bind a list model property to multiple input fields, you need this in the rendered form:
<input type="text" name="landingPageModels[0].landingPage.url" class="form-control" />
<input type="text" name="landingPageModels[1].landingPage.url" class="form-control" />
<input type="text" name="landingPageModels[2].landingPage.url" class="form-control" />
Which is accomplished by:
<c:forEach items="${campaignModel.landingPageModels}" varStatus="s">
<sf:input path="landingPageModels[${s.index}].landingPage.url" class="form-control" />
</c:forEach>
The error you are getting is correct as landingPageModels is a list.
You would need to use index access like this landingPageModels[0].landingPage.url.
If you have dynamic number of input/url, then you can use <c:forEach> to create dynamic input variable names
<c:forEach items="${campaignModel.landingPageModels}" var="landingPage">
<sf:input path="landingPage.url" class="form- control" />
</c:forEach>
Will the above not works for you to view data? To get them in controller you may have to use dynamic table row concept in HTML or for each single LandingPage entry add to form bean object by clicking add button and render back.
In my case Person command object having List<Token> property, in order to bind the list of tokens we have designed page as attached screen shot below, clicking on Add button hits the controller and add the each token List<Token> and render back to same view and displays added token in list view, it facilitates to add multiple token for Person.
I dont know how to do it with spring form lib input but if you want to bind using simple html input than you can bind list like this
Simple.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>
<head>
</head>
<body>
<form:form method="post" action="save.html" modelAttribute="contactForm">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr>
<td><input name="contacts[0].firstname" /></td>
<td><input name="contacts[0].lastname" /></td>
</tr>
<tr>
<td><input name="contacts[1].firstname" /></td>
<td><input name="contacts[1].lastname" /></td>
</tr>
</table>
<br/>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
#controller :
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("contactForm") ContactForm contactForm) {
List<Contact> contacts = contactForm.getContacts();
if(null != contacts && contacts.size() > 0) {
ContactController.contacts = contacts;
for (Contact contact : contacts) {
System.out.printf("%s \t %s \n", contact.getFirstname(), contact.getLastname());
}
}
return new ModelAndView("show_contact", "contactForm", contactForm);
}
ContactForm.java
import java.util.List;
public class ContactForm {
private List<Contact> contacts;
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
}
Contact.java
public class Contact {
private String firstname;
private String lastname;
private String email;
private String phone;
public Contact() {
}
//getters and setters
}

Struts2 - How can I use <s:a> without previously knowing the action that I'll use?

I have to display several links in a JSP and the structure of the HTML is the equal for every link, so I've used an struts2 taglib iterator to build it. The problem is that I don't know how to build the link itself:
My JSP
<%# taglib prefix="s" uri="/struts-tags"%>
<head></head>
<div class="menuBotoes">
<s:iterator value="links" var="link">
<s:a namespace="link.nameSpace" action="link.action">
<table cellpadding="0" cellspacing="0" class="tableBotaoMenu">
<tr class="trCimaBotaoMenuSelect">
<td align="center" class="imagemBotaoMenuSelect"><img src="<s:url value="/includes/imagens/global/botoes/grafico.png" />" /></td>
<td align="left" class="descricaoBotaoMenuSelect"><s:property value="textoLink" /></td>
</tr>
<tr class="trBaixoBotaoMenuSelect">
<td align="center" class="imagemBotaoMenuSelect" colspan="2"><s:property value="projeto" /></td>
</tr>
</table>
</s:a>
</s:iterator>
</div>
The object that is being iterated over in the JSP is this:
public enum LinksRelatorios {
1("Caixa Visita", "/relatorios/", "iniciarRelatorioCaixaVisita", "TISS"),
2("Caixa Visita Empresa", "/relatorios/", "iniciarRelatorioCaixaVisitaEmpresa", "TISS"),
3("Produtividade Internação Domiciliar", "/relatorios/", "iniciarRelatorioInternacaoDomiciliar", "TISS"),
4("Pendências", "/relatorios/", "iniciarRelatorioPendencias", "TISS"),
5("Solicitação Inicial", "/relatorios/", "iniciarRelatorioSolicitacaoInicial", "TISS"),
6("Solicitação Prorrogação", "/relatorios/", "iniciarRelatorioSolicitacaoProrrogacao", "TISS"),
7("Tempo Resposta", "/relatorios/", "iniciarRelatorioTempoResposta", "TISS");
private String textoLink;
private String nameSpace;
private String action;
private String projeto;
private LinksRelatorios(final String textoLinkParam, final String nameSpaceParam, final String actionParam,
final String projetoParam) {
this.textoLink = textoLinkParam;
this.nameSpace = nameSpaceParam;
this.action = actionParam;
this.projeto = projetoParam;
}
public String getTextoLink() {
return this.textoLink;
}
public String getNameSpace() {
return this.nameSpace;
}
public String getAction() {
return this.action;
}
public String getProjeto() {
return this.projeto;
}
}
My Action
#Controller
#Scope("request")
public class InicioAction extends BaseAction {
private static final long serialVersionUID = -1161409943678292285L;
private static final LinksRelatorios[] links = LinksRelatorios.values();
public String inicio() {
this.addActionMessage(this.getText("msg.sucesso.saudacao.mensagem", new String[] { (String) BaseAction
.getSession().getAttribute(Constantes.PERFIL) }));
return Action.SUCCESS;
}
public String iniciarRelatoriosPorProjeto() {
return Action.SUCCESS;
}
public String iniciarRelatoriosFiltro() {
return Action.SUCCESS;
}
public static LinksRelatorios[] getLinks() {
return InicioAction.links;
}
}
I've tried using
<s:a namespace="link.nameSpace" action="link.action">, < s:a namespace="%{link.nameSpace}" action="%{link.action}">, <s:a namespace="#link.nameSpace" action="#link.action">, but not seems to work.
Before someone asks, the enum is working fine, in my JSP I have <s:property value="projeto" /> and <s:property value="textoLink" /> and these are properties that come from the enum.
I've read the online official docs in http://struts.apache.org/release/2.3.x/docs/using-struts-2-tags.html, http://struts.apache.org/release/2.3.x/docs/a.html and http://struts.apache.org/release/2.3.x/docs/url.html but the examples sections is actually pretty poor comparing to frameworks such as PrimeFaces or RichFaces that have built theirs own showcases.
Use the below code
<s:a namespace="%{#link.nameSpace}" action="%{#link.action}">
Use of %{} makes struts2 evaluate the contents of the expression inside {} and then assign the result to the attribute.
Refer http://struts.apache.org/release/2.0.x/docs/tag-syntax.html for more details.

Removing dynamically added row from table having struts2

i am quite new at this and i what to know how can i get a index row from a dynamical table created with struts2. Here is what i have tried so far:
test file
<table class="table table-bordered table-striped table-condensed table-hover"
id="exp">
<thead>
<tr>
<th class="center"></th>
<th>Name</th>
</tr>
</thead>
<tbody>
<s:if test="listanume.size>0">
<s:iterator value="listanume" status="statusVar">
<tr>
<td class="center">
<button class="btn" onclick="javascript:setval(0)">
delete
</button>
</td>
<td><s:property value="nume"/></td>
</tr>
</s:iterator>
</s:if>
</tbody>
</table>
<h4>Numarul randului este: <s:property value="mysample"/> </h4>
<script>
var mysample= '';
function= setval(varval){
mysample=varval;
alert(mysample);
}
</script>
pop java
public class Pop {
private int nrrow;
private List<UserModel> listanume = new ArrayList<UserModel>();
UserModel user = new UserModel(),
user1 = new UserModel(),
user2 = new UserModel();
private String[] sample;
{
sample = new String[]{"list1", "list2", "list3"};
}
public String execute() {
user.setEmail("eret#esre");
user.setPass1("1234");
user.setNume("gigel");
user1.setEmail("yuii#ihj");
user1.setPass1("6789");
user1.setNume("marius");
user2.setEmail("nmnn#cvx");
user2.setPass1("7676");
user2.setNume("sorin");
sample1.add(user);
sample1.add(user1);
sample1.add(user2);
return "succes";
}
public String afisnrow(){
execute();
listanume=sample1;
return "succes";
}
public String[] getSample() {
return sample;
}
public void setSample(String[] sample) {
this.sample = sample;
}
public List<UserModel> getSample1() {
return sample1;
}
public void setSample1(List<UserModel> sample1) {
this.sample1 = sample1;
}
public void setNrrow(int nrrow){
this.nrrow=nrrow;
}
public int getNrrow(){
return nrrow;
}
public List<UserModel> getListanume(){
return listanume;
}
public void setListanume(List<UserModel> listanume){
this.listanume=listanume;
}
}
every row has a button on it and when i click that button i need to get the row index, i kind of stuck and run out of ideas, any suggestions?
replace
onclick="javascript:setval(0)"
with
onclick="javascript:setval(<s:property value="#statusVar.index" />)"
more info on the struts2 iterator tag here.
The solution i have found is this:
test file
<table class="table table-bordered table-striped table-condensed table-hover"
id="exp">
<thead>
<tr>
<th class="center"></th>
<th>Name</th>
</tr>
</thead>
<tbody>
<s:if test="listanume.size>0">
<s:iterator value="listanume" status="statusVar">
<tr>
<td class="center">
<button class="btn" id="<s:property value='indexrow'/>">
delete
</button>
</td>
<td><s:property value="nume"/></td>
</tr>
</s:iterator>
</s:if>
</tbody>
</table>
<i><p id="test"> No button pressed.</p></i>
<script>
$("button").click(function(e){
var idClicked = e.target.id;
$("#test").html(idClicked);
});
</script>
pop java
public class Pop {
private int indexrow;
private List<UserModel> listanume = new ArrayList<UserModel>();
UserModel user = new UserModel(),
user1 = new UserModel(),
user2 = new UserModel();
public String execute() {
user.setEmail("eret#esre");
user.setPass1("1234");
user.setNume("gigel");
user1.setEmail("yuii#ihj");
user1.setPass1("6789");
user1.setNume("marius");
user2.setEmail("nmnn#cvx");
user2.setPass1("7676");
user2.setNume("sorin");
listanume.add(user);
listanume.add(user1);
listanume.add(user2);
return "succes";
}
public String afisnrow(){
execute();
for (UserModel userModel : listanume) {
UserModel userModel1=new UserModel();
indexrow++;
userModel1.setNume(userModel.getNume());
userModel1.setIndexrow(indexrow);
listanume.add(userModel1);
}
return "succes";
}
public List<UserModel> getListanume(){
return listanume;
}
public void setListanume(List<UserModel> listanume){
this.listanume=listanume;
}
}

completing read CRUD sql in jsp servlet

I asked this questions last night, and was kind of foolish not to ask how to complete the coding on it. I now have a dropdown box in a JSP populated with some data from an SQL database. I am trying to get the selected data to direct to the final viewing page, but again am running into some difficulty with this.
When I run the program, it either populates the page with all the data from the list database, or will give me an unfriendly error.
My current coding is as such:
the Bean:
package com.login.read;
public class ReadBean {
protected int id;
protected String title;
protected String author;
protected String text;
public int getId(){
return id;
}
public void setId(int newID){
id = newID;
}
public String getTitle(){
return title;
}
public void setTitle(String newTitle){
title = newTitle;
}
public String getAuthor(){
return author;
}
public void setAuthor(String newAuthor){
author = newAuthor;
}
public String getText(){
return text;
}
public void setText(String newText){
text = newText;
}
}
The Controller:
package com.login.read;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
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;
#WebServlet (urlPatterns={"/com/defaultValidate/ReadController"})
public class ReadController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String address;
List<ReadBean> myList = new ArrayList<ReadBean>();
if(request.getParameter("ReadConfirm") != null){
try {
Connection connect = ConnectionManager.getConnection();
String SQL = "SELECT * FROM prayers ORDER BY prayerTitle DESC";
PreparedStatement ps = connect.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();
while(rs.next()){
ReadBean reader = new ReadBean();
reader.setTitle(rs.getString("prayerTitle"));
reader.setAuthor(rs.getString("author"));
reader.setText(rs.getString("text"));
myList.add(reader);
}
request.getSession().setAttribute("ref", myList);
rs.close();
ps.close();
connect.close();
} catch (Exception e) {
}
address = "ReadConfirm.jsp";
} else if(request.getParameter("ReadView") != null){
address = "ReadView.jsp";
} else{
address = null;
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
And my jsp pages that link the drop-down box to the selected material:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<h2 id="contentHeader">Select a prayer</h2>
<form action="ReadController">
<table border="1" width="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="prayer_id">
<c:forEach var="view" items="${ref}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="ReadView" value="View"> </td>
</tr>
</tbody>
</table>
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
and the final viewing page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<c:forEach var="view" items="${res}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
<form action="../Read.jsp">
<p>Click on the return button to return to the main menu</p>
<input type="submit" name="return" value="Return">
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
As always, any and all assistance in this regard is incredibly helpful. I am a relative newbie to the world of jsp and servlets.
If one needs any reference as to the continuation of this sequence, kindly view the previous question I posted regarding dynamically displaying data in a jsp combo-box.
Thank you for your time and help.
By reading above code, I can just ask you that where you have stored your session attribute in variable "var", which is being used in c:foreach loop ?

Categories

Resources