Struts 2 If-Else-If - java

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

Related

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.

Is it possible to output a drop-down list with values from DB in an easier way?

This way is not greatest. I'm looking for a better way. Is it possible to do without Lists?
My PageController:
public class CreateUserPageController {
#Autowired
private UserServiceImpl userServiceImpl;
#RequestMapping(value = "/create-user", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("admin/create-user");
model.addObject("user", new User());
UserRoleDTO[] roles = UserRoleDTO.values();
List<String> roleNames = new ArrayList<>();
for (UserRoleDTO role : roles) {
roleNames.add(role.getName());
}
model.addObject("roleNames", roleNames);
return model;
}
#RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView submitForm(#ModelAttribute("user") User user) {
userServiceImpl.create(user);
return showForm();
}
}
My JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Create test</title>
</head>
<body>
<h1>Create Test</h1>
<form:form method="POST" action="/create-test" modelAttribute="topicTestDTO">
<form:input path="topic.name" type="text" list="topic_list" placeholder="choose or create topic"/>
<datalist id="topic_list">
<c:forEach items="${topicList}" var="topic">
<option>${topic}</option>
</c:forEach>
</datalist>
<br>
<form:input path="test.name" type="text" placeholder="create test name"/>
<input type="submit">
</form:form>
</body>
</html>
Thanks for help.
If you need more information, tell me which one and I'll complete the code.
Here the problem is for every request it goes to Database to retrieve the data, even data is not changing also it reduces the performance of application.
By using local cache we can achieve performance, so while application loading it self data will be queried from database and store it in cache,then we can reuse the data from cache.

Struts 2 ajax-plugin: updating div

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.

Struts 2 Select tag error

I am new to Struts2. I want to compare JSTL's c tag and Struts2 s tag which one is easy to use... My code as below
ListDepartmentNameAction.java
package actions;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.mapping.Array;
import com.opensymphony.xwork2.ActionSupport;
import service.ListDepNameService;
public class ListDepartmentNameAction extends ActionSupport{
private static Logger log = Logger.getLogger(ListDepartmentNameAction.class);
ListDepNameService listDepNameService;
private List<String> allDNlist ;
public String execute() {
allDNlist = listDepNameService.ListAllDepName();
for (String ss : allDNlist) {
System.out.println(ss);
}
log.info(allDNlist);
return "success";
}
public ListDepNameService getListDepNameService() {
return listDepNameService;
}
public void setListDepNameService(ListDepNameService listDepNameService) {
this.listDepNameService = listDepNameService;
}
public List<String> getAllDNlist() {
return allDNlist;
}
public void setAllDNlist(List<String> allDNlist) {
this.allDNlist = allDNlist;
}
}
query.jsp
<%# page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<s:head />
<h1 align="center" id="h1"></h1>
<body>
<s:form action="listDepName" id="form" method="post">
<input name="Button" type="submit" id="listsubmit" value="List all Department Name"
onclick="javascirpt:abc(this)"/>
</s:form>
<select>
<c:forEach items="${allDNlist}" var="item">
<option value="abc" >${item}</option>
</c:forEach>
</select>
<s:if test="%{allDNlist==null}">456</s:if>
<s:else><s:select name="xxx" list="allDNlist" /></s:else> <!-- 1st -->
<s:select name="xyz" list="allDNlist" /> <!-- 2nd -->
</body>
</html>
"allDNlist" can get value from action class,therefore, JSTL c tag work properly.
I don't understand why the "1st" struts2 select tag work fine, but "2nd" select s tag doesn't work, and got message like this
HTTP Status 500 - tag 'select', field 'list', name 'xyz': The requested list key 'allDNlist' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
even I comment() the "2nd" select s tag, I still got same error message as above, only remove it.
EDIT:
I reproduced your whole code and it is perfectly working.
Note that you don't close </head> tag, i reproduced that too and it works the same...
It should be
<head>
<s:head/>
</head>
You should declare your ListDepNameService listDepNameService; as private too (you already have the accessors), and check what type of List is returned.
I tested the code with
allDNlist = new ArrayList<String>();
allDNlist.add("Valore 1 ");
allDNlist.add("Valore 2 ");
allDNlist.add("Valore 3 ");
in execute() method, this is the only difference.
Please try this instead the service call, and let me know...
I had the similar type of collection error while populating the drop down with <s:select: tag. after research i figured out that "i did not initialize my instance variable List" in your case make private List<String> allDNlist = new ArrayList<String>(); should solve the problem.

Displaying tree on JSP page

I need to display tree on JSP page. How can I do that? I have following object:
public class Node {
private Long id;
private Long parentId;
private String name;
private List<Node> children;
// Getters & setters
}
Roll your own with jsp recursion
In Controller.java
Node root = getTreeRootNode();
request.setAttribute("node", root);
In main.jsp page
<jsp:include page="node.jsp"/>
In node.jsp
<c:forEach var="node" items="${node.children}">
<!-- TODO: print the node here -->
<c:set var="node" value="${node}" scope="request"/>
<jsp:include page="node.jsp"/>
</c:forEach>
Based on http://web.archive.org/web/20130509135219/http://blog.boyandi.net/2007/11/21/jsp-recursion/
You may want to try http://www.soft82.com/download/windows/tree4jsp/
It is also downloadable from http://www.einnovates.com/jsptools/tree4jsp/tree4jsp_v1.2.zip
Jsp tree Project can help you.
I'd recommend you to use one of the available tag libraries.
For example:
http://beehive.apache.org/docs/1.0/netui/tagsTree.html
The following discussion can help too.
http://www.jguru.com/faq/view.jsp?EID=46659
Just check this JSP tree. It is simple and has minimum Java Scripts. I used velocity templates and JSP Tag class.
simple JSP tree
Compilation from the other answers. Tested.
Recursion on JSP tags
Unit.java
public class Unit {
private String name;
private HashSet<Unit> units;
// getters && setters
}
Employees.java
public class Employees {
private HashSet<Unit> units;
// getters && setters
}
Application.java
...
request.setAttribute("employees", employees);
request.getRequestDispatcher("EmployeeList.jsp").forward(request, response);
...
EmployeeList.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
<ul>
<c:forEach var="unit" items="${employees.getUnits()}">
<li>
<c:set var="unit" value="${unit}" scope="request"/>
<jsp:include page="Unit.jsp"/>
</li>
</c:forEach>
</ul>
</body>
<html>
Unit.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<span>${unit.getName()}</span>
...
<ul>
<c:forEach var="innerUnit" items="${unit.getUnits()}">
<li>
<c:set var="unit" value="${innerUnit}" scope="request"/>
<jsp:include page="Unit.jsp"/>
</li>
</c:forEach>
</ul>

Categories

Resources