I'm learning spring boot from a project https://github.com/rstyro/admin
In page/role/list.html,there is code:
<button th:if="${QX.add == '1' && QX.query == '1'}" class="btn btn-success
btn-sm" id="addRole"><i class="fa fa-plus"></i> add role</button>
I want to check what is this QX entity, So I go to RoleController.java
#RequestMapping(value="/list",method=RequestMethod.GET)
public Object list(Model model){
model.addAttribute("roles", roleService.list());
return "page/role/list";
}
then RoleService.java
#Service
public class RoleService implements IRoleService{
#Autowired
private RoleDao roleDao;
#Autowired
private MenuService menuService;
private Logger log = Logger.getLogger(this.getClass());
#Override
public List<ParameterMap> list() {
return roleDao.list();
}
then RoleDao.java
public interface RoleDao {
public List<ParameterMap> list();
public List<ParameterMap> getRoleByuId(ParameterMap pm);
public ParameterMap getRoleById(ParameterMap pm);
public void updateRoleQX(ParameterMap pm);
public void addRole(ParameterMap pm);
public void delRole(String roleId);
public void delUserRole(String roleId);
}
and RoleMapper.xml
<mapper namespace="com.lrs.admin.dao.RoleDao" >
<select id="list" resultType="pm">
SELECT
role_id,
role_name,
role_desc,
rights,
add_qx,
del_qx,
edit_qx,
query_qx
from
sys_role
</select>
and Role.java
public class Role {
private long roleId;
private String roleName;
private String roleDesc;
private String rights;
private String addQX;
private String delQX;
private String editQX;
private String queryQX;
public long getRoleId() {
return roleId;
}
But nothing is there. Am I missing something? Thx.
He is calling
return roleDao.list();
But there is no implementation of that statement, RoleDao interface is not implemented anywhere. Which means there is no bean called roleDao, which means, you cannot run this code. It will give you error.
The author probably did not share RoleDao implementation.
Related
I want to make an orderform with spring boot where I can Save the order with more order items.
I dont't know how to implement the Service, Class and even the thymeleaf page for this.
Any hint would be great!
Here's a picture what I want to make
An here's my two entity class(no getters and setters, and customer for brevity)
#Entity
#Table(name = "order_item")
public class OrderItem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "order_id")
private Order order;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id")
private Product product;
private int qty;
private double amount;
public OrderItem() {}
public OrderItem(int id, Order order, Product product, int qty, double amount) {
super();
this.id = id;
this.order = order;
this.product = product;
this.qty = qty;
this.amount = amount;
}
#Entity
#Table(name="order")
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private Date dateTime;
private double total;
private int paidStatus;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="customer_id")
private Customers customer;
#OneToMany(mappedBy="customOrder")
private List<OrderItem> orderItems;
You simply need to create a repository, service and controller.
1. First, let's create repositories for our models.
public interface CustomerRepository extends JpaRepository<Customer, Long> {}
public interface ProductRepository extends JpaRepository<Product, Long> {}
public interface OrderRepository extends JpaRepository<Order, Long> {}
2. Second, let's create our service layer.
(Note: I gathered all the functionality here for an example.You can distribute it to different layers.)
public interface OrderService {
List<Customer> findAllCustomers();
List<Product> findAllProducts();
List<Order> findAllOrders();
}
#Service
public class OrderServiceImpl implements OrderService {
private final CustomerRepository customerRepository;
private final ProductRepository productRepository;
private final OrderRepository orderRepository;
public OrderServiceImpl(CustomerRepository customerRepository,
ProductRepository productRepository,
OrderRepository orderRepository) {
this.customerRepository = customerRepository;
this.productRepository = productRepository;
this.orderRepository = orderRepository;
}
#Override
public List<Customer> findAllCustomers() {
return customerRepository.findAll();
}
#Override
public List<Product> findAllProducts() {
return productRepository.findAll();
}
#Override
public List<Order> findAllOrders() {
return orderRepository.findAll();
}
}
3. Now add a controller layer, this will reply to your urls. (Note: here are simple examples just to help you understand the operation. You can come up with many different solutions.)
#Controller
#RequestMapping("/order")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
#GetMapping("/create")
public String createOrder(Model model) {
model.addAttribute("customers", orderService.findAllCustomers());
model.addAttribute("products", orderService.findAllProducts());
model.addAttribute("order", new Order());
return "order-form";
}
#PostMapping("/insert")
public String insertOrder(Model model, Order order) {
// Save operations ..
return "order-view";
}
}
4. Here, customers and products come from your database.
The 'Submit Form' button will be sending the entity id's of the selections here to the insertOrder method. (You can duplicate your other fields in a similar way and I recommend you to examine the example in this link to dynamically duplicate this product selection area.)
<!DOCTYPE HTML>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<div>
<form action="/order/insert" method="post" th:object="${order}">
<p>
<label>Select Customer</label>
</p>
<p>
<select name="customer.id">
<option th:each="customer : ${customers}"
th:value="${customer.id}"
th:text="${customer.name}">Customer Name</option>
</select>
</p>
<p>
<label>Select Product</label>
</p>
<p>
<select name="orderItems[0].product.id">
<option th:each="product : ${products}"
th:value="${product.id}"
th:text="${product.name}">Product Name</option>
</select>
<input type="text" name="orderItems[0].quantity" />
</p>
<button type="submit">Submit Form</button>
</form>
</div>
</body>
</html>
I recommend you to read this example, which has scope for necessary library and spring settings.
I built a simple Springboot API which is hooked up to a H2 db that contains some test data. However when I hit the API endpoint I get an empty response.
[{}]
When I debug my application the user object that is returned by the controller contains the user I am expecting.
UserController.java
#RestController
#RequestMapping("api/user")
public class UserController {
private UserService userService;
public UserController(#Autowired UserService userService){
this.userService = userService;
}
#GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public Set<User> getAllUsers(){
final Set<User> users = userService.getAllUsers();
return users;
}
}
UserRepo.java
public interface UserRepository extends CrudRepository<User, Long> {
#Query("SELECT usr from User usr")
Set<User> getAllUsers();
}
UserService.java
public interface UserService {
Set<User> getAllUsers();
}
UserServiceImpl.java
#Service
public class UserServiceImpl implements UserService {
private final UserRepository repository;
public UserServiceImpl(#Autowired UserRepository userRepository){
this.repository = userRepository;
}
#Override
public Set<User> getAllUsers(){
final Set<User> users = repository.getAllUsers();
return users;
}
}
User.java
#Entity
#Getter
public class User {
#Id
private Long id;
private String username;
private String firstname;
private String lastname;
private String email;
private String role;
private String premium;
}
This was a rather strange issue of which I am still unable to say which. However, removing lombok's #getter and #setter annotations then implementing traditional ones fixed this issue.
You'll have to set the class members of User public to allow jackson serialise them, i.e.,
// User.java
#Entity
public class User {
#Id
public Long id;
public String username;
public String firstname;
public String lastname;
public String email;
public String role;
public String premium;
}
Note: if you'd like to not serialise a field, use #JsonIgnore instead of setting it as private, e.g.,
#Entity
public class User {
...
#JsonIgnore
public String role;
...
}
Just remove final and change Set to List as well.
and you really don`t need to do like this:
public UserController(#Autowired UserService userService)
Just remove this method and add Autowired up to userService filed.
Because final object can`t be cast to json string.
remove this as well:
produces = MediaType.APPLICATION_JSON_VALUE</h3>
I create a new service with spring boot and spring mvc .
UserEntity.class:
#Entity
#Table(name = "users")
public class UserEntity {
private long id;
private String username;
private String password;
private boolean active;
private boolean login;
public UserEntity(UserDto dto) {
this.id = dto.getId();
this.username = dto.getUsername();
this.password = dto.getPassword();
this.active = dto.isActive();
}
// getters&setters...
}
UserDto.class:
public class UserDto {
private long id;
private String username;
private String password;
private boolean active;
public UserDto(long id, String username, String password, boolean active) {
this.id = id;
this.username = username;
this.password = password;
this.active = active;
}
// getters&setters...
}
UserRepository:
#Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
}
UserServiceImpl.class: (and UserService Interface)
#Service
#Transactional
public class UserServiceImpl implements UserService {
private final UserRepository repo;
#Autowired
public UserServiceImpl(UserRepository repo) {
this.repo = repo;
}
#Override
public boolean saveUser(UserDto dto) {
UserEntity user = new UserEntity(dto);
repo.save(user);
return true;
}
}
UserController.class:
#RestController
public class UserController {
private final UserService service;
#Autowired
public UserController(UserService service) {
this.service = service;
}
#RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(#RequestBody UserDto userDto) {
service.saveUser(userDto);
}
}
Application.class:
#EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
my Spring Boot project starts correctly. But when I test my service with IntelliJ Test Restful Web Service Tool I encounter an error:
Response:
{"timestamp":1464066878392,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/users"}
What is the problem?
My suggestion would be to remove the constructors from the UserController and UserServiceImpl classes, there's no need for them. Then, assign the #Autowired annotation to the declarations instead. Also, I don't think you need to make them final.
UserServiceImpl.class:
#Service
#Transactional
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository repo;
#Override
public boolean saveUser(UserDto dto) {
UserEntity user = new UserEntity(dto);
repo.save(user);
return true;
}
}
UserController.class:
#RestController
public class UserController {
#Autowired
private UserService service;
public UserController(UserService service) {
this.service = service;
}
#RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(#RequestBody UserDto userDto) {
service.saveUser(userDto);
}
}
I am trying to learn how to build an application using Spring MVC and Hibernate. Currently I am stuck on inserting checkbox values into MySQL database.
My Database Table Structure is like following:
id name interest
When I fill up my form and hit submit I get this error message :
root cause
java.sql.SQLException: Incorrect string value: '\xAC\xED\x00\x05ur...' for column 'interest' at row 1
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
I am trying to insert values in my table so that after insertion it looks like following:
id name interest
1 Steve PHP
2 Steve Java
3 Wuagh C#
4 Wuagh PHP
Could you please tell me how to achieve this? And If possible could you also tell me how can I achieve this as well ?
id name interest
1 Steve PHP, Java
2 Wuagh C#, PHP
Please see my codes below
My Form:
<c:url var="action" value="/register" ></c:url>
<form:form action="${action}" modelAttribute="subscriber" method="POST" >
<div>
<label>Name</label>
<form:input path="name"/>
<form:errors path="name" cssClass="error"/>
</div>
<div>
<label>Interests</label>
<form:checkboxes path="interest" items="${records.interests}"/>
</div>
<input type="submit" value="Submit">
</form:form>
Controller:
package com.spring.org;
#Controller
public class HomeController {
#Autowired
private SubscriberService subService;
#RequestMapping(value="/register", method= RequestMethod.GET)
public ModelAndView RegistrationForm(#ModelAttribute Subscriber subscriber, BindingResult result)
{
HashMap<Integer, String> interest = new HashMap<Integer, String>();
interest.put(1,"Java");
interest.put(2,"PHP");
interest.put(3, "C#");
return new ModelAndView("regForm", "records", interest);
}
#RequestMapping(value="/register", method= RequestMethod.POST)
public ModelAndView RegistrationFormSubmit(#ModelAttribute("subscriber") #Valid Subscriber subscriber, BindingResult result)
{
if (result.hasErrors()) {
return new ModelAndView("regForm");
}
else
{
subService.addSubscriber(subscriber);
return new ModelAndView("redirect:/showList");
}
}
}
Model - Subscriber
#Entity
#Table(name = "PERSON", schema = "java2")
public class Subscriber {
#Id
#Column(name="ID")
#GeneratedValue
private int id;
#NotEmpty(message = "Please enter your Name.")
private String name;
private String[] interest;
public String getName() {return name;}
public void setName(String name) { this.name = name; }
public String[] getInterest() { return interest; }
public void setInterest(String[] interest) { this.interest = interest; }
}
SubscribeService Implementation :
#Service
public class SubscriberServiceImpl implements SubscriberService{
#Autowired
private SubscriberDao subsDao ;
#Override
public void addSubscriber(Subscriber subscriber) {
subsDao.addSubscriber(subscriber);
}
}
SubscriberDao Implementation :
#Repository
public class SubscriberDaoImpl implements SubscriberDao {
#Autowired
private SessionFactory sessionFactory ;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addSubscriber(Subscriber subscriber) {
getSessionFactory().openSession().save(subscriber);
}
}
I am trying to implement 'forgot password' functionality using JSF SEAM in our index page, I am using a a4j:jsFunction to send the users email and card number via two 's
It seems to work fine when I just send the email (as a string), but when I added card number (int) it threw the following..
Caused by: javax.el.PropertyNotFoundException: /index.xhtml #256,138 assignTo="#{forgotPasswordActions.cardnumber}": The class 'org.javassist.tmp.java.lang.Object_$$_javassist_seam_5' does not have the property 'cardnumber'.
The backing bean looks like this...
#Stateless
#Name("forgotPasswordActions")
public class ForgotPasswordActionsBean implements ForgotPasswordActions, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Logger private Log log;
#In private EmailService emailService;
#In private UserDAO userDAO;
#In private MessagePoster messagePoster;
#In private Map<String, String> messages;
private User user;
private String address;
private String email;
private int cardnumber;
#Override
public void resetPassword(){
new RunAsOperation(true) {
public void execute() {
if(StringUtils.isNotEmpty(email)){
user = userDAO.findByEmail(email);
}
else{
messagePoster.postPopupInfoMessage(messages.get("inputEmpty"));
}
if(user!=null && cardnumber == user.getCardId()){
String newPassword = generateRandomPassword();
log.debug("updating password...");
user.setPassword(newPassword);
user = userDAO.makePersistent(user);
address = user.getEmail();
log.debug("password changed to: "+newPassword);
Map<String, Object> emailInfo = new HashMap<String, Object>();
emailInfo.put("name", user.getFirstname());
emailInfo.put("newPassword", newPassword);
emailService.sendToAddress(Email.user_password_reset, address, emailInfo);
messagePoster.postPopupInfoMessage(messages.get("pwReset")+" "+user.getEmail());
}
else{
messagePoster.postPopupInfoMessage(messages.get("resetFailed"));
}
}
}.run();
}
//---------------------- Setters
#Override
public void setEmail(String email) {
this.email = email;
}
#Override
public void setCardno(int cardnumber) {
this.cardnumber = cardnumber;
}
}
and the JSF / HTML
<div id="forgotPasswordDialog" title="Forgot Password">
<div class="textBox">
<input id="emailLookupval" type="text" />
<input id="cardNoval" type="text" />
<button onclick="resetPassword(jQuery('#emailLookupval').val(),jQuery('#cardNoval').val())" type="button">Reset</button>
<a4j:form id="forgotPassword">
<a4j:jsFunction name="resetPassword"
action="#{forgotPasswordActions.resetPassword}"
oncomplete="jQuery('#forgotPasswordDialog').dialog('open')">
<a4j:actionparam name="userEmail" assignTo="#{forgotPasswordActions.email}" />
<a4j:actionparam name="userCardno" assignTo="#{forgotPasswordActions.cardnumber}" />
</a4j:jsFunction>
</a4j:form>
</div>
</div>
I cant work out why it wont set this bean property?? Any help appreciated!
Your setter is called setCardno() while setCardnumber() is been expected by the view. The #{bean.property} does not relate to property names in the bean. It relates to getter/setter method names. There are 2 ways to fix this:
Rename the setter method:
public void setCardnumber(int cardnumber) {
this.cardnumber = cardnumber;
}
Or, rename the view property:
assignTo="#{forgotPasswordActions.cardno}"