Incorrect request from jsp form - java

When I try submit my form tomcat throw me "The request sent by the client was syntactically incorrect."
This is my jsp form. Please help me.
<form:form method="POST" commandName="articleDTO" id="categoryForm">
<form:errors path="*" />
<td>Title</td>
<td><form:input path="title" /></td>
<table>
<thead>
<tr>
<th>Category</th>
<th></th>
</tr>
</thead>
<c:forEach items="${articleDTO.categories}" var="Category"
varStatus="i" begin="0">
<td><form:select path="categories[${i.index}]">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${categoryList}" />
</form:select></td>
</c:forEach>
</table>
<td colspan="3"><input type="submit" value="GG" /></td>
</form:form>
Conroller:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView getAdminPage() {
return new ModelAndView("admin_page").addObject("categoryList",
categoryService.getAllCategories()).addObject("articleDTO", new ArticleDTO());
}
#RequestMapping(method = RequestMethod.POST)
public ModelAndView ondas(ArticleDTO articleDTO) {
return new ModelAndView("done").addObject("article", articleDTO);
}
DTO:
private String title;
#NotEmpty
#Range(min = 100, max = 6000)
private String description;
#NotEmpty
private List<Category> categories = new ArrayList<Category>();
public ArticleDTO() {
Category category = new Category();
category.setTitle("news");
category.setId(1L);
Category category1 = new Category();
category1.setTitle("news1");
category1.setId(2L);
categories.add(category1);
categories.add(category);
}
I'm try to get from user list of article categories

I'm almost sure your POST is having validation issues... :)
Try to change your method to something like this.
#RequestMapping(method = RequestMethod.POST)
public ModelAndView ondas(ArticleDTO articleDTO, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("admin_page").addObject("categoryList",
categoryService.getAllCategories()).addObject("articleDTO", new ArticleDTO());
}
return new ModelAndView("done").addObject("article", articleDTO);
}

Related

Java SpringBoot Postgres remove rows

Help me please to remove the row in Postgres by clicking the Del button.
Maybe to link id in DB and id on the HTML page, but how?
Maybe I need to parse the HTML page and pass String id?
Any ideas will help me.
here is my database schema:
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<th><form action="/remove" method="post">
<input type="submit" value="Del"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
</form>
</th>
</tr>
{{/messages}}
</tbody>
#Entity
#Table(name = "message")
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String text;
private String sn;
private String owner;
public Message() {
}
public Message(String text, String sn, String owner) {
this.text = text;
this.sn = sn;
this.owner = owner;
}
Rows are forming in database by:
#PostMapping("/main")
public String add (
#RequestParam String owner,
#RequestParam String text,
#RequestParam String sn, Map<String, Object> model) {
Message message = new Message (text, sn, owner);
if (text != null && !text.isEmpty() & sn != null && !sn.isEmpty() & owner != null &&
!owner.isEmpty()) {
if (!text.matches("^[0-9].*$")) {
messageRepo2.save(message);
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else
model.put("error", "ТМЦ не должно начинаться с цифры");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else {
model.put("error", "Заполните все поля!");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
}
return "main";
}
There are two issues with your html code:
it would be to let the form element outside the table
need to use <input type="hidden" name="xxx" value="{{xxx}}" /> in order to let it can pass parameter to your controller method
<form action="/remove" method="post">
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}} <input type="hidden" name="id" value="{{id}}" /></td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i> <input type="hidden" name="sn" value="{{sn}}" /></td>
<td><i>{{owner}}</i> <input type="hidden" name="owner" value="{{owner}}" /></td>
<td><input type="submit" value="Del"/></td>
</th>
</tr>
{{/messages}}
</tbody>
</table>
</form>
<thead>
<tr>
<th>ID ТМЦ</th><th>Наименование ТМЦ</th><th>Серийный номер ТМЦ</th><th>За кем числится</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<td>
<form action="/remove" method="post" name="remove">
<input type="submit" value="Удалить"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<input type="hidden" name="sn" value="{{sn}}"/>
</form>
</td>
</tr>
{{/messages}}
</tbody>
import com.example.webapp.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Transactional
public interface MessageDel extends CrudRepository<Message, Long>{
List<Message> deleteBySn (String sn);
}
#PostMapping("/remove")
public String remove (#RequestParam String sn, Map<String, Object> model) {
Message messagedel = new Message (sn);
messageDel.deleteBySn(sn);
model.put("messages", messagedel);
return "redirect:/main";
}

