So I've been playing around with Spring Boot and it's going fairly well. However, I've found myself in a weird situation and need help with it. All of my request mapping works with exception to one, for which I'm getting a 404.
My project structure is:
+Project Name
-src/main/java - Code
-src/main/resources - Resources
-src/main/webapp/views - Jsp Pages
Important java code:
Application.java
package com.demo.faisal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.demo.faisal.model.Task;
import com.demo.faisal.service.TaskService;
#Configuration
#ComponentScan()
//#EnableAutoConfiguration
#EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner demo(TaskService taskService) {
return (args) -> {
// save a couple of customers
taskService.addTask(new Task("Learn Java"));
taskService.addTask(new Task("Learn Hibernate"));
taskService.addTask(new Task("Learn Spring"));
taskService.addTask(new Task("Learn SpringBoot"));
// fetch all tasks
log.info("Finding all tasks with getTasks():");
log.info("-------------------------------");
for (Task task : taskService.getAllTasks()) {
log.info(task.toString());
}
log.info("");
// fetch an individual customer by ID
Task task = taskService.findTask(1L);
log.info("Task found with findTask(1L):");
log.info("--------------------------------");
log.info(task.toString());
log.info("");
// fetch an individual customer by ID
task.setDescription("Learn Java Done");
log.info("Updated task description to: " + task.getDescription());
taskService.updateTask(task);
log.info("");
// Updated task
task = taskService.findTask(1L);
log.info("Updated Task (1L):");
log.info("--------------------------------");
log.info(task.toString());
log.info("");
};
}
}
Model:
package com.demo.faisal.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
//#Table(name = "${table_name})
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
public Task() {}
public Task(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return String.format("Task[id=%d, description='%s']", id, description);
}
}
Repository:
package com.demo.faisal.model;
import org.springframework.data.repository.CrudRepository;
public interface TaskRepository extends CrudRepository<Task, Long> {
}
Service:
package com.demo.faisal.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.faisal.model.Task;
import com.demo.faisal.model.TaskRepository;
#Service
public class TaskServiceImpl implements TaskService {
#Autowired
private TaskRepository taskRepository;
#Override
#Transactional
public void addTask(Task task) {
taskRepository.save(task);
}
#Override
#Transactional
public void deleteTask(Long id) {
Task task = taskRepository.findOne(id);
taskRepository.delete(task);
}
#Override
#Transactional
public void updateTask(Task task) {
Task retrieved = taskRepository.findOne(task.getId());
retrieved.setDescription(task.getDescription());
taskRepository.save(retrieved);
}
#Override
#Transactional
public Task findTask(Long id) {
return taskRepository.findOne(id);
}
#Override
#Transactional
public List<Task> getAllTasks() {
return (List<Task>) taskRepository.findAll();
}
}
MVC Config File (Replacement for web.xml):
package com.demo.faisal.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index");
}
}
Controller:
package com.demo.faisal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo.faisal.model.Task;
import com.demo.faisal.service.TaskService;
#Controller
public class TaskController {
#Autowired
private TaskService taskService;
#RequestMapping(value = "/tasks", method = RequestMethod.GET)
public ModelAndView getTasks() {
ModelAndView mav = new ModelAndView();
mav.setViewName("tasks");
List<Task> tasks = taskService.getAllTasks();
mav.addObject("tasks", tasks);
return mav;
}
#RequestMapping("/taskform")
public ModelAndView showform() {
return new ModelAndView("taskform","task",new Task());
}
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("task") Task task) {
taskService.addTask(task);;
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
#RequestMapping(value="/delete_task/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable long id) {
taskService.deleteTask(id);;
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
#RequestMapping(value="/edit_task/{id}")
public ModelAndView update(#PathVariable long id) {
Task task = taskService.findTask(id);
System.out.println("Returning taskeditform jsp with task: " + task.toString());
return new ModelAndView("taskeditform","task",task);
}
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("task") Task task) {
taskService.updateTask(task);
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
}
VIEW:
taskform.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Task</h1>
<form:form method="post" action="save" commandName="task">
<table>
<tr>
<td>Task Description :</td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
taskeditform.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Task</h1>
<form:form method="post" action="/editsave" commandName="task">
<table>
<tr>
<td>Id</td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Task Description :</td>
<td><form:input path="desciption" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
tasks.jsp
<%# page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Tasks List</h1>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<table border="2" width="70%" cellpadding="2">
<tr>
<th>Id</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="task" items="${tasks}">
<tr>
<td>${task.id}</td>
<td>${task.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
<br />
Add New Task
From my controller, all of my RequestMappings work fine, except /edit_task/{id}.
Everytime I call this url, I hit the breakpoint and can see it returning a new ModelAndView with the view pointing to taskeditform.jsp
However, I get a 404 error saying it cannot find the view. The error message is below:
type Status report
message /edit_task/WEB-INF/pages/taskeditform.jsp
description The requested resource is not available.
What I don't understand is the URL it's looking for : /edit_task/WEB-INF/pages/taskeditform.jsp. It looks like it is using the request mapping url and appending the view to it.
Can someone please point out what's going on here?
Thanks.
Related
--> when i am Updating it was not saving the entered details insted it was saving null. when deleting it throws error.
DataBase : restonetoone
application.properties
/*****************************/
crm.rest.url=http://localhost:8080/restonetoone/api/details
-->when i use to update it was taking null value insted of inserted data.
Details [id=25, city=null, mobileno=0, student=Student [id=25, name=null, clas=0]]
->when i was deleting it throws this error.
Mar 06, 2021 4:09:53 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping for GET /restclient/student/delete
the Details.java class Onetoone with student.java class
Details.java
/******************/
package com.rest.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="details")
public class Details {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private long mobileno;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="student_id")
private Student student;
public Details(){
}
public Details(int id, String city, long mobileno, Student student) {
super();
this.id = id;
this.city = city;
this.mobileno = mobileno;
this.student = student;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
#Override
public String toString() {
return "Details [id=" + id + ", city=" + city + ", mobileno=" + mobileno + ", student=" + student + "]";
}
}
student.java class
Student.java
/******************/
package com.rest.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
private int clas;
public Student() {
}
public Student(int id, String name, int clas) {
super();
this.id = id;
this.name = name;
this.clas = clas;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getClas() {
return clas;
}
public void setClas(int clas) {
this.clas = clas;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", clas=" + clas + "]";
}
}
DetailsServImpl.java class(service layers)
DetailsServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
#Service
public class DetailsServImpl implements DetailsServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public DetailsServImpl(RestTemplate theRestTemplate,
#Value("${crm.rest.url}") String theUrl) {
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Details> getDetails() {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Details>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Details>>() {});
// get the list of customers from response
List<Details> theDetails = responseEntity.getBody();
logger.info("in getDetails(): details" + theDetails);
return theDetails;
}
#Override
public Details getDetails(int theId) {
logger.info("in getDetails(): Calling REST API " + crmRestUrl);
// make REST call
Details theDetails =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Details.class);
logger.info("in saveDetails(): theDetails=" + theDetails);
return theDetails;
}
#Override
public void saveDetails(Details theDetails) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int detailsId = theDetails.getId();
// make REST call
if (detailsId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theDetails, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theDetails);
}
logger.info("in saveDetails(): success");
}
#Override
public void deleteDetails(int theId) {
logger.info("in deleteDetails(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteDetails(): deleted Details theId=" + theId);
}
}
StudentServImpl.java class
StudentServImpl.java
/******************/
package com.rest.service;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.rest.entity.Details;
import com.rest.entity.Student;
#Service
public class StudentServImpl implements StudentServ {
private RestTemplate restTemplate;
private String crmRestUrl;
private Logger logger = Logger.getLogger(getClass().getName());
#Autowired
public StudentServImpl(RestTemplate theRestTemplate,#Value("${crm.rest.url}") String theUrl){
restTemplate = theRestTemplate;
crmRestUrl = theUrl;
logger.info("Loaded property: crm.rest.url=" + crmRestUrl);
}
#Override
public List<Student> getStudent() {
logger.info("in getCustomers(): Calling REST API " + crmRestUrl);
// make REST call
ResponseEntity<List<Student>> responseEntity =
restTemplate.exchange(crmRestUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<Student>>() {});
// get the list of customers from response
List<Student> theStudent = responseEntity.getBody();
logger.info("in getCustomers(): customers" + theStudent);
return theStudent;
}
#Override
public void saveStudent(Student theStudent) {
logger.info("in saveSt(): Cudentalling REST API " + crmRestUrl);
int studentId = theStudent.getId();
// make REST call
if (studentId == 0) {
// add employee
restTemplate.postForEntity(crmRestUrl, theStudent, String.class);
} else {
// update employee
restTemplate.put(crmRestUrl, theStudent);
}
logger.info("in saveStudent(): success");
}
#Override
public Student getStudent(int theId) {
logger.info("in getCustomer(): Calling REST API " + crmRestUrl);
// make REST call
Student theStudent =
restTemplate.getForObject(crmRestUrl + "/" + theId,
Student.class);
logger.info("in saveCustomer(): theCustomer=" + theStudent);
return theStudent;
}
#Override
public void deleteStudent(int theId) {
logger.info("in deleteStudent(): Calling REST API " + crmRestUrl);
// make REST call
restTemplate.delete(crmRestUrl + "/" + theId);
logger.info("in deleteStudent(): deleted Student theId=" + theId);
}
}
Now the controller class(here i am using single controller for multiple entites).
ClientController.java
/******************/
package com.rest.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.rest.entity.Details;
import com.rest.entity.Student;
import com.rest.service.DetailsServ;
import com.rest.service.StudentServ;
#Controller
#RequestMapping("/cont")
public class ClientController {
#Autowired
private DetailsServ detailsServ;
#Autowired
private StudentServ studentServ;
#GetMapping("/showForm")
public String showForm(Model theModel){
Details theDetails = new Details();
Student theStudent = new Student();
theDetails.setStudent(theStudent);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#PostMapping("/saveForm")
private String saveForm(#ModelAttribute("for") Details theDetails) {
detailsServ.saveDetails(theDetails);
return "redirect:/cont/list";
}
#GetMapping("/list")
public String showList(Model theModel) {
List<Details> theDetails = detailsServ.getDetails();
theModel.addAttribute("details", theDetails);
return "list-table";
}
#GetMapping("/update")
public String updateDetails(#RequestParam("detailsId") int theId, Model theModel) {
Details theDetails =detailsServ.getDetails(theId);
theModel.addAttribute("for",theDetails);
return "the-for";
}
#GetMapping("/delete")
public String deleteDetails(#RequestParam("detailsId") int theId) {
detailsServ.deleteDetails(theId);
return "redirect:/cont/list";
}
}
I use this form for both saving and updating.
the-for.jsp
/******************/
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Save Customer</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/style.css">
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>
<body>
<div id="wrapper">
<div id="header">
<h2>Form</h2>
</div>
</div>
<div id="container">
<h3>Save StudentDetails</h3>
<form:form action="saveForm" modelAttribute="for" method="POST">
<!-- need to associate this data with customer id -->
<form:hidden path="id" />
<table>
<tbody>
<tr>
<td><label>City name:</label></td>
<td><form:input path="city" /></td>
</tr>
<tr>
<td><label>mobileno:</label></td>
<td><form:input path="mobileno" /></td>
</tr>
<tr>
<td><label>name:</label></td>
<td><form:input path="student.name" /></td>
</tr>
<tr>
<td><label>class:</label></td>
<td><form:input path="student.clas" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save" class="save" /></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear; both;"></div>
<p>
Back to List
</p>
</div>
</body>
</html>
Now the table which shows the CRUD dynamically.
list-table.jsp
/******************/
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>List</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2 class="pt-2">Student Manager</h2>
<!-- put new button: Add Student -->
<input type="button" value="Add Student"
onclick="window.location.href='showForm'; return false;"
class="btn btn-primary btn-sm mb-3" />
<!-- add our html table here -->
<table class="table table-bordered table-striped">
<thead class="table-dark">
<tr>
<th>city</th>
<th>mobileno</th>
<th>name</th>
<th>class</th>
<th>Action</th>
</tr>
</thead>
<!-- loop over and print our students -->
<tbody>
<c:forEach var="tempDetails" items="${details}">
<!-- construct an "update" link with student id -->
<c:url var="updateLink" value="/cont/update">
<c:param name="detailsId" value="${tempDetails.id}" />
</c:url>
<!-- construct an "delete" link with student id -->
<c:url var="deleteLink" value="/student/delete">
<c:param name="studentId" value="${tempStudent.id}" />
</c:url>
<tr>
<td>${tempDetails.city}</td>
<td>${tempDetails.mobileno}</td>
<td>${tempDetails.student.name}</td>
<td>${tempDetails.student.clas}</td>
<td>
<!-- display the update link -->
Update
|
<a href="${deleteLink}"
onclick="if (!(confirm('Are you sure you want to delete this student?'))) return false">Delete</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
For more clearity sake i am shering the link of my project which include Both client side and backend code files with database.
LINK( https://drive.google.com/file/d/128pvCd6bYdCNhOiG6ERRXbPRUlnhZlTp/view?usp=sharing )
## i am now coading on eclipse java-ee , in curd mvc program i have generated four methods all are working except update method while compiling i can able to read data but when i am updateing i got error 400 ,i have given my controller and dao classes ##
## my controller ##
----------
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.``ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import dao.UserDaoImpl;
import model.User;
#Controller
public class Firstcontroller {
#Autowired
UserDaoImpl userDao;
#RequestMapping(value="/add")
public ModelAndView redirectUser()
{
ModelAndView m=new ModelAndView("add");
return m;
}
#RequestMapping(value="/table")
public ModelAndView viewUser()
{
List<User> list=userDao.viewUsers();
return new ModelAndView("All_User","list",list);
}
#RequestMapping(value="/register",method=RequestMethod.POST)
public ModelAndView processSaveUser(#ModelAttribute User user)
{
if(userDao.saveUser(user))
{
ModelAndView m=new ModelAndView("login","response","Successfully Registered");
return m;
}
ModelAndView m1=new ModelAndView("signup","response","Failed Registeration");
return m1;
}
#RequestMapping(value="deleteuser/{id}" ,method = RequestMethod.GET)
public ModelAndView deleteuser(#PathVariable int id)
{
userDao.delete(id);
return new ModelAndView("redirect:/table");
}
#RequestMapping(value="/edituser/{id}")
public ModelAndView edit(#PathVariable int id){
User user=userDao.getUserById(id);
return new ModelAndView("edituser","command",user);
}
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView edituser(#PathVariable String id){
System.out.println("Got In");
//userDao.update(user);
return new ModelAndView("redirect:/table");
}
}
and my dao is
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import handler.UserRowMapper;
import model.User;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemp;
public void setJdbcTemp(JdbcTemplate jdbcTemp) {
this.jdbcTemp = jdbcTemp;
}
public boolean saveUser(User user) {
String sql_query="INSERT INTO userdata (username,password) VALUES (?,?)";
int x=jdbcTemp.update(sql_query,user.getLunm(),user.getLpwd());
if(x>0)
{
return true;
}
return false;
}
public List<User>viewUsers()
{
return jdbcTemp.query("select * from userdata",new RowMapper<User>()
{
public User mapRow(ResultSet rs,int row)throws SQLException
{
User u=new User();
u.setId(rs.getInt(1));
u.setLunm(rs.getString(2));
u.setLpwd(rs.getString(3));
return u;
}
}
);
}
public User getUserById(int id)
{
String sql="select * from userdata where id=?";
return (User)jdbcTemp.queryForObject(sql,new Object[]{id},new UserRowMapper());
}
public int delete(int id)
{
String sql="delete from userdata where id=?";
int x=jdbcTemp.update(sql,id);
if(x>0)
{
return(x);
}
return (0);
}
public int update(User user)
{
String sql="update userdetails set username=? and password=? where id=?";
return jdbcTemp.update(sql,user.getLunm(),user.getLpwd(),user.getId());
}
}
EditUser.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page isELIgnored="false" %>
<h1>Edit User</h1>
<h1>${command.id }</h1>
<form:form method="POST" action="save?id=${command.id }">
<table >
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Username : </td>
<td><form:input path="lunm" /></td>
</tr>
<tr>
<td>password :</td>
<td><form:input path="lpwd" /></td>
<tr>
<td> </td>
<td><input type="submit" value="Edit" /></td>
</tr>
</table>
</form:form> [ this is my error msg][1]
getting the values from table
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView edituser(#PathVariable String id){
System.out.println("Got In");
//userDao.update(user);
return new ModelAndView("redirect:/table");
}
if above code is for Store updated username and password means change #PathVariable into #ModelAttribute User user
for Example:
#RequestMapping(value="edituser/save",method = RequestMethod.POST)
//#RequestMapping(value="/save",method=RequestMethod.PUT)
public ModelAndView edituser(#ModelAttribute User user){
System.out.println("Got In");
userDao.update(user);
return new ModelAndView("redirect:/table");
}
different table names are there
public int delete(int id)
{
String sql="delete from userdata where id=?";
int x=jdbcTemp.update(sql,id);
if(x>0)
{
return(x);
}
return (0);
}
public int update(User user)
{
String sql="update userdata set username=?,password=? where id=?";
return jdbcTemp.update(sql,user.getLunm(),user.getLpwd(),user.getId());
}
this is my index page:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Employee List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Name</th><th>Address</th>
<th>City</th><th>Cars</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.name }</td>
<td>${emp.address }</td>
<td>${emp.city }</td>
<td>${emp.cars}</td>
<td>Edit
<td>Delete
</tr></c:forEach>
</table>
Add New Employee"
problem is when i click on other link than it works fine but when i click on editemp or deleteemp link,than it shows me error:The requested resource is not available
This is my controller class:
package first;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmpController {
#Autowired
EmployeeDao dao;
#RequestMapping("/empform")
public ModelAndView showForm()
{
return new ModelAndView("empform","command",new Employee());
}
#RequestMapping(value="/save",method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Employee employee)
{
dao.saveEmployee(employee);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/viewemp")
public ModelAndView viewemp()
{
List<Employee> list=dao.getAllEmployee();
return new ModelAndView("viewemp","list",list);
}
#RequestMapping(value="/editemp/{name}",method=RequestMethod.GET)
public ModelAndView edit(#PathVariable String name)
{
Employee e=dao.getbyName(name);
return new ModelAndView("empeditform","command",e);
}
#RequestMapping(value="/saveedit",method=RequestMethod.POST)
public ModelAndView saveedit(#ModelAttribute("emp")Employee employee)
{
dao.updateEmployee(employee);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping(value="/deleteemp/{name}",method=RequestMethod.GET)
public ModelAndView delete(#PathVariable String name)
{
dao.delete(name);
return new ModelAndView("redirect:/viewemp");
}
}
Please tell me,why it is unable to map with controller method specified in controller class.....thanks in advance
One thing to try for your links to to update them to use the context path:
<td>Edit
<td>Delete
This post has a few other ways that you can specify your routes in a jsp page:
[How to use relative paths without including the context root name?
Also, for the controller routes to be registered, you will need to set component scan to look for any annotations:
<context:component-scan base-package="namespace to controller class" />
so I am working in a Spring MVC project where I have this class with a few Date fields and I am creating a CRUD for it. Problem is, I read an instance of the class from the database and then send it to the view for editing, and although I am not manipulating any of the Date fields, only the strings, when I collect the object using a post form, the Date fields come as null even though they came from the database with a value and I sent them to the view with that value.
The class:
package com.sophos.mat.beans;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import org.hibernate.validator.constraints.Length;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name="IN_PROYECTO")
#GeneratedValue(strategy=GenerationType.AUTO, generator="SECUENCIA_IN_PROYECTO")
#SequenceGenerator(name="SECUENCIA_IN_PROYECTO", sequenceName="SECUENCIA_IN_PROYECTO", allocationSize=1, initialValue= 1)
private long id;
#Column(name="VC_NOMBRE")
#Length(max = 50, message = "El campo no puede exceder los 50 caracteres")
private String nombre;
#Column(name="VC_DESCRIPCION")
#Length(max = 200, message = "El campo no puede exceder los 200 caracteres")
private String descripcion;
#Column(name="VC_CODIGO_SOPHOS")
#Length(max = 20, message = "El campo no puede exceder los 20 caracteres")
private String codigoSophos;
#Column(name="DT_FECHACREACION")
private Date fechaCreacion;
#Column(name="VC_USUARIOACTUALIZACION")
private String usuarioActualizacion;
#Column(name="DT_FECHAACTUALIZACION")
private Date fechaActualizacion;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getCodigoSophos() {
return codigoSophos;
}
public void setCodigoSophos(String codigoSophos) {
this.codigoSophos = codigoSophos;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public String getUsuarioActualizacion() {
return usuarioActualizacion;
}
public void setUsuarioActualizacion(String usuarioActualizacion) {
this.usuarioActualizacion = usuarioActualizacion;
}
public Date getFechaActualizacion() {
return fechaActualizacion;
}
public void setFechaActualizacion(Date fechaActualizacion) {
this.fechaActualizacion = fechaActualizacion;
}
}
The controller:
package com.sophos.mat.controller;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sophos.mat.beans.Proyecto;
import com.sophos.mat.services.IProyectoService;
#Controller
public class ProyectoController {
#Autowired
private IProyectoService proyectoService;
#RequestMapping(value = "/editarproyecto/{id}", method = RequestMethod.GET)
public String editarProyectoGet(ModelMap model, #PathVariable long id){
try {
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
model.put("proyectoData", proyectoData);
return "editarproyecto";
} catch (Exception e) {
e.printStackTrace();
return "redirect:/proyectos";
}
}
#RequestMapping(value="/editarproyecto/{id}", method = RequestMethod.POST)
public String editarProyectoPost(ModelMap model, #PathVariable long id, #ModelAttribute("proyectoData")#Valid Proyecto proyectoData, BindingResult result){
if(result.hasErrors()){
return "editarproyecto";
}
try{
proyectoData.setFechaActualizacion(new Date());
proyectoService.actualizarProyecto(proyectoData);
return "redirect:/proyectos";
}catch(Exception e){
e.printStackTrace();
return "redirect:/proyectos";
}
}
public IProyectoService getProyectoService() {
return proyectoService;
}
public void setProyectoService(IProyectoService proyectoService) {
this.proyectoService = proyectoService;
}
}
And the view: editarproyecto.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib uri= "http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<title>>Nuevo Proyecto</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<h1>Nuevo Proyecto</h1>
<form:form method="post" modelAttribute="proyectoData">
<table >
<tr>
<td align="right">
Nombre proyecto:
</td>
<td>
<form:input path="nombre"/>
</td>
<td>
<form:errors path="nombre" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Descripción
</td>
<td>
<form:input path="descripcion"/>
</td>
<td>
<form:errors path="descripcion" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Cód. Sophos
</td>
<td>
<form:input path="codigoSophos"/>
</td>
<td>
<form:errors path="codigoSophos" cssClass="error"/>
</td>
</tr>
<tr>
<td align="right">
Usuario que actualiza
</td>
<td>
<form:input path="usuarioActualizacion"/>
</td>
<td>
<form:errors path="usuarioActualizacion" cssClass="error"/>
</td>
</tr>
</table>
<br>
<input type="submit" value="Guardar">
</form:form>
Proyectos
</body>
</html>
When processing POST, I get an exception from hibernate telling me that I'm trying to update to NULL the column 'DT_FECHACREACION' corresponding to the class field 'fechaCreacion'. As a temporary fix, I had to add in the POST method a query to the database to reset 'fechaCreacion' back to its previous value which I don't want to change and then update the entity with the rest of the captured values. That works but is ugly af and adds extra and unwanted overhead. My database is Oracle 11g. Thanks in advance folks!
PD: Very newbie spring developer, am in my internship and trying my best to get a full contract when the internship is over :D so any help will be much appreciated.
When you call the service you have to control which fields you return to the view.
Proyecto proyectoData = proyectoService.buscarProyectoPorId(id);
You can omit fields your DAO is returning with #JsonIgnore annotation.
....
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="T_PROYECTOS")
public class Proyecto implements Serializable{
...
#JsonIgnore
public Date getFechaCreacion() {
return fechaCreacion;
}
....
}
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<div align="center" style="margin-top:100px;">
<font face="verdana" size="2">
${welcomeMessage} <BR><BR>
${result}
<form:form action="${pageContext.request.contextPath}/login.html" method="POST" modelAttribute="loginForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Login</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /> <form:errors path="username"></form:errors></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /> <form:errors path="password"></form:errors></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" style="background-color:white;" /></td>
</tr>
</table>
</form:form>
Register if not already registered
</font>
</div>
</body>
</html>
HelloController.java
package java4s;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java4s.model.Login;
#Controller
public class LoginSuccessController {
#Autowired
EmployeeService emp_service;
#RequestMapping(value = "/login", method=RequestMethod.POST)
public ModelAndView loginvalidateForm(ModelMap model, #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
if(result.hasErrors()){
model.addAttribute("result", "All Fields are neccessary");
return new ModelAndView("index",model);
}
if(emp_service.validateLogin(login.getUsername(), login.getPassword()))
{
List<Employee> user_info = emp_service.getUserinfo(login.getUsername());
session.setAttribute("session_username", login.getUsername()); //Add value to session variable
model.addAttribute("result", "Login Success");
model.addAttribute("user_info", user_info);
return new ModelAndView("LoginSuccess",model);
}
else
{
model.addAttribute("result", "Login Failure");
return new ModelAndView("index",model);
}
}
}
Login.java
package java4s.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Login {
#NotNull
#Size(min = 3, max = 20)
private String username;
#NotNull
#Size(min = 3, max = 20)
private String password;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
I am trying to put validation on the login fields when they are empty, but errors are not showing on the index page the the login fields are empty. What is the problem in the code?
You have to add the annotation #Valid ( see the spring doc for more details) :
public ModelAndView loginvalidateForm(ModelMap model, #Valid #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
....
}
Don't forget to enable “mvc:annotation-driven” to make Spring MVC supports #Valid annotation.
Add the following tag to your application context XML file.
<mvc:annotation-driven />