How to list data from database in a web page in spring framework - spring

I have created a database called student base on the tutorial provided by tutorials point PDF, they have covered how to map the form and insert values in to the database using controllers, but they have not explained how to display the data from the database on to the webpage.
My code to list all students.
#Override
public List<Student> listStudents() {
String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
return students;
}
How to call this from my controller in spring and return the list to my webpage.
My contoller is given below
#Controller
public class StudentController {
#RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student()
{
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Student student, ModelMap model)
{
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
studentJDBCTemplate.create(student.getName(), student.getAge());
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("msg", "Student Enrolled");
return "result";
}
// How to write the listing controller?
}

From the details you provide ,
public String ListStudents(ModelMap model)
{
List<Student> list= YourServiceClassObj.listStudents();
model.addAttribute("result", list);
return "View Name here";
}

public class AccountDAO {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public Account getAll(String user, String pass) {
String query = "SELECT * FROM dbo.USERR WHERE username=? AND password =?";
try {
conn = new DBContext().getConnection();
ps = conn.prepareStatement(query);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
while (rs.next()) {
return new Account(rs.getString(1),
rs.getString(2),
rs.getString(3));
}
} catch (Exception e) {
}
return null;
}
}

your controller and service methods should be like this .and then in the view use the controller returned attribute students.
#Controller
#RequestMapping(value = "/students", method = RequestMethod.GET)
public String students(ModelMap model)
{
List<Student> students= studentService.getStudents();
model.addAttribute("students", students);
return "student/studentList.html";
}
Service :
public interface StudentService {
List<Student> getStudents();
}
#Service
public class StudentServiceImpl implements StudentService {
#Override
public List<Student> getStudents() {
return studentRepository.findAll();
}

Related

Mockito Test for Spring NamedJDBC Template

I am trying to figure out mickito test for Named Jdbc Template but unable to do so. I did googling but did not find any accurate result. Below is example Code.
Student.class
#Data
public class Student {
private int id;
private String name;
private String address;
public Student(ResultSet rs) throws SQLException {
id = rs.getInt("id");
name = rs.getString("name");
address = rs.getString("address");
}
}
Student class takes ResultSet argument in constructor and mapped all column to variable .
StudentService.class
public class StudentService {
#Autowired
#Qualifier("namedJdbcTemplate")
NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public Student gerStudent(String id) {
Student student;
String selectStudent = "select id , name ,address from student where id=:id";
MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
mapSqlParameterSource.addValue(id, "id");
student = namedParameterJdbcTemplate.query(selectStudent, mapSqlParameterSource, resultSet -> {
Student response = new Student(resultSet);
return response;
});
return student;
}
}
Can anyone please help on Mockito Test for below line of code?
student = namedParameterJdbcTemplate.query(selectStudent, mapSqlParameterSource, resultSet -> {
Student response = new Student(resultSet);
return response;
});

How spring mvc handle responsebody and view excpetion?

I have a controller as
#Controller
#RequestMapping("/test")
public class TestController {
#RequestMapping("/1")
#ResponseBody
public String test1(){
Object o = null;
o.toString();
return "I ma test one!";
}
#RequestMapping("/2")
public String test2(){
Object o = null;
o.toString();
return "test";
}
}
Is it possible to create ControllerAdvice(s) to handle the controller method as different result without moving these to message to different classes.
I mean:
1. test1 returns a String message: if there is exception, handle it with handleError1 and return a message.
2. test1 returns a view : if there is exception, handle it with handleError2 and return/redirect to a view.
#ControllerAdvice
public class AdviceController {
#ExceptionHandler({ NullPointerException.class })
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
#ResponseBody
public Map handleError1(IllegalStateException ex, HttpServletRequest request) {
Map map = new HashMap();
map.put("code","1000");
map.put("message","NullPointerException of Object");
return map;
}
#ExceptionHandler(NullPointerException.class)
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public String handleError2(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
redirectAttributes.addFlashAttribute("code", "1000");
return "redirect:/error";
}
}
if use
#ControllerAdvice(annotations=RestController.class)
#ControllerAdvice(annotations=Controller.class)
We need to create more controllers.

Render a view based on the conditional statement in Spring

I am kind of new to Spring. I am trying to render a view based on the the value returned from DBDAOImplementation class using a conditional if statement inside processController. I am trying to return successuseraddstatus jsp file for success scenarios and faileduseraddstatus jsp file for failed scenarios.
ProcessController.java:
#RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Process process,ModelMap model) {
model.addAttribute("fname", process.getFname());
model.addAttribute("lname", process.getLname());
model.addAttribute("email", process.getEmail());
model.addAttribute("phone", process.getPhone());
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
DBDAOImp dbd =
(DBDAOImp)context.getBean("JDBCTemplate");
dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone());
if (true){ //This is where I am having trouble
return "successuseraddstatus";
}
return "faileduseraddstatus";
}
DBDAOImplementation.java:
#Override
public Boolean createuser(String fname, String lname, String email, String phone) {
isExists(email);
if (isExists==false){
String SQL = "insert into USERS (user_id,f_name,l_name,creation_date,email,phone) values (seq_users.nextval,?,?,sysdate,?,?)";
jdbcTemplateObject.update( SQL, fname,lname,email,phone);
System.out.println("Created Record");
return true;
} else {
return false;
}
}
Below if condition works. But I am not too sure if this is the right approach.
ProcessController.java:
#RequestMapping(value = "/adduserstatus", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("SpringWeb")Process process,ModelMap model) {
model.addAttribute("fname", process.getFname());
model.addAttribute("lname", process.getLname());
model.addAttribute("email", process.getEmail());
model.addAttribute("phone", process.getPhone());
DBDAOImp dbd =
(DBDAOImp)context.getBean("JDBCTemplate");
if (dbd.createuser(process.getFname(), process.getLname(), process.getEmail(), process.getPhone())){
return "useraddstatus";
} else {
return "faileduseraddstatus";
}
}

