java web development step - tomcat

Keywords: SQL Database Java xml

java web development process - tomcat

1. Setting up servers server (tomcat)

  • Operational steps: servers - > New - > server - > Apache - > Tomcat 7.0 - > next - > Tomcat Install Location - > Borwse (select the location of tomcate) - - > next - > finish - > you will see a server below the upper servers.

2. Creating Dynamic Engineering

  • Action steps: file -> new -> Dynamic web Project -> project name -> finish

3. Add web.xml file to WEB-INF

  • <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false" version="3.0"> <absolute-ordering/> <display-name>MyfirstProject</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

4. Import the relevant jar package and JSTL package (el/jstl) of the database into the lib file and build the path.

  • ** Operational steps: ** Select all imported packages, right-click -> build path -> add to...
  • Relevant jar packages
Mysql-connector-java-5.1.4.0 (XXXXXX) -bin.jar (database driver)
Druid-1.0.1.5.jar
 Commons-dbutils-1.8.3.jar (used with Druid Connection Pool)
Commons-beanutils-1.8.3.jar
 commons-logging-1.1.1.jar (print log)

5. Create packages in src

  • domain: Mapping fields in the database
  • Web: The servlet layer (creating servlets, retaining service methods) handles exceptions and transmits the processed results to the jsp of the response.
  • service Layer Function: Transfer data in the middle and judge the returned results accordingly. If the data returned is wrong, the exception is thrown directly to the web layer.
  • dao layer: query data from service layer and get results (connect database, execute sql statement, return results, return results, and throw exception s up)
  • Add the package of db.proprerties database to the src file directory.
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mystore?useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true
username=User name
password=Password
maxActive=maximum connection
  • Utl package: Get database connection information from db.properties, create data sources, and close data sources (connection, preparestatement, resultset). Create jdbcUtil.java in the package (code below).
