MyBatis-01MVC Development Steps and Project Application of jsp+Servlet

Keywords: Java Database xml JSP

java Naming specification

  1. Project Name: No requirement, not Chinese
  2. Package: Company Domain Name Reversal
  3. Data access layer: dao,persist,mapper
  4. Entities: entity,model,bean,javabean,pojo
  5. Business logic: service,biz
  6. Controller: controller,servlet,action,web
  7. Filter:filter
  8. Exception:exception
  9. Listener: listener
    10. Notes:
    Use Document Annotation/** on Class 1 and Method*/
    2 Use /*/or in the method//
  10. Category: Great Hump
  11. Method, Attribute: Small Hump

MVC Development Model

  1. M:Model model, entity classes and business and Dao (persistence)
  2. V:view View. JSP
  3. C:Controller controller, servlet (role: view and logic separation)
    Note: MVC - also known as JSP model 2
  4. MVC Applicable Scenario: Large-scale Project Development
  5. Illustration (from bottom to top)
    DB (database)
    DAO: Database Access Object
    Service: Business logic
    Controller
    view
    Entity classes are responsible for encapsulating data throughout the process
    The regulations are as follows:
    5.1 Design the database first (bottom of the project)
    5.2 Write entity classes first
    5.3 Persistence Layer
    5.4 Business Logic
    5.5 Controller
    5.6 View

The specific operation is as follows:

  1. Design database
create database sum DEFAULT CHARACTER set utf8;
use sum;
create table flower(
id int(10) PRIMARY key auto_increment comment 'number',
name varchar(30) not null comment 'Flower name',
price float not null comment 'Price',
production VARCHAR(30) not null comment 'Country of origin'
);
  1. Write entity classes
package com.youdian.pojo;

public class Flower {
	private int id;
	private String name;
	private double price;
	private String production;
	public Flower(int id, String name, double price, String production) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.production = production;
	}
	public Flower() {
		super();
	}
	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 double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public String getProduction() {
		return production;
	}
	public void setProduction(String production) {
		this.production = production;
	}
	
}

  1. Data access layer (persistence layer)
package com.youdian.dao;

import java.util.List;

import com.youdian.pojo.Flower;


public interface FlowerDao {
	/**
	 * All queries
	 */
	List<Flower> selAll();
	
	/**
	 *Newly added
	 */
	int insFlower(Flower flower);
}

Implementation class (need to load database driver)

package com.youdian.dao.impl;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.youdian.dao.FlowerDao;
import com.youdian.pojo.Flower;


public class FlowerDaoImpl implements FlowerDao {


