SpringMVC接口开发

SpringMVC接口开发

创建一个简单的SpringMVC框架,并且通过数据库连接池c3p0访问数据库,通过QueryRunner (使用参考)简化数据的增删改查操作(大佬请绕路,此文章仅供萌新参考)。

项目源码

项目源码和搭建环境所需jar包

项目目录截图

SpringMVC接口开发_第1张图片

数据库文件

CREATE TABLE `student`  (
`id` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
sname` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
age` int(11) NULL DEFAULT NULL,
sex` int(11) NULL DEFAULT NULL,
mobile` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

INSERT INTO `student` VALUES ('1', 'zhangsan', 18, 0, 123);
INSERT INTO `student` VALUES ('2', 'lisi', 28, 1, 456);

第一步

创建dynamic web project项目,在WEB-INF的lib中导入相应的 jar包(右键点击jar包->build path->add to build path)

第二步

配置web.xml(在WEB-INF路径下)



 MySpringMVC

index.html
index.htm
index.jsp
default.html
default.htm
default.jsp


	springDispatcherServlet
	org.springframework.web.servlet.DispatcherServlet
	
		
		contextConfigLocation
		classpath:springmvc.xml
	
	1




	springDispatcherServlet
	/

配置c3p0-config.xml(在src路径下)




	jdbc:mysql://localhost:3306/students_manage?serverTimezone=UTC
	com.mysql.cj.jdbc.Driver
	root
	root
	30000
	10
	30
	100
	10




	jdbc:mysql://localhost:3306/students_manage?serverTimezone=UTC
	com.mysql.cj.jdbc.Driver
	root
	root
	30000
	10
	30
	100
	10

配置springmvc.xml(在src路径下)








是重点,base-package中放的是spring中controller的包名。
重点!重点!重点!

第三步

创建c3p0Utils用于c3p0数据库连接池的配置

package com.apan.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {

	static private ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql_dev");

	/**
	 * 获取connection
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException{	
		return dataSource.getConnection();
	}
	
	/**
	 * 获取连接池对象
	 * @return
	 */
	public static ComboPooledDataSource getDataSource(){
		return dataSource;
	}
	
	/**
	 * 关闭所有连接
	 * @param conn
	 * @param stmt
	 * @param rs
	 */
	public static void closeAll(Connection conn, Statement stmt, ResultSet rs){
		closeAll(conn, stmt);
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
	}
	
	/**
	 * 关闭 conn stmt
	 * @param conn
	 * @param stmt
	 */
	public static void closeAll(Connection conn, Statement stmt){
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(stmt != null){
			try {
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

创建QueryRunnerUtils用于获取QueryRunner对象

package com.apan.utils;
import org.apache.commons.dbutils.QueryRunner;
public class QueryRunnerUtils {
	//创建静态QueryRunner对象
	public static QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
}

第四步

创建封装json相关的工具类

package com.apan.json;

import java.util.Date;

public class AbstractJsonObject {
    //code
	private String code;
	//msg
	private String msg;
 
	private Long time = new Date().getTime();
 
	public String getCode() {
		return code;
	}
 
	public void setCode(String code) {
		this.code = code;
	}
 
	/**
	 * @return the time
	 */
	public Long getTime() {
		return time;
	}
 
	/**
	 * @param time
	 *            the time to set
	 */
	public void setTime(Long time) {
		this.time = time;
	}
 
	public String getMsg() {
		return msg;
	}
 
	public void setMsg(String msg) {
		this.msg = msg;
	}
 
	public void setContent(String code, String msg) {
		this.code = code;
		this.msg = msg;
	}
 
	public void setStatusObject(StatusObject statusObject) {
		this.code = statusObject.getCode();
		this.msg = statusObject.getMsg();
	}
}

package com.apan.json;
public class SingleObject extends AbstractJsonObject {

	private Object object;
 
	public Object getObject() {
		return object;
	}
 
	public void setObject(Object object) {
		this.object = object;
	}
}

package com.apan.json;
/**
 * 状态对象
*/
public class StatusObject {
	// 状态码
	private String code;
 
	// 状态信息
	private String msg;
 
	public StatusObject(String code, String msg) {
		super();
		this.code = code;
		this.msg = msg;
	}
 
	public String getCode() {
		return code;
	}
 
	public void setCode(String code) {
		this.code = code;
	}
 
	public String getMsg() {
		return msg;
	}
 
	public void setMsg(String msg) {
		this.msg = msg;
	}
 
}

package com.apan.json;

public class StatusCode {
	public static final String CODE_SUCCESS = "1";
	public static final String CODE_FAIL = "0";
}

package com.apan.json;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JackJsonUtils {
	static ObjectMapper objectMapper;
	/**
	 * 解析json
	 * 
	 * @param content
	 * @param valueType
	 * @return
	 */
	public static  T fromJson(String content, Class valueType) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return objectMapper.readValue(content, valueType);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
 
	/**
	 * 生成json
	 * 
	 * @param object
	 * @return
	 */
	public static String toJson(Object object) {
		if (objectMapper == null) {
			objectMapper = new ObjectMapper();
		}
		try {
			return objectMapper.writeValueAsString(object);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

package com.apan.json;

import java.util.List;

public class ListObject extends AbstractJsonObject {
 
	// 列表对象
	private List items;
 
	public List getItems() {
		return items;
	}
 
	public void setItems(List items) {
		this.items = items;
	}
 
}

package com.apan.json;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

/**
 * HttpServletResponse帮助类
 */
public class ResponseUtils {
 
public static void renderJson(HttpServletResponse response, String text) {
		// System.out.print(text);
		render(response, "text/plain;charset=UTF-8", text);
	}
 
 
/**
	 * 发送内容。使用UTF-8编码。
	 * 
	 * @param response
	 * @param contentType
	 * @param text
	 */
	public static void render(HttpServletResponse response, String contentType, String text) {
		response.setContentType(contentType);
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
		}
	}
	
	/**
	 * 发送内容。使用UTF-8编码。
	 * 
	 * @param response
	 * @param contentType
	 * @param text
	 */
	public static void render(HttpServletResponse response, String text) {
		response.setContentType("txt");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		try {
			response.getWriter().write(text);
		} catch (IOException e) {
		}
	}
}

第五步

创建student实体类

package com.apan.model;
public class Student {
	private int id;
	private String sname;
	private int age;
	private int sex;
	private int mobile;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	public int getMobile() {
		return mobile;
	}
	public void setMobile(int mobile) {
		this.mobile = mobile;
	}
	@Override
	public String toString() {
		return "Students [id=" + id + ", sname=" + sname + ", age=" + age + ", sex=" + sex + ", mobile=" + mobile + "]";
	}
}

第六步

创建student数据库操作的dao接口并实现dao.impl

package com.apan.dao;
import java.util.HashMap;
import java.util.List;

import com.apan.model.Student;

public interface IStudentDao {

	//获取所有学生信息
	public List getAllStudent();
	
	//根据字段查找学生信息
	public List getStudentById(String key, String values);
	
	//插入学生信息
	public int insertStudent(List students);
	
	//修改学生信息
	public int updateStudent(Student students);
	
	//修改学生信息
	public int updateStudent(String key, String value, int id);
	
	//删除学生信息
	public int deleteStudent(int id);
}

dao.impl实现

package com.apan.dao.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.apan.dao.IStudentDao;
import com.apan.model.Student;
import com.apan.utils.QueryRunnerUtils;

public class StudentDaoImpl implements IStudentDao {

	QueryRunner qr = QueryRunnerUtils.qr;

	@Override
	public List getAllStudent() {
		// TODO Auto-generated method stub
		
		String sql = "select * from student";
		
		try {
			List Students = qr.query(sql, new BeanListHandler(Student.class));
			
			return Students;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}


	@Override
	public List getStudentById(String key, String values) {
		// TODO Auto-generated method stub
		
		String sql = "select * from student where " + key + " = ?";
		
		System.out.println(sql);
		List students = null;
		try {
			students = qr.query(sql, new BeanListHandler(Student.class), values);
			return students;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}


	@Override
	public int insertStudent(List students) {
		// TODO Auto-generated method stub
		int sign = 0;
		
	//		INSERT INTO student VALUES(null, 'lisi', 28, 1, 456);
		String sql = "INSERT INTO student VALUES(null, ?, ?, ?, ?)";
		for (Student temp : students) {
			try {
				sign += qr.update(sql, temp.getSname(), temp.getAge(), temp.getSex(), temp.getMobile());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return sign;
	}


	@Override
	public int updateStudent(Student student) {
		// TODO Auto-generated method stub
	//		update student set sname = '1', age = 10, sex = 1, mobile = 123 where id = 3;
		int sign = 0;
		String sql = "update student set sname = ?, age = ?, sex = ?, mobile = ? where id = ?";
		try {
			sign = qr.update(sql, student.getSname(), student.getAge(), student.getSex(), student.getMobile(), student.getId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}
	
	@Override
	public int updateStudent(String key, String value, int id) {
		// TODO Auto-generated method stub
		int sign = 0;
	//		update student set sname = '2' where id = 3;

		String sql = "update student set " + key + " = ? where id = ?";
		try {
			sign = qr.update(sql, value, id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}


	@Override
	public int deleteStudent(int id) {
		// TODO Auto-generated method stub
		int sign = 0;
	//		delete from student where id = 3;
		String sql = "delete from student where id = ?";
		try {
			sign = qr.update(sql, id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}
}

第七步

创建student查询结果逻辑处理service并实现service.impl

package com.apan.service;

import java.util.List;

import com.apan.model.Student;

public interface StudentService {
	//获取所有学生信息
		public List getAllStudent();
		
		//根据字段查找学生信息
		public List getStudentById(String key, String values);
		
		//插入学生信息
		public int insertStudent(List students);
		
		//修改学生信息
		public int updateStudent(Student students);
		
		//修改学生信息
		public int updateStudent(String key, String value, int id);
		
		//删除学生信息
		public int deleteStudent(int id);
}

实现service.impl

package com.apan.service.impl;

import java.util.List;

import com.apan.dao.IStudentDao;
import com.apan.dao.impl.StudentDaoImpl;
import com.apan.model.Student;
import com.apan.service.StudentService;

public class StudentServiceImpl implements StudentService{
	
	IStudentDao studentDaoImpl = new StudentDaoImpl();
 
	@Override
	public List getAllStudent() {
		// TODO Auto-generated method stub
		return studentDaoImpl.getAllStudent();
	}

	@Override
	public List getStudentById(String key, String values) {
		// TODO Auto-generated method stub
		return studentDaoImpl.getStudentById(key, values);
	}

	@Override
	public int insertStudent(List students) {
		// TODO Auto-generated method stub
		return studentDaoImpl.insertStudent(students);
	}

	@Override
	public int updateStudent(Student students) {
		// TODO Auto-generated method stub
		return studentDaoImpl.updateStudent(students);
	}

	@Override
	public int updateStudent(String key, String value, int id) {
		// TODO Auto-generated method stub
		return studentDaoImpl.updateStudent(key, value, id);
	}

	@Override
	public int deleteStudent(int id) {
		// TODO Auto-generated method stub
		return studentDaoImpl.deleteStudent(id);
	}
 
}

第八步

实现student的servlet

package com.apan.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.apan.json.AbstractJsonObject;
import com.apan.json.JackJsonUtils;
import com.apan.json.ListObject;
import com.apan.json.ResponseUtils;
import com.apan.json.StatusCode;
import com.apan.model.Student;
import com.apan.service.StudentService;
import com.apan.service.impl.StudentServiceImpl;


@Controller
@RequestMapping("student")
public class StudentServlet {
	
	public StudentService studentServiceImpl = new StudentServiceImpl();
 
 
//	http://localhost:8080/SpringMVCModel/student/getAllStudent
	@RequestMapping("/getAllStudent")
	public void getAllStudent(HttpServletRequest request, HttpServletResponse response) {
		List list = studentServiceImpl.getAllStudent();
		
		
		ListObject listObject = new ListObject();
		listObject.setItems(list);
		listObject.setCode(StatusCode.CODE_SUCCESS);
		listObject.setMsg("访问成功");
		
		
		ResponseUtils.renderJson(response, JackJsonUtils.toJson(listObject));
	}
	
	//http://localhost:8080/SpringMVCModel/student/getStudentById?key=id&value=1
	@RequestMapping("/getStudentById")
	public void getStudentById(HttpServletRequest request, HttpServletResponse response) {
		String key = request.getParameter("key");
		String values = request.getParameter("value");
		System.out.println("key: " + key + " | value: " + values);
		List list = studentServiceImpl.getStudentById(key, values);
		
		ListObject listObject = new ListObject();
		listObject.setItems(list);
		listObject.setCode(StatusCode.CODE_SUCCESS);
		listObject.setMsg("访问成功");
		
		
		ResponseUtils.renderJson(response, JackJsonUtils.toJson(listObject));

	}
	
//	http://localhost:8080/SpringMVCModel/student/insertStudent?id=4&sname=4&age4&sex1&mobile=345
//	http://localhost:8080/SpringMVCModel/student/insertStudent?sname=4&age4&sex1&mobile=345
	@RequestMapping("/insertStudent")
	public void insertStudent(HttpServletRequest request, HttpServletResponse response, Student students) {
		
		List students2 = new ArrayList();
		students2.add(students);
		int sign = studentServiceImpl.insertStudent(students2);
		
		AbstractJsonObject obj = new AbstractJsonObject();
		obj.setCode(StatusCode.CODE_SUCCESS);
		obj.setMsg(String.valueOf(sign));;
		
		
		ResponseUtils.renderJson(response, JackJsonUtils.toJson(obj));

	}
	
//	http://localhost:8080/SpringMVCModel/student/updateStudent?key=age&value=111&id=4
	@RequestMapping("/updateStudent")
	public void updateStudent(HttpServletRequest request, HttpServletResponse response, String key, String value,int id) {
		
		int sign = studentServiceImpl.updateStudent(key, value, id);
		
		AbstractJsonObject obj = new AbstractJsonObject();
		obj.setCode(StatusCode.CODE_SUCCESS);
		obj.setMsg(String.valueOf(sign));;
		
		
		ResponseUtils.renderJson(response, JackJsonUtils.toJson(obj));
	}
	
//	http://localhost:8080/SpringMVCModel/student/deleteStudent?id=4
	@RequestMapping("/deleteStudent")
	public void deleteStudent(HttpServletRequest request, HttpServletResponse response, int id) {
		int sign = studentServiceImpl.deleteStudent(id);
		
		AbstractJsonObject obj = new AbstractJsonObject();
		obj.setCode(StatusCode.CODE_SUCCESS);
		obj.setMsg(String.valueOf(sign));;
		
		
		ResponseUtils.renderJson(response, JackJsonUtils.toJson(obj));
	}
	
	
	@RequestMapping("/test")
	public void method01(HttpServletRequest req, HttpServletResponse response) {
		String name = req.getParameter("name");
		if(name == null) {
			name = "参数错误";
		}
		
		System.out.println("name:" + name);
		ResponseUtils.render(response, name);
	}
 
}

查询结果如下:
SpringMVC接口开发_第2张图片
这只是一个简单的SpringMVC接口开发的封装,仅供初学者参考

你可能感兴趣的:(Java)