package com.helong.util;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JdbcUtil {

	public static DataSource ds = null;
	static {
		try {
			//1. Loading configuration files
			Properties p = new Properties();
			//Get the bytecode directory
			String path = JdbcUtil.class.getClassLoader().getResource("db.properties").getPath();
			FileInputStream in = new FileInputStream(path);
			p.load(in);
			//ds = BasicDataSourceFactory.createDataSource(p);
			ds = DruidDataSourceFactory.createDataSource(p);
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	//Getting data sources
	public static DataSource  getDataSource() {
		return ds;
	}
	public static Connection getConn() {
		try {
			// 2. Connecting to the database
			return ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * close resource 
	 */
	public static void close(Connection conn,Statement st,ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {

				e.printStackTrace();
			}
		}
		if (st != null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}

6. Create tables in the database (specify requirements)

7. Immediately after the creation, the same table name class in damain is created according to the field name in the database, and the relationship mapping is done well.

[Note: The field name is wrapped with a wrapper class and is private ly modified. No other class calls are allowed. It conforms to the javabean specification (creating set and get methods)]

package com.helong.domain;

public class Goods {
	private Integer id;
	private String name;
	private Double price;
	private String image;
	private String gdesc;
	private Integer is_hot;
	private Integer cid;
	public Integer getId() {
		return id;
	}
	public void setId(Integer 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 getImage() {
		return image;
	}
	public void setImage(String image) {
		this.image = image;
	}
	public String getGdesc() {
		return gdesc;
	}
	public void setGdesc(String gdesc) {
		this.gdesc = gdesc;
	}
	public Integer getIs_hot() {
		return is_hot;
	}
	public void setIs_hot(Integer is_hot) {
		this.is_hot = is_hot;
	}
	public Integer getCid() {
		return cid;
	}
	public void setCid(Integer cid) {
		this.cid = cid;
	}
	@Override
	public String toString() {
		return "Goods [id=" + id + ", name=" + name + ", price=" + price + ", image=" + image + ", gdesc=" + gdesc
				+ ", is_hot=" + is_hot + ", cid=" + cid + "]";
	}
	
}

8. Create corresponding classes for manipulating the table at the web layer, service layer and dao layer, respectively.

  • Naming specifications:
    - web layer: table name + Servlet.java
    - service Layer: Indicate / Module + Service.java
    - dao layer: table name / module + Dao.java
  • Dao level:
    - It establishes the operation of tables, such as adding, deleting, modifying and checking.
//Connect to the database (get the data source)
	private QueryRunner qr = new QueryRunner(JdbcUtil.getDataSource());
	
	
	//1. Query the list of all goods from the database
	public List<Goods> getAllGoods() throws Exception{
		//1. Query operation
		String sql = "select * from goods";
		//2) implementation of sql
		List<Goods> allGoods = qr.query(sql, new BeanListHandler<Goods>(Goods.class));
		return allGoods;
	}
	
	//2. Add merchandise to database
	public void addGoods(Goods goods) throws Exception {
		//1. Insert operation
		String sql = "insert into goods(name,price,image,gdesc,is_hot,cid) value(?,?,?,?,?,?)";
		qr.update(sql, goods.getName(),goods.getPrice(),goods.getImage(),goods.getGdesc(),goods.getIs_hot(),goods.getCid());
	}
	
	//3. Delete a commodity from the database according to id
	public void delGoods(int id) throws Exception {
		//1. Delete operation
		String sql = "delete from goods where id=?";
		qr.update(sql,id);
	}
	
	//4. Pass in an object, go to the database to update according to the object, go to the database to update according to the id.
	public void uodateGoods(Goods goods) throws Exception {
		//1. Update operation
		String sql = "update goods set name=?,price=?,image=?,gdesc=?,is_hot=?,cid=? where id=?";
		qr.update(sql,goods.getName(),goods.getPrice(),goods.getImage(),goods.getGdesc(),goods.getIs_hot(),goods.getCid(),goods.getId());
	}
	
	//Query a commodity based on id
	public Goods getGoodsWithId(String id) throws Exception {
		//1. Query operation
		String sql = "select * from goods where id=?";
		Goods goods = qr.query(sql,new BeanHandler<Goods>(Goods.class),Integer.parseInt(id));
		return goods;
	}
  • web level
    - First extract a base class (so that it is convenient for later operation, so that different methods of the same module are written in the same servlet method and so on, reducing code redundancy)
**Base class code:**
@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1. Receiving parameters
		String action = request.getParameter("action");
		try {
			//2. Get the bytecode of the current object
			Class clazz = this.getClass();
			//3. Getting the corresponding method in the current object
			Method method = clazz.getMethod(action, HttpServletRequest.class,HttpServletResponse.class);
			//4. Judging whether or not the method is introduced
			if(method != null) {
				//1). If you have this method, call it.
				String path = (String)method.invoke(this, request,response);
				//2. Forwarding to the class that calls this method
				if(path != null) {
					request.getRequestDispatcher(path).forward(request, response);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

}
Control code:
@WebServlet("/GoodsServlet")
public class GoodsServlet extends BaseServlet {

	//Add merchandise
	public String add(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//Setting the character encoding set for post requests
		request.setCharacterEncoding("utf-8");
		//Get all the parameters (all the data transferred from the front-end interface is stored in Map)
		Map<String, String[]> parameterMap = request.getParameterMap();
		System.out.println(parameterMap);
		//Encapsulating parameters into objects
		Goods goods = new Goods();
		try {
			//Packaging methods (using jar packages)
			BeanUtils.populate(goods, parameterMap);
			//goods.setImage("goods_11.png");
			//System.out.println(goods);
			//Calling the Service Layer
			GoodsService goodsService = new  GoodsService(); 
			goodsService.addGoods(goods);
			//Jump lists,
			return "Relative Path of Front End Interface";
			
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
}

  • service layer:
    - Code Display (Intermediate Service Part)
public class GoodsService {
	GoodsDao goodsDao = new GoodsDao();
	public void addGoods(Goods goods) throws Exception {
		goodsDao.addGoods(goods);		
	}
}

9.service layer can get data from JSP (front-end) or send data to front-end.

  • The first section can be displayed by el/jstl.

Posted by Zallus on Sun, 15 Sep 2019 02:04:38 -0700