	public List<Flower> selAll() {
		List<Flower> list=new ArrayList<>();//Starting with JDK 1.7, generics can be omitted
		java.sql.Connection conn=null;
		java.sql.PreparedStatement ps=null;
		ResultSet rs=null;
		
		try {
			//Database Load Driver
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:33006/sum","root","root");
			//Your own database name and account password
			ps = conn.prepareStatement("select * from flower");
			rs = ps.executeQuery();//Create a cursor pointing to a row of data
			//Currently in long connection
			
			while(rs.next()){
				list.add(new Flower(rs.getInt(1), rs.getString(2), rs.getDouble(3), rs.getString(4)));
			}
		} 
		catch (ClassNotFoundException e1) {
		e1.printStackTrace();
		}
		catch (SQLException e) {
		e.printStackTrace();
		}finally{
			try {
				rs.close();
				ps.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	} 


	public int insFlower(Flower flower) {
		return 0;
	}

}

  1. Business logic (servers)
package com.youdian.service;

import java.util.List;

import com.youdian.pojo.Flower;

public interface FlowerService {
	//Display all flower information
	List<Flower> show();
}

Implementation class

package com.youdian.service;

import java.util.List;

import com.youdian.dao.FlowerDao;
import com.youdian.dao.impl.FlowerDaoImpl;
import com.youdian.pojo.Flower;
import com.youdian.service.FlowerService;

public class FlowerServiceImpl implements FlowerService {
	private FlowerDao flowerDao = new FlowerDaoImpl();

	public List<Flower> show() {
		return flowerDao.selAll();
	}

	public int add(Flower flower) {
		return flowerDao.insFlower(flower);
	}

}

  1. Configure web.xml
    Copy web.xml from Servers to WEB-INF and modify it
    (This part can be ignored because tags are equivalent)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee               
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <!-- This one schemaļ¼ŒOne xml Document Compiler -->
    <servlet>
    	<servlet-name>ShowServlet</servlet-name>
    	<servlet-class>com.youdian.servlet.ShowServlet</servlet-class>
    </servlet>
    <!-- each servlet You can map multiple -->
    <servlet-mapping>
    	<servlet-name>ShowServlet</servlet-name>
    	<url-pattern>/show</url-pattern>
    </servlet-mapping>
    
</web-app>

Servlet

package com.youdian.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 

import com.youdian.pojo.Flower;
import com.youdian.service.FlowerService;
import com.youdian.service.impl.FlowerServiceImpl;
@WebServlet("/show")
//Equivalent configuration of web.xml files with tags after web3.0 
public class ShowServlet extends HttpServlet {
	private FlowerService flowerService =new FlowerServiceImpl();
	@Override
	protected void service(HttpServletRequest req, 
	HttpServletResponse res) 
			throws ServletException, IOException {
		List<Flower> list = flowerService.show();
		req.setAttribute("list", list);
		req.getRequestDispatcher("index.jsp").forward(req, res);
	}
}

  1. view
    There is no JSTL package in eclipse, but MyEclipse comes with it.
    index.jsp is as follows:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=utf-8">
<title>Insert title here</title>
<style type="text/css">
a{
	color:black;
	text-decoration:none;
}
a:hover{
	color:red;
}
</style>
</head>
<body>
	<table border='1'>
		<tr>
			<th>Flower Number</th>
			<th>Flower Name</th>
			<th>Price(element)</th>
			<th>Country of origin</th>
		</tr>
		<c:forEach items="${list }" var="flower">
			<tr>
			<!--  Read content from the database   -->
				<td>${flower.id }</td>
				<td>${flower.name }</td>
				<td>${flower.price }</td>
				<td>${flower.production }</td>
			</tr>
		</c:forEach>
	</table>
	<a href="add.jsp">Add Flower Information</a>
</body>
</html>

To add database content, you need to write an add.jsp:
Among them, three pieces of information must be filled in completely, and no prompt will be given and no submission will be made this time.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
//Execution after page loading is completed
//Equivalent to: window. _nl_ad = function () {} $(document). ready (function () {});
//Listen for forms - submit, listen for submit buttons - Click
$(function(){
	$("form").submit(function(){
		//Form selector: input tag type attribute value
		if($(":text:eq(0)").val()==""||$(":text:eq(1)").val()==""||$(":text:eq(2)").val()==""){
			alert("Please fill in the complete information.");
			//Prevent default behavior
			return false;
		}
	});
});
</script>
</head>
<body>
<!--  post:
		Byte stream
		2GB
		More secure
		Relative inefficiency
	get:
		Character stream
		2KB
 -->
<form action="insert" method="post">
<table border="1" align="center">
	<tr>
		<td colspan="2" style="text-align:center;font-size:30px;font-weight:bold;">
			Flower Information
		</td>
	</tr>
	<tr>
		<td><b>Flower Name:</b></td>
		<td><input type="text" name="name"/></td>
	</tr>
	<tr>
		<td><b>Flower price:</b></td>
		<td><input type="text" name="price"/></td>
	</tr>
	<tr>
		<td><b>Country of origin:</b></td>
		<td><input type="text" name="production"/></td>
	</tr>
	<tr>
		<td colspan="2" align="center">
			<input type="submit" value="Submission"/><input type="reset" value="Reset"/>
		</td>
	</tr>
</table>
</form>
</body>
</html> 

Posted by chigley on Wed, 31 Jul 2019 02:44:41 -0700