s11 MVC

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 8

MVC Architecture

-- it consist of 3 layer architecture


View (UI) -
fronted code like html, jsp, we can develop view layer

Controller(Mediator) :
It reads the data from view Layer
It gives it to the Model layer

Model :
it takes data from controller and data back from model layer gives it back to view
layer.

exa:view data int 10,20 ,,, controller take data and give to model perform add
logic it return baack to controller and view

advantages of mvc
--
when we are working with big project then 1000's of html file
1000's database line code then thigs become so difficult.
-- i want html page in one place, controller file one place
-- easy to find the file
-----------
app.prop
--
spring.datasource.url=jdbc:mysql://localhost:3306/crud_demo1
spring.datasource.username=root /postgres
spring.datasource.password=root
spring.jpa.show-sql=true // hibernate will write the sql query
----
****************
first web development project
============
spring web --- internally mvc architecture
------
step 1 : create spriing boot project with mysql/postgresql jar, spring data
jpa,spring web
step 2: create database table with forward engineering
step 3: create entity class
step 4: create repository layer
step 5: configure app.prop file
-------
create database marketing_db_1 / crud_demo1 ;
not create table
---
com.marketiing.entity
--
@Entity
@Table(name="leads")
class Lead{

@Id
@GeneratedValue(strategy = generatedType.IDENTITY)
private long id;

@Column(name="first_name, length=45,nullable=false)
private String firstName;
@Column(name="last_name, length=45,nullable=false)
private String lastName;

@Column(name="email, length= 128 , nullable = false, unique=true)


private String email;

@Column(name="mobile, length= 10, nullable= false, unique=true)


private long mobile;

//getter and setter


-------------
package com.marketingapp.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.marketingapp.entity.Lead;
public interface LeadRepository extends JpaRepository<Lead, Long>{
}
----
spring.application.name=marketingapp

spring.datasource.url=jdbc:mysql://localhost:3306/crud_demo1
spring.datasource.username=postgres
spring.datasource.password=root

#create a table
spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.dialect =org.hibernate.dialect.MySQL5InnoDbDialect
#console sql query
spring.jpa.show-sql=true
******************************************************************
jsp -> controller -> model/service -> repository -> entity -> db
===============
maven dependency
src/main/webapp/WEB-INF/jsps
Create_Lead.jsp
----
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>create</title>
</head>
<body>
<h2>Lead</h2>
</body>
</html>
------------
com.marketing.controller

LeadController
--------
@Controller
LeadController
--
// http://localhost:8080/create

@RequestMapping("/create)
public String method(){
return "Create_Lead";

# View Resolver Configuration for JSP


spring.mvc.view.prefix=/WEB-INF/jsps/
spring.mvc.view.suffix=.jsp
----------
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

================================
=------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>create</title>
</head>
<body>
<h2>Create Lead</h2>
<form action="saveReg" method="post">
<pre>
First Name <input type="text" name="firstName" />
Last Name <input type="text" name="lastName" />
Email <input type="text" name="email" />
Mobile <input type="text" name="mobile" />
<input type="submit" value="save" />
</pre>
</form>
</body>
</html>
--------
@RequestMapping("/saveReg")
public String saveLead(@ModelAttribute Lead lead) { // bind form data to this
method
System.out.println(lead.getFirstName());
System.out.println(lead.getLastName());
System.out.println((lead.getEmail()));
System.out.println(lead.getMobile());
return "Create_Lead";
}
---------
com.marketing.service -> LeadService(interface) and LeadServiceImpl
---
package com.marketingapp.service;
import com.marketingapp.entity.Lead;
public interface LeadService {
public void saveLead(Lead lead);
}
---
package com.marketingapp.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.marketingapp.entity.Lead;
import com.marketingapp.repository.LeadRepository;
@Service
public class LeadServiceImpl implements LeadService{
@Autowired
private LeadRepository leadrepo;
@Override
public void saveLead(Lead lead) {
leadrepo.save(lead);
}
}
---------
@Controller
public class LeadController {

@Autowired
private LeadService leadservice; // new LeadServiceImpl

// http://localhost:8080/create
@RequestMapping("/create")
public String index() {
return "Create_Lead"; }

approach : 1
@RequestMapping("/saveReg")
public String saveLead(@ModelAttribute Lead lead) { // bind form data to this
method
leadservice.saveLead(lead);
return "Create_Lead"; } }
******************
approach : 2
--
@RequestMapping("/saveReg")
public String saveLead(
@RequestParam("first") String firstName,
@RequestParam("last") String lastName,
@RequestParam("email") String email,
@RequestParam("mobile") long mobile) {
Lead lead = new Lead();
lead.setFirstName(firstName);
lead.setLastName(lastName);
lead.setEmail(email);
lead.setMobile(mobile);
leadservice.saveLead(lead);
return "Create_Lead";
}
-------
approach : 3 (data transfer object)
---com.marketing.dto -> LeadDto (fields as per the form)
package com.marketingapp.dto;
public class LeadDto {
private long id;
private String firstName;
private String lastName;
private String email;
private long mobile;
public long getId() {
return id;
//getter and setter
}
----
@RequestMapping("/saveReg")
public String saveLead(
LeadDto leadDto) {
Lead lead = new Lead();
lead.setFirstName(leadDto.getFirstName());
lead.setLastName(leadDto.getLastName());
lead.setEmail(leadDto.getEmail());
lead.setMobile(leadDto.getMobile());
leadservice.saveLead(lead);
return "Create_Lead";
}

******************
==================
//http://localhost:8080/listall
@RequestMapping("/listall")
public String listAllLeads(ModelMap model) {
List<Lead> listLeads = leadservice.listLeads();
model.addAttribute("leads", listLeads);
return "search_results";
}
---------
public List<Lead> listLeads();
------
@Override
public List<Lead> listLeads() {
List<Lead> findAll = leadrepo.findAll();
return findAll;
}
-----------
**********************
================================
jstl msg and retrieve a record
--here we have add dependency and jstl tag
--------------
### wrong taglib <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<dependency>
<groupId>jakarta.servlet.jsp.jstl</groupid>
<artifactid>jakarta.servlet.jsp.jstl-api</>
</dependency>

<dependency>
<groupId>org.eclipse.jetty</groupid>
<artifactid>glassfish-jstl</>
<version>11.0.12</version>
</dependency>
------------
approach : 1
@RequestMapping("/saveReg")
public String saveLead(@ModelAttribute Lead lead,Model model) {
// bind form data to this method also we use ModelMap/Mode
leadservice.saveLead(lead);
model.addAttribute("msg","Record is
save!"); //act like a setattribute
return "Create_Lead";
}
--------------
//http://localhost:8080/listall
@RequestMapping("/listall")
public String listAllLeads(ModelMap model) {
List<Lead> listLeads = leadservice.listLeads();
model.addAttribute("leads", listLeads);
return "search_results";
}
-------------
search_results.jsp
-----------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>All Leads</title>
</head>
<body>
<table border=1>
<tr><th colspan="7" bgcolor="lightgrey"><font size="6"> LIST OF LEADS
</font></th></tr>
<tr bgcolor="lightgrey">
<th>Id No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Mobile</th>
<th colspan="2">Action</th>
</tr>
<c:forEach var="leads" items="${allleads}">
<tr><td style="text-align:center"> ${leads.id} </td>
<td> ${leads.firstName} </td>
<td>${leads.lastName}</td>
<td>${leads.email}</td>
<td>${leads.mobile}</td>
<td><a href="delete?id=${leads.id}">
<input style="background-color:mistyrose; color:darkred" type="submit"
value="Delete">
</a></td>
<td><a href="update?id=${leads.id}">
<input style="background-color:lightcyan; color:darblue" type="submit"
value="Update">
</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
******************************************
/read data from view
--------------------------
===========================
@RequestMapping("/delete")
public String deleteOneLead(@RequestParam ("id") long id, ModelMap model) {
leadservice.deleteLeadById(id);
List<Lead> leads = leadservice.listLeads();
model.addAttribute("allleads", leads);
return "leadSearchResult"; //After delete stay on the same page
}

@RequestMapping("/update")
public String updateOneLead(@RequestParam ("id") long id, ModelMap model) {
Lead lead = leadservice.getOneLead(id);
model.addAttribute("leadUpd", lead);
return "updateLead";
}
---------------
public void deleteLeadById(long id);
public Lead getOneLead(long id);
---------
@Override
public void deleteLeadById(long id) {
leadrepo.deleteById(id); // To delete data from the database
}

@Override
public Lead getOneLead(long id) {
Optional<Lead> findById = leadrepo.findById(id); // findrecord by ID#
in the database
Lead lead = findById.get();
return lead;
}
----------------
//update the data in the database. (LeadController.java)
@RequestMapping("/updateLead")
//Using DTO Method to update Lead data as we don't have entity class here
public String updateOneLeadData(LeadDto data, ModelMap model) {
Lead ld = new Lead();
ld.setId(data.getId());
ld.setFirstName(data.getFirstName());
ld.setLastName(data.getLastName());
ld.setEmail(data.getEmail());
ld.setMobile(data.getMobile());
leadservice.saveLead(ld);
List<Lead> leads = leadservice.listLeads();
model.addAttribute("allleads", leads);
return "search_results";
}

----------------------
<%@ include file="Menu.jsp" %>

---
add into the all jsp pages
---------
create Menu.jsp
-------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<h1> Welcome to Spring MVC</h1>
<hr>
<a href="createlead"> <input type="button" value="Create Lead"> </a>
<a href="listAll"> <input type="button" value="List of All Leads"> </a>
<hr>
</body>
</html>
***************************

You might also like