how does we enhance presistent class

AS I am new to JDO and datastore
I have set up a simple Google App Engine project based on Spring Framework to Perform Basic CRUD operation.
When I run my Application Its Show's
Persistent class "Class com.pandian.model.Customer does not seem to have been enhanced. You may want to rerun the enhancer and check for errors in the output." has no table in the database, but the operation requires it. Please check the specification of the MetaData for this class.
Customer
#PersistenceCapable
public class Customer {
#PrimaryKey
#Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
#Persistent
private String name;
#Persistent
private String email;
#Persistent
private Date date;
public Key getKey() {
return key;
}
public void setKey(Key key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Customer() {
super();
}
Controller
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAddCustomerPage(ModelMap model) {
return "add";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView add(HttpServletRequest request, ModelMap model) {
String name = request.getParameter("name");
String email = request.getParameter("email");
Customer c = new Customer();
c.setName(name);
c.setEmail(email);
c.setDate(new Date());
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(c);
} finally {
pm.close();
}
return new ModelAndView("redirect:list");
}
#RequestMapping(value = "/update/{name}", method = RequestMethod.GET)
public String getUpdateCustomerPage(#PathVariable String name,
HttpServletRequest request, ModelMap model) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Query q = pm.newQuery(Customer.class);
q.setFilter("name == nameParameter");
q.setOrdering("date desc");
q.declareParameters("String nameParameter");
try {
#SuppressWarnings("unchecked")
List<Customer> results = (List<Customer>) q.execute(name);
if (results.isEmpty()) {
model.addAttribute("customer", null);
} else {
model.addAttribute("customer", results.get(0));
}
} finally {
q.closeAll();
pm.close();
}
return "update";
}
#RequestMapping(value = "/update", method = RequestMethod.POST)
public ModelAndView update(HttpServletRequest request, ModelMap model) {
String name = request.getParameter("name");
String email = request.getParameter("email");
String key = request.getParameter("key");
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Customer c = pm.getObjectById(Customer.class, key);
c.setName(name);
c.setEmail(email);
c.setDate(new Date());
} finally {
pm.close();
}
// return to list
return new ModelAndView("redirect:list");
}
#RequestMapping(value = "/delete/{key}", method = RequestMethod.GET)
public ModelAndView delete(#PathVariable String key,
HttpServletRequest request, ModelMap model) {
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
Customer c = pm.getObjectById(Customer.class, key);
pm.deletePersistent(c);
} finally {
pm.close();
}
PMF
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
list//JSP
....
<%
if(request.getAttribute("customerList")!=null){
List<Customer> customers =
(List<Customer>)request.getAttribute("customerList");
if(!customers.isEmpty()){
for(Customer c : customers){
%>
<tr>
<td><%=c.getName() %></td>
<td><%=c.getEmail() %></td>
...
Any body help me out from this.....
When you looked at the AppEngine docs for using JDO, you would have come across
https://developers.google.com/eclipse/docs/appengine_orm
This tells you HOW to enhance classes for use with JDO.

Spring : timely/late binding of #ModelAttribute

I'm using the following code to bind the users to the model [to be used in the view/jsp]:
#ModelAttribute("users")
public Collection<User> populateUsers() {
return userService.findAllUsers();
}
But sometimes I just need to load few users with a particular Role, which I'm trying by using the following code:
int role = 2; //this is being set in a Controller within a method #RequestMapping(method = RequestMethod.GET) public String list(
#ModelAttribute("users")
public Collection<User> populateUsers() {
if(role == 2)
return userService.findAllUsersByRole(role);
else
return userService.findAllUsers();
}
but the populateUsers is always called at the start of the controller, before the role is set in list method, Could you please help me on how to set the users [something like late binding]
Regards
-- adding code
#Controller
#RequestMapping("/users")
public class UserController {
#Autowired
UserService userService;
#RequestMapping(method = RequestMethod.POST)
public String create(#Valid User user, BindingResult bindingResult,
Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
uiModel.addAttribute("user", user);
addDateTimeFormatPatterns(uiModel);
return "users/create";
}
uiModel.asMap().clear();
userService.saveUser(user);
return "redirect:/users/"
+ encodeUrlPathSegment(user.getId().toString(),
httpServletRequest);
}
#RequestMapping(params = "form", method = RequestMethod.GET)
public String createForm(Model uiModel) {
uiModel.addAttribute("user", new User());
addDateTimeFormatPatterns(uiModel);
return "users/create";
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String show(#PathVariable("id") Long id, Model uiModel) {
addDateTimeFormatPatterns(uiModel);
uiModel.addAttribute("user", userService.findUser(id));
return "users/show";
}
#RequestMapping(value = "/{id}", params = "form", method = RequestMethod.GET)
public String updateForm(#PathVariable("id") Long id, Model uiModel) {
uiModel.addAttribute("user", userService.findUser(id));
addDateTimeFormatPatterns(uiModel);
return "users/update";
}
#ModelAttribute("users")
public Collection<User> populateUsers() {
return userService.findAllUsers();
}
#ModelAttribute("userroles")
public Collection<UserRole> populateUserRoles() {
return Arrays.asList(UserRole.class.getEnumConstants());
}
void addDateTimeFormatPatterns(Model uiModel) {
uiModel.addAttribute(
"user_modified_date_format",
DateTimeFormat.patternForStyle("M-",
LocaleContextHolder.getLocale()));
}
}
#PathVariable("id") Long id is the ID I require in populateUsers, hope it is clear.
If role is in the current request, this method binding role to variable role.
#ModelAttribute("users")
public Collection<User> populateUsers(#RequestParam(required=false) Integer role) {
if(role != null && role == 2)
return userService.findAllUsersByRole(role);
else
return userService.findAllUsers();
}
Setting the model attribute in the required method has solved my issue:
model.addAttribute("users", return userService.findAllUsersByRole(role));
Thanks!

Resources