Struts 2 ajax-plugin: updating div - java

Acсording to this question
I tried use of ajax-plugin for updating div. However, this example does not work as it should, it outputs nothing.
What is missing this time?
So, what we have.
page:
<div id="div1">
<!-- ajax result ? -->
<div>
<s:iterator value="<s:property value='data1'/>">
<s:property />
<br />
</s:iterator>
</div>
</div>
<div>
<s:url id="ajaxData" value="/AjaxData.action"/>
<sj:a id="link1" href="%{ajaxData}" targets="div1">
Update Content
</sj:a>
</div>
struts.xml:
<action name="AjaxData" class="com.data.action.AjaxDataAction">
<result name="success">/ajaxdata.jsp</result>
</action>
action:
public class AjaxDataAction extends ActionSupport {
private List<String> data1;
public String execute() {
RandData data = new RandData();
data1 = data.getData();
return SUCCESS;
}
public List<String> getData1() {
return data1;
}
public void setData1(List<String> data1) {
this.data1 = data1;
}
}
and ajaxdata.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<div>
<s:iterator value="<s:property value='data1'/>">
<s:property />
<br />
</s:iterator>
</div>
Update: execute() method does not starting.

Related

Include the record in same JSP returned from controller. If record is there then show the record as a table or give a message

Include the record in the same JSP returned from the controller. If any record is there then show the record as a table or give a message
I have done it on two different JSP pages. I need to do it on a single page. I need to update the controller as I am only allowed to return the same jsp.mappings
#Controller
public class EmpController {
#Autowired
EmpDao dao;
#PostMapping("/viewemp")
public String viewemp(#RequestParam(value="start") #DateTimeFormat(pattern="yyyy-MM-dd") Date start,
#RequestParam(value="end") #DateTimeFormat(pattern="yyyy-MM-dd") Date end, Model m){
List<Event> list=dao.getEmployees(start,end);
if(list.size()==0) return "index";
m.addAttribute("list",list);
return "viewemp";
}
}
jsp1:
<center>
<h1> Search Event</h1>
<form method="post" action="viewemp">
Start Date: <input type="date" id="start" name="start"/>
End Date: <input type="date" id="end" name="end"/>
<input type="submit" value="find" />
</form></center>
jsp2:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Event List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>eventName</th><th>eventOrgName</th><th>eventFare</th><th>startDate</th><th>endDate</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.eventName}</td>
<td>${emp.eventOrgName}</td>
<td>${emp.eventFare}</td>
<td>${emp.startDate}</td>
<td>${emp.endDate}</td>
</tr>
</c:forEach>
</table>
<br/>
I need to add jsp2 inside jsp1 if it has any record. like this image

Error messages not showing upon validating form

