I am trying to send some value in my jsp to a portlet class.I am using jstl to achieve that ,my requirement is to use requestScope to pass the value in the portlet.Here i have seen that when i am using requestScope to create URL in portlet it is working fine,but in case of value passing it is not working,i am posting my code what i have done so far
<fmt:setBundle basename="Language-ext"/>
<form action="<c:out value='${requestScope.registerUserActionUrl}'/>" method="POST">
<table width="200px">
<tr>
<td colspan="2">
<font color="#FF0000"><c:out
value="${requestScope.errorMsg}"/></font>
</td>
</tr>
<tr>
<td><fmt:message key="label.firstName"/></td>
<td><input type="text" name="firstName" value="${requestScope.User.firstName}"></input></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><fmt:message key="label.lastName"/></td>
<td><input type="text" name="lastName" value="${requestScope.User.lastName}"></input></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><font color="#FF0000"><b>*</b></font> <fmt:message key="label.email"/></td>
<td><input type="text" name="email" value="${requestScope.User.email}"></input> </td>
</tr>
<tr>
<td> </td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit"/>
<a href="<c:out value='${requestScope.resetRenderUrl}'/>">
<b><fmt:message key="label.reset"/></b>
</a>
</td>
</tr>
And this is my bean class
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5729328658617182010L;
private String firstName;
private String lastName;
private String email;
public User(String firstName,String lastName,String email){
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
And this is the portlet where i am catching the value
#ProcessAction(name = "registerUserAction")
public void registerUser(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
String email = request.getParameter("email");
System.out.println("Email :"+email +","+request.getParameter("firstName"));
// --set the information entered by the user on the registration
But i am getting null for both email and firstName .Somebody please help
Answer relevant for Liferay 6.2
By default, Liferay 6.2 requires request parameters for a given portlet to be prefixed with the portlet namespace. In plain HTML, you need to specify the namespace for each request parameter / form field explicitely by using <portlet:namespace/> tag:
<input type="text" name="<portlet:namespace/>firstName" value="${requestScope.User.firstName}">
Don't forget the required TLD import:
<%#taglib prefix="portlet" uri="http://java.sun.com/portlet" %>
Only the namespaced parameters are visible to the portlet (through standard portlet API).
Related
i am a beginner of spring boot framework.i want to work with search records using spring boot application. my index.html is loaded successfully when i enter the employee id on the employee id textbox and click search button relevant employee name result want to display the below textbox.but i don't know how to pass it .what i tired so so i attached below.
index.html
<form action="#" th:action="#{/search}" th:object="${employee}" method="post">
<div alight="left">
<tr>
<label class="form-label" >Employee ID</label>
<td>
<input type="hidden" th:field="*{id}" />
<input type="text" th:field="*{id}" class="form-control" placeholder="Employee ID" />
</td>
</tr>
</div>
<br>
<tr>
<td colspan="2"><button type="submit" class="btn btn-info">Search</button> </td>
</tr>
<div alight="left">
<tr>
<label class="form-label" >Employee Name</label>
<td>
<input type="text" th:field="*{ename}" class="form-control" placeholder="Employee Name" />
</td>
</tr>
</div>
</form>
Controller
#Controller
public class EmployeeController {
#Autowired
private EmployeeService service;
#GetMapping("/")
public String add(Model model) {
List<Employee> listemployee = service.listAll();
// model.addAttribute("listemployee", listemployee);
model.addAttribute("employee", new Employee());
return "index";
}
#RequestMapping("/search/{id}")
public ModelAndView showSearchEmployeePage(#PathVariable(name = "id") int id) {
ModelAndView mav = new ModelAndView("new");
Employee emp = service.get(id);
mav.addObject("employee", emp);
return mav;
}
}
Entity
#Entity
public class Employee {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String ename;
private int mobile;
private int salary;
public Employee() {
}
public Employee(Long id, String ename, int mobile, int salary) {
this.id = id;
this.ename = ename;
this.mobile = mobile;
this.salary = salary;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getMobile() {
return mobile;
}
public void setMobile(int mobile) {
this.mobile = mobile;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [id=" + id + ", ename=" + ename + ", mobile=" + mobile + ", salary=" + salary + "]";
}
Repository
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
It is easiest to create a dedicated form data object:
public class EmployeeSearchFormData {
private long employeeId;
// getter and setter
}
In the controller:
#Controller
public class EmployeeController {
#Autowired
private EmployeeService service;
#GetMapping("/")
public String add(Model model) {
model.addAttribute("employeeSearchFormData", new EmployeeSearchFormData());
return "index";
}
#PostMapping("/search")
public String doSearchEmployee(#ModelAttribute("employeeSearchFormData") EmployeeSearchFormData formData, Model model) {
Employee emp = service.get(formData.getEmployeeId());
model.addAttribute("employee", emp);
return "index";
}
}
Thymeleaf template:
<form action="#" th:action="#{/search}" th:object="${employeeSearchFormData}" method="post">
<div alight="left">
<tr>
<label class="form-label" >Employee ID</label>
<td>
<input type="text" th:field="*{employeeId}" class="form-control" placeholder="Employee ID" />
</td>
</tr>
</div>
<br>
<tr>
<td colspan="2"><button type="submit" class="btn btn-info">Search</button> </td>
</tr>
<div alight="left">
<tr>
<label class="form-label" >Employee Name</label>
<td>
<input type="text" th:field="${employee.ename}" class="form-control" placeholder="Employee Name" />
</td>
</tr>
</div>
</form>
Note the use of th:field="${employee.ename}" and not use *{...}. I also removed the hidden field as it does not seem needed to have it to me.
As an alternative, you can have the #PostMapping redirect to /employee/<id> if there is an endpoint available like that:
#PostMapping("/search")
public String doSearchEmployee(#ModelAttribute("employeeSearchFormData") EmployeeSearchFormData formData) {
return "redirect:/employee/" + formData.getEmployeeId();
}
Among CRUD operation Create is giving error of "A different object with the same identifier value was already associated with the session" Rest all (Read, Update and Delete) is working fine.
Im using oracle sql as database and there is one more entity of product with many to one mapping with categories class.
EntityClass
#Entity
public class Categories {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
public Categories() {
super();
}
public Categories(Integer id,String name) {
this.id=id;
this.name=name;
}
public Categories(String name) {
this.name=name;
}
//with setters and getters
}
JSP page
<body onload="document.getElementById('name').disabled = true;document.getElementById('hidden').disabled = true;">
<div align="center">
<h4>Add or Modify or Delete Categories</h4>
<form:form method="POST" action="/categories" modelAttribute="categories">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td>
<form:select path="name">
<form:option value="NONE" label="Select" />
<form:options items="${categoriesList}" />
</form:select>
</td>
</tr>
<tr>
<td>Operations</td>
<td>
<input type="radio" name="Ops" value="Add" checked="checked" onclick="document.getElementById('name').disabled = true; document.getElementById('newName').disabled = false;document.getElementById('hidden').disabled = true;">Add</input><br/>
<input type="radio" name="Ops" value="Modify" onclick="document.getElementById('name').disabled = false; document.getElementById('newName').disabled = false;document.getElementById('hidden').disabled = true;">Modify</input><br/>
<input type="radio" name="Ops" value="Delete" onclick="document.getElementById('name').disabled = false; document.getElementById('newName').disabled = true;document.getElementById('hidden').disabled = false;">Delete</input><br/>
</td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="newName" id="newName"/>
<input type="hidden" id="hidden" name="newName" value="dummy"/>
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</div>
</body>
Controller Class
#Controller
public class CategoriesController {
#Autowired
private CategoriesService cservice;
#RequestMapping(value = "/categories", method = RequestMethod.GET)
public ModelAndView categories() {
// view name model
ModelAndView modelAndView = new ModelAndView("categories", "categories", new Categories());
return modelAndView;
}
#RequestMapping(value = "/categories", method = RequestMethod.POST)
public String opsOnCategories(#ModelAttribute("categories") Categories cat,#RequestParam("Ops") String ops,#RequestParam("newName") String name)
{
if(ops.equals("Modify"))
{
cservice.modifyCategory(new Categories(Integer.parseInt(cat.getName()), name));
}else if(ops.equals("Add"))
{
cservice.addCategory(new Categories(name));
}else
{
cservice.deleteCategory(Integer.parseInt(cat.getName()));
}
return "categories";
}
#ModelAttribute("categoriesList")
public Map<String, String> getCategoryList() {
Map<String, String> categoriesList = new HashMap<String, String>();
List<Categories> ls=cservice.getAll();
for(int i=0;i<ls.size();i++)
{
categoriesList.put(ls.get(i).getId().toString(), ls.get(i).getName());
}
return categoriesList;
}
}
Can anyone please help on this.
Previous one due to which there was error
insert into CATEGORIES(ID,NAME) values (1,'Mobile');
insert into CATEGORIES(ID,NAME) values (2,'Laptop');
**Changes made to remove error*
insert into CATEGORIES(ID,NAME) values (hibernate_sequence.nextval,'Mobile');
insert into CATEGORIES(ID,NAME) values (hibernate_sequence.nextval,'Laptop');
My initial guess is that there something wrong with #Id #GeneratedValue with Oracle Database specifically.
There are couple of things that you can do:
1- Try to connect to any other Database type just to test the functionality - so that you can rule out what doesn't matter
2- Try to use the #org.springframework.data.annotation.Id alongside with the #Id of javax persistence
Something that look like this
#Id
#org.springframework.data.annotation.Id
private Integer id;
3- Create a class that Generates random Integer Ids and refer to it using the annotations (#GenericGenerator & #GeneratedValue)
This is my Entity
#Entity
public class User implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String mobNum;
private String email;
String gender;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
LocalDate bdate;
public LocalDate getDate() {
return bdate;
}
public void setDate(LocalDate bdate) {
this.bdate = bdate;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public User() {
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMobNum() {
return this.mobNum;
}
public void setMobNum(String mobNum) {
this.mobNum = mobNum;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
and here is my Spring-Form
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form:form action="add_student_data.htm" method="POST" commandName="user">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
<td><font color="red" /><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="bdate" >Date Of Birth</form:label></td>
<td><form:input path="bdate"/></td>
<td><font color="red" /><form:errors path="bdate" cssClass="bdate" /></td>
</tr>
<tr>
<td><form:label path="gender" >Gender</form:label></td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td><form:label path="mobNum">Mob Num</form:label></td>
<td><form:input path="mobNum"/></td>
<td><font color="red" /><form:errors path="mobNum" ccssClass="error"/></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email"/></td>
<td><font color="red" /><form:errors path="email" cssClass="error" /></td>
</tr>
</table>
<input type="submit" value="submit">
</form:form>
</body>
</html>
when i want to open this fom error is occured like
"org.apache.jasper.JasperException: org.springframework.beans.NotReadablePropertyException: Invalid property 'dateOfBirth' of bean class [com.domain.User]: Bean property 'dateOfBirth' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?"
I am using joda.org.time.LocalDate in User entity.What is the cause of the problem?
Your getter/setter method name and variable name in JSP do not match, change the following methods from:
public LocalDate getDate() {
return bdate;
}
public void setDate(LocalDate bdate) {
this.bdate = bdate;
}
to
public LocalDate getBdate() {
return bdate;
}
public void setBdate(LocalDate bdate) {
this.bdate = bdate;
}
I am developing a small Spring and hibernate base application in java, and my appication has a one to many relationship with Employee and Unit, Employee has a one unit, Unit has a many Employee.
in this small application genarate error like this `
I was hard code data to Unit schema table, i populate unit combobox filled in jsp its works, but inside the #controller unit has a null data.
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Column 'unit_id' cannot be null
if allow to null value to unit_id other data inserted with out insert unit_id
here my Entity class
#Entity
#Table(name = "employee")
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "epf")
private int epf;
#Column(name = "fname")
private String fname;
#Column(name = "lname")
private String lname;
#Column(name = "email")
private String email;
#JoinColumn(name = "unit_id", referencedColumnName = "id")
#ManyToOne//(optional = false)
private Unit unit;
#Entity
#Table(name = "unit")
public class Unit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "name")
My controller Class
#Autowired
private EmployeeService employeeService;
private DesignationService designationService;
#RequestMapping({"/index", "/"})
public String setupForm(Map<String, Object> map){
Employee student = new Employee();
map.put("employee", student);
map.put("employeeList", employeeService.getAllEmployee());
map.put("unitList", employeeService.getAllUnitList());
return "employee";
}
#RequestMapping(value="/employee.do", method=RequestMethod.POST)
public ModelAndView doActions(#ModelAttribute Employee emp, BindingResult result, #RequestParam String action, Map<String, Object> map){
ModelAndView modelAndView = new ModelAndView("employee");
Employee employeetResult = new Employee();
switch(action.toLowerCase()){ //only in Java7 can put String in switch
case "add":
employeeService.addEmployee(emp);
employeetResult = emp;
break;
case "edit":
employeeService.updateEmployee(emp);
employeetResult = emp;
break;
case "delete":
employeeService.deleteEmployee(emp.getId());
employeetResult = new Employee();
break;
case "search":
Employee searchedStudent = employeeService.getEmployee(emp.getId());
employeetResult = searchedStudent!=null ? searchedStudent : new Employee();
break;
}
map.put("employee", employeetResult);
map.put("employeeList", employeeService.getAllEmployee());
return modelAndView;
}
My JSP
<form:form action="employee.do" method="POST" commandName="employee">
<table width="341" border="0">
<tr>
<td width="154"> </td>
<td width="21"> </td>
<td width="152"> </td>
</tr>
<tr>
<td><spring:message code="employee.id"/></td>
<td> </td>
<td><form:input path="epf" /></td>
</tr>
<tr>
<td><spring:message code="employee.epf"/></td>
<td> </td>
<td><form:input path="epf" /></td>
</tr>
<tr>
<td><spring:message code="employee.fname"/></td>
<td> </td>
<td><form:input path="fname"/></td>
</tr>
<tr>
<td><spring:message code="employee.lname"/></td>
<td> </td>
<td><form:input path="lname" /></td>
</tr>
<tr>
<td><spring:message code="employee.email"/></td>
<td> </td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><spring:message code="employee.unit"/></td>
<td> </td>
<!-- Unit Combo filling --><td>
<form:select path="unit" multiple="false" size="1">
<form:options items="${unitList}" itemValue="id" itemLabel="name"/>
</form:select>
<!-- Unit Combo filling end --></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
<input type="submit" name="action" value="Edit" />
<input type="submit" name="action" value="Delete" />
<input type="submit" name="action" value="Search" />
</td>
</tr>
</table>
</form:form>
My DAO Class
> #Repository public class EmployeeDaoImp implements EmployeeDao {
>
> #Autowired private SessionFactory sessionfactory;
> public void addEmployee(Employee emp) { sessionfactory.getCurrentSession().save(emp);
>
> }
>
> public void updateEmployee(Employee emp) {
> sessionfactory.getCurrentSession().update(emp);
>
> }
>
> public void deleteEmployee(int id) {
> sessionfactory.getCurrentSession().delete(getEmployee(id)); }
>
> Employee public Employee getEmployee(int empId) {
> return (Employee) sessionfactory.getCurrentSession().get(Employee.class,empId); }
>
> public List getAllEmployee() {
> return sessionfactory.getCurrentSession().createQuery("from Employee").list(); }
The id is primary key in the DB. You are save an object without giving it's value. So either make it auto increment in table or generate it's value using hibernate.
I am trying to bind the input type checkbox using spring form controller,But i failed .
Here i am posting Controller,bean and jsp example,One more thing is i can't use
.
Below is the code:
Controller:
package com.test.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;
#SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {
private UserService userService;
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
user.setCommunity(user.getCommunity());
userService.add(user);
return new ModelAndView("userForm","user",user);
}
}
jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Registration Page</title>
<script>
function submitForm(){
document.testForm.submit();
}
</script>
</head>
<body>
<form:form method="POST" commandName="user" name="testForm" action="./userRegistration.htm">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="1" label="India" />
<form:option value="2" label="USA" />
<form:option value="3" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><input type="checkbox" name="community" value="Hibernate"/>Hibernate</br>
<input type="checkbox" name="community" value="test"/>test</br>
<input type="checkbox" name="community" value="test1"/>test1</br>
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" onclick="submitForm();"></td>
</tr>
</table>
</form:form>
</body>
</html>
Java beans:
package com.test.domain;
public class User {
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
I tried different ways,but no luck.Any hints please.
the browser will not send the field in the request if the checkbox isn't checked. the value will either be "true" or not sent. you will never get a "false" value.
add a hidden field with _name for every checkbox
EX:
<input type="checkbox" name="community" value="Hibernate"/>
<input type="hidden" name="_community" value="on"/>
Then, spring will take care of it.
If you do not use the form tag it will not automaticly bind your checkboxes. If you use plain html you have to bind the your self.
You can solve this by adding a list of community objects and then use form:checkboxes.
For example:
<form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
I would also recomend you to use a HashMap when using ModelAndView like this:
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
model.put("communityList", communityList);
return new ModelAndView("userFormat", model);
Manually bind using 'ServletRequestUtils'... http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/ServletRequestUtils.html
Example
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
Long subscriptionOwnerId = ServletRequestUtils.getLongParameter(request, "id");
return new ModelAndView('test'); }`