Spring MVC controller returning null modelAttribute when #Valid fails

I've been scratching my head for a long time on this one. I'm working on a web app that has over 20 controllers and i'm having this strange issue with only one of them. No matter how long I compare with a working one i cannot seem to find any differences. Basically, I am able to add an Interface entity no problem as long as it does not fail validation. If i try to save say a completely empty object (or leave one of the required fields blank for example) I get this error :
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'intface' available as request attribute
Here is the relevant code :
View :
<form:form method="POST" modelAttribute="intface" class="form-style-7">
<form:input type="hidden" path="id" id="id"/>
<table>
<tr>
<td><label for="name">Name: </label> </td>
<td><form:input path="name" id="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td><label for="type">Type: </label> </td>
<td><form:input path="type" id="type"/></td>
<td><form:errors path="type" cssClass="error"/></td>
</tr>
<tr>
<td><label for="ip">IP: </label> </td>
<td><form:input path="ip" id="ip"/></td>
<td><form:errors path="ip" cssClass="error"/></td>
</tr>
<tr>
<td><label for="port">Port: </label> </td>
<td><form:input path="port" id="port"/></td>
<td><form:errors path="port" cssClass="error"/></td>
</tr>
<tr>
<td><label for="test">Test: </label> </td>
<td><form:checkbox path="test" id="test"/></td>
<td><form:errors path="test" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update Interface"/>
</c:when>
<c:otherwise>
<input type="submit" value="Add Interface"/>
</c:otherwise>
</c:choose>
</td>
</tr>
</table>
</form:form>
Controller :
#RequestMapping(value = {"/newInterface"}, method = RequestMethod.POST)
public String saveInterface(#Valid Interface intface, BindingResult result, ModelMap model)
{
if (result.hasErrors())
{
return "interfaceDataAccess";
}
interfaceService.saveInterface(intface);
return "redirect:/interfaces/list";
}
Entity :
#RequestMapping(value = {"/newInterface"}, method = RequestMethod.POST)
public String saveInterface(#Valid Interface intface, BindingResult result, ModelMap model)
{
if (result.hasErrors())
{
return "interfaceDataAccess";
}
interfaceService.saveInterface(intface);
return "redirect:/interfaces/list";
}
You will notice this #Unique annotation which is something i built. Essentially it allows me to check if one of the values entered by the user already exists and that works just fine on my other entities. I tried removing it completely and i still get this exception as soon as validation fails. I literally have over 20 controllers that work the exact same way, line for line, and they work fine. This completely baffles me and i'm sure it's something really stupid. I can provide the MVC code for a working entity for comparison if needed.
Thanks
* EDIT *
Here is some working code for my heightUnit class:
Controller :
#RequestMapping(value = {"/newHeightUnit"}, method = RequestMethod.GET)
public String newHeightUnit(ModelMap model)
{
HeightUnit heightUnit = new HeightUnit();
model.addAttribute("heightUnit", heightUnit);
model.addAttribute("edit", false);
return "heightUnitDataAccess";
}
#RequestMapping(value = {"/newHeightUnit"}, method = RequestMethod.POST)
public String saveHeightUnit(#Valid HeightUnit heightUnit, BindingResult result, ModelMap model)
{
if (result.hasErrors())
{
return "heightUnitDataAccess";
}
heightUnitService.saveHeightUnit(heightUnit);
return "redirect:/heightUnits/list";
}
View :
<form:form method="POST" modelAttribute="heightUnit" class="form-style-7">
<form:input type="hidden" path="id" id="id"/>
<ul>
<li>
<label for="name">Name: </label>
<form:input path="name" id="name"/>
<span><form:errors path="name" cssClass="error"/></span>
</li>
<c:choose>
<c:when test="${edit}">
<input type="submit" value="Update Height Unit"/>
</c:when>
<c:otherwise>
<input type="submit" value="Add Height Unit"/>
</c:otherwise>
</c:choose>
</ul>
</form:form>
Entity :
private int id;
private String name;
#Id
#GeneratedValue
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
#Size(min = 1, max = 15, message = "Name must be between 1 and 15 characters long")
#Unique(entityType = "heightUnit", field = "name", message = "The name needs to be unique!")
#Column(nullable = false, unique = true, length = 15)
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof HeightUnit)
{
HeightUnit heightUnit = (HeightUnit)obj;
if (id == heightUnit.getId())
{
return true;
}
}
return false;
}
#Override
public int hashCode()
{
int hash = 7;
hash = 37 * hash + this.id;
hash = 37 * hash + Objects.hashCode(this.name);
return hash;
}
This works perfectly and i'm getting the errors back on the form when attempting to break a validation rule.
Your issue is that you are heading to the form page and it's looking for a pre-instantiated model that aIt's not available. What you have to do is to add the Interface object as an attribute of the model:
model.addAttribute("intface", new Interface());
Remember to add it to the #RequestMapping annoted method that takes you to the form page, something like this:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String displayNewInterfaceLogin(Model model) {
model.addAttribute("intface", new Interface());
return "newInterface";
}
i FINALLY figured this out. For whatever the crap reason, i had to change the signature of my controller's saveInterface method to this :
public String saveInterface(#Valid #ModelAttribute("intface") Interface intface, BindingResult result, ModelMap model)
I have NO IDEA why only THIS entity complains about this when the CRUD operations of all my entity types are built the exact same way but there you go!
Hope this can help someone eventually!

Spring MVC passing ArrayList back to controller

I am new to Spring. I display a list with users. Every row has a checkbox for removing the users.
Controller:
#Controller
public class AdminController {
#Autowired
private UserDao userDao;
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("users", userDao.findAll());
model.setViewName("admin");
return model;
}
#RequestMapping(value = "admin/remove", method = RequestMethod.POST)
public ModelAndView removeUser(#ModelAttribute(value = "users") ArrayList<User> users) {
ModelAndView model = new ModelAndView();
//UPDATE USERS HERE
model.setViewName("redirect:/admin");
return model;
}
JSP:
<form:form action="/admin/remove" method="POST" modelAttribute="users">
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email/login</th>
<th>Profession</th>
<th>Select<th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${users}">
<tr>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.login}</td>
<td>${user.profession}</td>
<td><input type="checkbox" value="${user.delete}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" value="Delete user(s)" class="btn-danger" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form:form>
The list is rendered correctly. If i press the "Delete user(s)" button. The #modelAttribute users is empty.
I also tried wrapping the list in a new class, but i get the same results.
Any ideas?
Thanks to minion, i found the answer
Wrapper:
public class UserListWrapper {
private ArrayList<User> users;
public ArrayList<User> getUsers() {
return users;
}
public void setUsers(ArrayList<User> users) {
this.users = users;
}
Controller:
#Controller
public class AdminController {
#Autowired
private UserDao userDao;
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
UserListWrapper wrapper = new UserListWrapper();
wrapper.setUsers(new ArrayList<User>(userDao.findAll()));
model.addObject("userListWrapper",wrapper);
model.setViewName("admin");
return model;
}
#RequestMapping(value = "admin/remove", method = RequestMethod.POST)
public ModelAndView removeUser(#ModelAttribute(value = "userListWrapper") UserListWrapper userListWrapper) {
ModelAndView model = new ModelAndView();
userDao.removeFlaggedUsers(userListWrapper.getUsers());
model.setViewName("redirect:/admin");
return model;
}
}
View:
<form:form action="/admin/remove" method="POST" modelAttribute="userListWrapper">
<table class="table table-striped">
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email/login</th>
<th>Profession</th>
<th>Select<th>
</tr>
</thead>
<tbody>
<c:forEach varStatus="us" var="user" items="${userListWrapper.users}" >
<tr>
<td><form:input type="hidden" path="users[${us.index}].firstName"/>${user.firstName}</td>
<td><form:input type="hidden" path="users[${us.index}].lastName"/> ${user.lastName}</td>
<td><form:input type="hidden" path="users[${us.index}].login"/>${user.login}</td>
<td><form:input type="hidden" path="users[${us.index}].profession"/>${user.profession}</td>
<td><form:checkbox path="users[${us.index}].delete" value="${user.delete}"/></td>
<form:input type="hidden" path="users[${us.index}].id"/>
</tr>
</c:forEach>
</tbody>
</table>
<input type="submit" value="Delete user(s)" class="btn-danger" />
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form:form>
Thank you!
EDIT: Dont forget to also add the fields you are not displaying.
For example:
If you dont add the id, your delete will not work because the id in the returned User object will be NULL.
Your ModelAttribute is empty as there is no form data binding happening from your jsp to your model attribute. Take a look at how Spring sample for binding collections "http://developer.ucsd.edu/develop/user-interface/building-a-form/form-binding-with-collections.html". This will help you to understand.
Most of the Spring application typically uses form:input with "path" parameter to do data binding.
You should build your functionality around spring-mvc select tag. Few changes would be in order though, push a list to a POJO class e.g.
public class FormBean {
private List<String> users;
public FormBean() {
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
}
change your mapping to
#RequestMapping(value = "admin/remove", method = RequestMethod.POST)
public ModelAndView removeUser(#ModelAttribute(value = "formBean") FormBean formBean) {
finally, swap your c:forEach with springs select tag, so something like
<form:form action="/admin/remove" method="POST" modelAttribute="formBean">
...
<form:select path="users" items="${users}" multiple="true" />
...
</form>
This is because you are using a redirect: in your view. Have a look on Flash Attributes :
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html
http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/
You should be able to get the updated list :)

Spring validation with Javax.validation redirects to 400

I am working on a Spring-MVC application, and I want to validate some data. Currently I am able to validate the data with no problems. Only thing is if the data is invalid, I would like to go to another JSP page, which is not happening right now. Instead I get an Apache 400 error, request was sent syntactically incorrect. Can anyone tell me what all is remaining to implement in validation.
Controller :
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listPersons(Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
if(!(person==null)){
return "redirect:/canvas/list";
} else {
model.addAttribute("person", new Person());
// model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("notices",new Notes());
model.addAttribute("canvases",new Canvas());
return "person";
}
}
#RequestMapping(value= "/person/add", method = RequestMethod.POST)
public String addPerson(#Valid Person person,#ModelAttribute("person") Person p,Model model,BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "redirect:/";
}
this.personService.addPerson(p);
return "redirect:/";
}
Entity :
#Entity
#Table(name="person")
public class Person implements UserDetails{
#NotEmpty #Email
#Column(name = "username")
private String username;
#NotEmpty(message = "Please enter password")
#Column(name = "password")
private String password;
#Size(min = 2,max = 30)
#Column(name = "firstname")
private String firstName;
#Size(min = 2,max = 50)
#Column(name = "secretquestion")
private String secretquestion;
#Size(min = 2,max = 500)
#Column(name = "secretanswer")
private String secretanswer;
}
JSP :
<tr>
<td>
<form:label path="firstName">
<spring:message text="FirstName"/>
</form:label>
</td>
<td>
<form:input path="firstName" />
</td>
<td><form:errors path="firstName"/>Please enter Firstname properly</td>
</tr>
<tr>
<td>
<form:label path="username">
<spring:message text="Email"/>
</form:label>
</td>
<td>
<form:input path="username" />
</td>
<td><form:errors path="username"/>Please enter Email properly</td>
</tr>
<tr>
<td>
<form:label path="password">
<spring:message text="Password"/>
</form:label>
</td>
<td>
<form:input path="password" />
</td>
<td><form:errors path="password"/>Please enter password properly</td>
</tr>
<tr>
<td>
<form:label path="secretquestion">
<spring:message text="secretquestion"/>
</form:label>
</td>
<td>
<form:input path="secretquestion" />
</td>
<td><form:errors path="secretquestion"/>Please enter secretquestion properly</td>
</tr>
<tr>
<td>
<form:label path="secretanswer">
<spring:message text="secretanswer"/>
</form:label>
</td>
<td>
<form:input path="secretanswer" />
</td>
<td><form:errors path="secretanswer"/>Please enter secretanswer properly</td>
</tr>
Servlet-context.xml
<beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"/>
Pom.xml
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.1.Final</version>
</dependency>
Any pointers would be nice. Mainly I would like to avoid going on Apache 400, but just display what exactly went wrong with the input field.
This is might be because of public String addPerson(#Valid Person person,#ModelAttribute("person") Person p,Model model,BindingResult bindingResult) signature . BindingResult must follow #ModelAttribute as method signature might have more that one model object and Spring will create a separate BindingResult instance for each of them.That is why when the data is invalid spring is not able to bind errors to BindingResult and throws 400 error.
Try changing method signature to public String addPerson(#Valid Person person,#ModelAttribute("person") Person p,BindingResult bindingResult,Model model).
Read more on BindingResult.

jsp in another jsp struts 2

1st problem : i have a jsp in which there are two tabs ,for the second tab i have included the struts include tag. When i open the second tab and performs the action the second tab form values are not passing to the action.
2nd problem : in the select tag i have populate the list but it is coming as prepopulated means all the options are coming as selected="selected"
main jsp in which tabs are made
<!-- admin first tab starts here -->
<form action="saveRolesAndPermissions" method="post">
<table align="center">
<tr>
<td ><s:text name="FTID" ></s:text></td>
<td ><s:textfield id="FTID" name="ft_id">
</s:textfield></td>
<td><input type="button" value="validate" onclick="userPresent()"></td>
</tr>
</table>
<table>
<tr>
<td>First Name</td>
<td><input id="first_name" type="text" readonly onkeydown="return false"></td>
<td>Last Name</td>
<td><input id="last_name"
type="text" readonly onkeydown="return false"></td>
<td>Email-Id</td>
<td><input id="mail_id" type="text"
readonly onkeydown="return false"></td>
</tr>
</table>
<table align="center">
<tr>
<td><s:text name="ROLES"></s:text></td>
<td></td>
<td></td>
</tr>
<tr>
<td><s:text name="Available Roles"></s:text></td>
<td></td>
<td><s:text name="Assigned Roles"></s:text></td>
</tr>
<tr>
<td><s:select id="roles" name="availableRole"
multiple="true" list="availableRole"></s:select></td>
<td><input type="button" value="&gt" onclick="move_list_items('roles','assignedroles');"/><input
type="button" value="&lt" onclick="move_list_items('assignedroles','roles');"/></td>
<td><s:select id="assignedroles" name="assignedRole" multiple="true"
list="{}" >
</s:select></td>
</tr>
</table>
<br /> <br /> <br />
<table>
<tr>
<td><s:text name="Permissions"></s:text></td>
<td></td>
<td> </td>
</tr>
<tr>
<td><s:text
name="Available Permissions"></s:text></td>
<td></td>
<td><s:text name="Assigned Permissions"></s:text></td>
</tr>
<tr>
<td><s:select id="permissions" multiple="true"
name="availablePermission" list="availablePermission" headerValue=""></s:select></td>
<td><input
type="button" value="&gt" onclick="move_list_items('permissions','assignedpermissions');"/><br /> <input type="button"
value="&lt" onclick="move_list_items('assignedpermissions','permissions');" /></td>
<td><s:select id="assignedpermissions" multiple="true" name="assignedPermission"
list="{}" ></s:select></td>
</tr>
</table>
<br /> <br />
<table align="center" style="width: 25%;">
<tr>
<td><s:if test="hasActionMessages()">
<div class="welcome" style="list-style:none">
<s:actionmessage />
</div>
</s:if></td>
</tr>
</table>
<table>
<tr>
<td><s:submit
value="save"onclick="saveRole();return false;"></s:submit></td>
<td> <input type="button" name="close"
value="close" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</form>
<!-- second tab for modify roles -->
<div id="content02" class="content" >
<s:include value="../asp/aspAdminModify.jsp"></s:include>
</div>
<!-- /second tab ends here -->
included jsp
<form action="grantedRolesAndPermissions" method="post">
<table>
<tr>
<td><s:text name="FTID" ></s:text></td>
<td><s:textfield id="modify_FTID" name="modifyftid">
</s:textfield></td>
<td><s:submit
value="search" onclick="search();return false;"></s:submit>
</td>
</tr>
</table>
Bean for the first tab
private String ft_id;
private ArrayList<String> availableRole;
private ArrayList<String> availablePermission;
private ArrayList<String> assignedRole;
private ArrayList<String> assignedPermission;
//getters and setters
Action for the first tab
public class ASPadmin extends ActionSupport implements ServletRequestAware, ModelDriven<ASPAdminBean>{
/**
*
*/
private static final long serialVersionUID = 1L;
private AdminASPService aspService = new AdminASPService();
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
public CMTUser cmtuser;
private ASPAdminBean aspAdminBean = new ASPAdminBean();
//getters and setters
public String populateRolesAndPermissions() throws Exception
{
/*aspAdminBean=new ASPAdminBean();*/
aspAdminBean.setAvailableRole(aspService.getRolesList());
aspAdminBean.setAvailablePermission(aspService.getPermissionsList());
return SUCCESS;
}
public String saveRolesAndPermissions() throws Exception
{
User user = CMTUser.getUser(request);
String login = user.getUserId();
String[] temp = login.split("\\.");
String abcfinal = temp[0].substring(0, 1).toUpperCase()
+ temp[0].substring(1);
String deffinal = temp[1].substring(0, 1).toUpperCase()
+ temp[1].substring(1);
String name = abcfinal + " " + deffinal;
System.out.println("name ==============>" + name);
String id = aspService.saveRolesPermissions(aspAdminBean,name);
System.out.println("id=======>"+id);
if("Y".equals(id)){
addActionMessage("Record Inserted Successfully");
populateRolesAndPermissions();
return SUCCESS;
}
else{
return ERROR;
}
}
#Override
public String execute() throws Exception {
String url = request.getRequestURL().toString();
String[] actionArray = url.split("/");
String event = null;
String forward = SUCCESS;
for (int i = 0; i < actionArray.length; i++) {
event = actionArray[i];
}
System.err.println(event);
try {
if (event.equals("aspAdmin.action")) {
populateRolesAndPermissions();
}
}catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
#Override
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
#Override
public ASPAdminBean getModel() {
// TODO Auto-generated method stub
return aspAdminBean;
}
}
bean for second tab
public class ASPAdminModifyBean {
private String modifyftid;
private String aspmodifyassignedRole;
private String aspmodifyassignedPermission;
private String createddate;
private String createdby;
private String updateddate;
private String updatedby;
private String username;
private ArrayList<String> modifyavailableRole;
private ArrayList<String> modifyavailablePermission;
private ArrayList<String> modifyassignedRole;
private ArrayList<String> modifyassignedPermission;
//getters and setters
action for the second tab
public class ASPadminModify extends ActionSupport implements ServletRequestAware, ModelDriven<ASPAdminModifyBean> {
private AdminASPService aspService = new AdminASPService();
private GetRolePermissionListInt[] roleVO;
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
private ASPAdminModifyBean modify = new ASPAdminModifyBean();
GetRolePermissionListInt role;
//getters and setters for the above
public String grantRolesPermissions(){
System.out.println("enter the grant roles and permissions");
String tab2="modify";
boolean id;
HttpServletRequest request=getRequest();
HttpSession session=request.getSession();
session.setAttribute("tabs",tab2 );
role=aspService.getGrantedRolesAndPermissions(modify);
System.out.println("assigned roles===================>"+role.getAssignedRoles());
modify.setAspmodifyassignedRole(role.getAssignedRoles());
modify.setAspmodifyassignedPermission(role.getAssignedPermissions());
modify.setCreatedby(role.getCreatedBy());
modify.setCreateddate(role.getCreatedDate());
modify.setUpdatedby(role.getUpdatedBy());
modify.setUpdateddate(role.getUpdatedDate());
modify.setUsername(role.getUserName());
modify.setModifyftid(role.getFtid());
System.out.println("assigned permissions==============>"+role.getAssignedPermissions());
System.out.println("updated by=================>"+role.getUpdatedBy());
System.out.println("update date=================>"+role.getUpdatedDate());
System.out.println("created by===================>"+role.getCreatedBy());
System.out.println("created date=====================>"+role.getCreatedDate());
System.out.println("ftid=============================>"+role.getFtid());
System.out.println("user name===========================>"+role.getUserName());
System.out.println("ftid=============>"+role.getFtid());
if(role!=null){
return SUCCESS;
}else{
return ERROR;
}
}
#Override
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
}
#Override
public ASPAdminModifyBean getModel() {
// TODO Auto-generated method stub
return modify;
}
}
Well, the code is grown again :)
Start by :
changing your ArrayList declarations to List (in both beans, and regenerate getters and setters);
changing the way you get the Request, the Response and the Session, by using Struts2 Aware s interfaces (and their setters, with code inside)
Then if it still doesn't work, describe a little better what do you mean by "values are not passing to Action", and consider posting your interceptor stack config.
Hope that helps...

Categories

Resources