So i have to make this app where you have a list of birdspecies and you can add new ones to the list. This form needs to have some validation but for some reason the error messages aren't showing up. Also, when you enter all the input correctly, everything works perfect but when you enter wrong input, it should just show the same page again, but it returns a whitelabel error instead.
here is my modelclass with the validation:
public class BirdSpecie {
#NotEmpty(message="This input may not be empty")
private String name;
#NotNull(message="This input may not be empty")
#DecimalMin(value="1250", message="The earliest year of discovery allowed is 1250")
private Integer yearOfDiscovery;
#NotEmpty(message="This input may not be empty")
#Pattern(regexp= "^[A-Z]{1,2}[0-9]{3}$", message="Code should start with one or more capital letters [A-Z] followed by 3 digits")
private String code;
Here is my controller method:
#PostMapping(value="/{locationName}/addBirdSpecie")
public String onSubmit (
#PathVariable("locationName")String locationName,
#Valid #ModelAttribute("spottedBirdSpecie") BirdSpecie birdSpecie,
Model model, BindingResult result)
{
model.addAttribute("spottedBirdSpecie", birdSpecie);
BirdSpotLocation birdSpotLocation = spottedBirdService.findByName(locationName).get();
yearValidation.validate(birdSpecie,result);
if(result.hasErrors()) {
return "addSpecie";
}else {
birdSpotLocation.increaseBirdSpot(birdSpecie);
model.addAttribute("location", birdSpotLocation);
return "birdsList";
}
}
and here is my jsp file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib prefix = "form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<spring:url value="/css/style.css" var="urlCss"/>
<link rel="stylesheet" href="${urlCss}" type="text/css" />
<title>Create a new bird Specie</title>
</head>
<body>
<h1>Create new bird specie: </h1>
<form:form method="post" action="addBirdSpecie" modelAttribute="spottedBirdSpecie">
<spring:url value="/birdspotting/" var="showLocation" />
<div>
<p>
Specie: <form:input path="name" size="25"/><br>
<form:errors path="name" cssClass="error"/>
</p>
<p>
Year of discovery: <form:input path="yearOfDiscovery" size="25"/><br>
<form:errors path="yearOfDiscovery" cssClass="error"/>
</p>
<p>
Books of birds code: <form:input path="code" size="25"/><br>
<form:errors path="code" cssClass="error"/>
</p>
<input type="submit" value="Spot new bird"/>
</div>
</form:form>
</body>
</html>
the error messages are showing correctly in my console, but they won't show up on the website.

Java Spring dropdown populating

I am working in spring mvc, I am doing some jsp with showing multiple dropdowns in a single pages....
I seen an example to show drop down from database by using the following example.
<%# page import="java.util.*" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="state" scope="session" class="src.StateDAO"/>
<html>
<head>
<title></title>
</head>
<body>
<form id="test" method="POST" action="">
<input name="state" type="radio" value="Australia" id="state-aus">Australia
<input name="state" type="radio" value="NewZealand" id="state-new">NewZealand
<input name="state" type="radio" value="India" id="state-oth" >India
<Select name="othStates" size="1" id="oth-states">
<c:forEach items="${state.stateList}" var="st">
<option value="1"><c:out value="${st.name}"/></option>
</c:forEach>
</select>
<br>
<input type="Submit" name="cmdSub" value="SUBMIT">
<input type="Reset" name="cmdReset" value="RESET">
</form>
</body>
</html>
Is this right way to do this to get dropdowns in jsp using Spring mvc?
I think that a better option is to use the spring tags for jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
...
<form:select path="country">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${countryList}" />
</form:select>
See full example here: http://www.mkyong.com/spring-mvc/spring-mvc-dropdown-box-example/
Edit:
$('#stateSelect').change(function() {
$.ajax({
type:"GET",
url : "/getCitiesForState",
data : { state: $('#stateSelect').val()},
success : function(data) {
$('#citySelect').empty(); //remove all child nodes
for(var i = 0; i < data.length; i++){
var newOption = $('<option value=data[i].value>data[i].text</option>');
$('#citySelect').append(newOption);
}
},
error: function() {
alert('Error occured');
}
});
});
On the server side you need an endpoint that respondes on the url(/getCitiesForState in the example) and returns a list of objects that have value and text properties.
Edit(add controlelr):
#Controller
public class HelloController{
#RequestMapping("/getCitiesForState")
#ResponseBody
public List<City> printHello(#RequestParam long state) {
List<City> cities = //get from the some repository by state
return cities;
}
}
public class City{
private String value;
private String text;
//getters setters
}

Struts 2 If-Else-If

I have set an attribute in session in the UserAction class that will be retrieved in a JSP. The retrieved attribute from the session will control how the page will be displayed. The intention is to make certain portions of the JSP turn on/off depending on the type of user (0 = guest, 1 = admin, 2 = user) after logging in.
Action Class:
public class UserAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private Map<String, Object> session;
private String userId;
private String userPassword;
private String userEmail;
private int userType;
private Date registeredDate;
#Override
public String execute() {
UserManager um = new UserManager();
String registeredPassword = um.getCurrentUserDetail("user_password",
getUserId());
if (getUserPassword().equals(registeredPassword)) {
String currentUserId = um.getCurrentUserDetail("user_id", userId);
int currentUserType = um.getCurrentUserType(userId);
session.put("currentUserId", (String) currentUserId);
session.put("currentUserType", (Integer) currentUserType);
System.out.println("You have successfully logged in!");
return SUCCESS;
}
System.out.println("Your login has failed!");
return ERROR;
}
#Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
// getters and setters
}
index.jsp:
<%# taglib prefix="s" uri="/struts-tags"%>
<%# page import="com.mypackage.model.UserAction"%>
<html>
<head>
<title>My Site - Home</title>
<%# include file="css/style.css"%>
<%# include file="css/style2.css"%>
<s:set var="type" value="0" />
<s:if test='#session.containsKey("currentUserType")'>
<s:set var="type" value='#session["currentUserType"]' />
</s:if>
</head>
<body>
<div id="wrapper">
<div id="inner">
<div id="header">
<s:if test="type==0">
<%# include file="templates/guest-header.jsp"%>
</s:if>
<s:else>
<%# include file="templates/logged-header.jsp"%>
</s:else>
</div>
<dl id="browse">
<s:if test="type==1 || type==2">
<%# include file="templates/logged-acct.jsp"%>
</s:if>
<dt>NAVIGATE WEBSITE</dt>
<s:if test="type==0">
<%# include file="templates/guest-nav.jsp"%>
</s:if>
<s:elseif test="type==1">
<%# include file="templates/admin-nav.jsp"%>
</s:elseif>
<s:elseif test="type==2">
<%# include file="templates/user-nav.jsp"%>
</s:elseif>
<dt>SEARCH MOVIE</dt>
<dd class="searchform">
<%# include file="templates/search-box.jsp"%>
</dd>
</dl>
<div id="body">
<div class="inner">
<%# include file="templates/content.jsp"%>
</div>
<!-- end .inner -->
</div>
<!-- end body -->
<div class="clear"></div>
<%# include file="templates/copyright.jsp"%>
</div>
<!-- end inner -->
</div>
<!-- end wrapper -->
<%# include file="templates/footer.jsp"%>
</body>
</html>
However, it does not seem to enter any of the if-conditions. At the very least, I believe the guest view should be displaying, since type has been initially set to 0 by <s:set var="type" value="0" />.
(Kindly forgive the design for now, I have been made aware there is an elegant approach with this using <s:include> instead of <%# include %>, but I am only beginning Struts 2. I often make improvements/optimizations after I make it work.)
You've forgot the pound sign # in your testing.
It should be like this.
<s:if test="#type==0">
<%# include file="templates/guest-header.jsp"%>
</s:if>
<s:else>
<%# include file="templates/logged-header.jsp"%>
</s:else>
Reference on how to access a variable in struts

Struts2 - getting 404 Resource Unavailable error from request page

I'm trying to write a login example that takes the user to a success.jsp if username equals password and an error message if it doesn't. The error message works but success (username=password) results in a 404 (HTTP Status 404 - /Struts2Ch4/success.jsp)
I experienced a similar problem in a previous post. I had not declared the RESULT parameter in the class. I was advised to use annotations in the class file and this solved the problem. In this case both the success and result parameters seem to be declared by the class so I'm not sure why I'm getting 404.
alias.jsp
<%# page language="java" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<table align="center" width="300">
<tr>
<td colspan="2"><s:actionerror/></td>
</tr>
<tr><td align="center" colspan="2">Enter Login ID and Password</td></tr>
<tr><td align="center">
<s:form action="aliasing" method="post">
<s:textfield name="uname" key="app.loginid"/>
<s:password name="pwd" key="app.password"/>
<s:submit value="Enter"/>
</s:form>
</td>
</tr>
<tr><td align="center" colspan="2">
B a c k</td>
</tr>
</table>
</body>
</html>
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="exception"/>
</global-exception-mappings>
<action name="aliasing" class="com.manaar.action.AliasAction">
<param name="aliases">#{ 'uname' : 'loginid','pwd' : 'password' }</param>
<interceptor-ref name="alias"/>
<interceptor-ref name="basicStack"/>
<result name="success">/success.jsp</result>
<result name="error">/alias.jsp</result>
<result name="input">/alias.jsp</result>
</action>
</package>
</struts>
AliasAction.java
package com.manaar.action;
import com.opensymphony.xwork2.ActionSupport;
public class AliasAction extends ActionSupport {
private String loginid;
private String password;
public String getLoginid() {
return loginid;
}
public void setLoginid(String loginid) {
this.loginid = loginid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute() throws Exception {
System.out.println("Login Id: "+getLoginid());
System.out.println("Password: "+getPassword());
if(loginid.equals(password))
return SUCCESS;
else{
this.addActionError(getText("app.invalid"));
return ERROR;
}
}
}
success.jsp
<%# page language="java" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head><title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<div align="center">
<h1><s:text name="app.success"/></h1>
The action has returned SUCCESS as result code.<br><br>
Back to Index</div>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org /2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com /xml/ns/javaee http://java.sun.com/xml/ns/javaee /web-app_3_0.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
<%# page language="java" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"/>
<html>
<head><title><s:text name="app.title"/></title>
<link rel="stylesheet" href="mystyle.css" type="text/css" />
</head>
<body>
<table align="center" width=400>
<tr><td><h2>Sruts 2 Interceptors</h2></td></tr>
<tr><td><s:a href="alias.jsp">Interceptor Example 1</s:a></td></tr>
<tr><td>alias, basicStack </td></tr>
<tr><td> </td></tr>
<tr><td><s:a href="model.jsp">Interceptor Example 2</s:a></td></tr>
<tr><td>
exception, prepare, debugging, model-driven, params, conversionError, workflow
</td></tr>
<tr><td> </td></tr>
<tr><td>
<s:a href="servletAction.action">Interceptor Example 3</s:a>
</td></tr>
<tr><td>servlet-config, scoped-model-driven </td></tr>
<tr><td> </td></tr>
<tr><td><s:a href="longAction.action">Interceptor Example 4</s:a></td></tr>
<tr><td>completeStack, execAndWait</td></tr>
<tr><td> </td></tr>
<tr><td><s:a href="login.jsp">Interceptor Example 5</s:a> </td></tr>
<tr><td>basicStack, validation, workflow, scope </td></tr>
</table>
</body>
</html>

Categories

Resources