MVC框架的小例子`
这里主要做个保存,参考了网上的代码,不是完全原创,也不是照搬转载,自己运行修改了的!
先搭建项目环境,新建一个Spring web项目
在数据库中创建一个学生表
if exists (select * from sysdatabases where name='Test') drop database Test
--建数据库
go
create database Test
go
use Test
if exists (select * from sysobjects where name='students') drop table students
create table students
(
stuId int not null primary key identity(1,1),
stuName varchar(50) not null,
stuAge int not null
)
ServletAddStu.java
package controller;
import model.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ServletAddStu")
public class ServletAddStu extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
//设置编码格式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//得到姓名和年龄.封装到student类中
String name=request.getParameter("stuName");
int age=Integer.valueOf(request.getParameter("stuAge"));
Student student=new Student();
student.setStuName(name);
student.setStuAge(age);
//调用调价方法
StudentDao stuDao=new StudentDao();
stuDao.stuAdd(student);
}
}
ServletDelete.java
package controller;
import model.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ServletDelete")
public class ServletDelete extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
//设置编码格式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//得到姓名和年龄.封装到student类中
String name = request.getParameter("stuName");
//调用调价方法
StudentDao stuDao = new StudentDao();
stuDao.stuDeletByName(name);
}
}
Basedao.java
package model;
import java.sql.*;
public class Basedao {
private static final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private static final String URL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=Test";
private static final String USERNAME="sa";
private static final String PASSWORD="123456";
private Connection conn;//连接对象
protected PreparedStatement pst;//预编译的PreparedStatement对象
protected ResultSet rs;//结果集resultsSet对象
//获取数据库的连接
public void getConnection(){
try {
Class.forName(DRIVER);
conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放资源
public void closeConnection(){
//释放结果集
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放预编译的对象
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放连接
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//增删改
public int executeUpdate(String sql,String []paras){
int count=0;
try {
this.getConnection();//连接数据库
pst=conn.prepareStatement(sql);//基于sql语句创建预编译对象
//如果paras不为空或者长度大于0 就赋值
if(paras!=null && paras.length>0){
for (int i = 0; i < paras.length; i++) {
pst.setString(i+1, paras[i]);
}
}
count=pst.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeConnection();
}
return count;
}
//查询
public ResultSet executeQuery(String sql,String[]paras){
try {
this.getConnection();//连接数据库
pst=conn.prepareStatement(sql);//基于sql语句创建预编译对象
//如果paras不为空或者长度大于0 就赋值
if(paras!=null && paras.length>0){
int index=1;
for (String para : paras) {
pst.setString(index,para);
index++;
}
}
rs=pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
上面的查询方法没有用到,但保留着以后可以扩充查询功能
Student.java
package model;
public class Student {
private int stuId;//编号
private String stuName;//姓名
private int stuAge;//年龄
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
public void setStuAge(int stuAge) {
this.stuAge = stuAge;
}
}
StudentDao.java
package model;
public class StudentDao extends Basedao{
public int stuAdd(Student stu) {
int count=0;
String sql="insert into students values (?,?)";
String [] paras={stu.getStuName(),String.valueOf(stu.getStuAge())};
count=super.executeUpdate(sql, paras);
return count;
}
public int stuDeletByName(String name)
{
int c=0;
String sql="delete from students where stuName =? ";
String [] paras={name};
c=super.executeUpdate(sql, paras);
return c;
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>欢迎</title>
</head>
<body>
登入成功!<br>
<a href="Add.jsp">添加用户</a><br>
<a href="Show.jsp">删除用户</a>
</body>
</html>
Add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>添加</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<%=path %>/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function onSubmit(){
var name=$("#stuName").val();
if(name=="") {
alert("姓名不能为空");
return false; // 返回false,不跳转
}else {
return true; // 返回true,跳转
}
}
</script>
<title>警告</title>
</head>
<body>
注册添加 <br>
<form action="/ServletAddStu" method="post">
<p>姓名:<input type="text" name="stuName" id="stuName"/></p>
<p>年龄:
<select name="stuAge">
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
</select>
</p>
<p><input type="submit" value="提交" onClick="return onSubmit()"></p>
</form>
</body>
</html>
Show.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>删除用户</title>
<script type="text/javascript" src="<%=path %>/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function onSubmit(){
var name=$("#stuName").val();
if(name=="") {
alert("姓名不能为空");
return false; // 返回false,不跳转
}else {
return true; // 返回true,跳转
}
}
</script>
<title>警告</title>
</head>
<body>
<form action="/ServletDelete" method="post">
<p>姓名:<input type="text" name="stuName" id="stuName"/></p>
<p><input type="submit" value="提交" onClick="return onSubmit()"></p>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.form</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ServletAddStu</servlet-name>
<servlet-class>controller.ServletAddStu</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletAddStu</servlet-name>
<!-- 监听所有请求 -->
<url-pattern>/controller.ServletAddStu</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ServletDelete</servlet-name>
<servlet-class>controller.ServletDelete</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletDelete</servlet-name>
<!-- 监听所有请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
*实验结果
参考代码:
https://blog.youkuaiyun.com/miaomiaowyj/article/details/79779475