Spring-mvc restful实现学生信息增删改查实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Maybeno1314/article/details/81630824

pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.zzxt</groupId>
	<artifactId>spring.mvc</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring.mvc Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring.version>5.0.7.RELEASE</spring.version>
	</properties>

	<dependencies>
		<!-- 娣诲姞Servlet鏀寔 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>javax.servlet.jsp-api</artifactId>
			<version>2.3.1</version>
		</dependency>

		<!-- 娣诲姞jtl鏀寔 -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>


		<!-- 娣诲姞Spring鏀寔 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- Mysql椹卞姩鍖?-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.46</version>
		</dependency>

		<!--闃块噷鏁版嵁搴撹繛鎺ユ睜 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>spring.mvc</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>
</project>

applacationContext-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/mvc
        	   http://www.springframework.org/schema/mvc/spring-mvc.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context.xsd">

	<context:component-scan base-package="com.zzxt.spring.mvc.restful.action"></context:component-scan>
	
	
	<!-- 
		少了这句话就会出现
		
		 No mapping found for HTTP request with URI [/spring.mvc/student/manager] in DispatcherServlet with name 'DispatcherServlet'
	 -->
	 <mvc:annotation-driven />
	 
	 
	 
	 <!-- 
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	 
	 	目的是为了不在Controller层定义空的方法来进入insertInfo页面
	  -->
	 <mvc:view-controller path="/editStuInfo" view-name="/views/stu/insertInfo.jsp"/>
	 	
</beans>

applicationContext.xml文件 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 
 -->
	<context:component-scan base-package="com.zzxt.spring.mvc.restful.service"></context:component-scan>
	<context:component-scan base-package="com.zzxt.spring.mvc.restful.dao"></context:component-scan>
																			
																				
	 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
             	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
             	<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
             	<property name="username" value="root"></property>
             	<property name="password" value="root"></property>
             </bean>
             
              <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
              	<property name="dataSource" ref="dataSource"></property>
              </bean>																
				
			   <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
             	<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>             	
              </bean>
             <!-- 
              <bean id="bankDaoImpl" class="com.zzxt.spring.mvc.hello.entity.BankDaoImpl">
              	<property name="jdbcTemplate" ref="jdbcTemplate"></property>
              	<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
              </bean>
             
              --> 
</beans>

 com.zzxt.spring.mvc.restful.dao文件夹下

stuInfoDao.java

package com.zzxt.spring.mvc.restful.dao;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.zzxt.spring.mvc.restful.entity.Student;


@Repository
public interface StuInfoDao {
	public void insertStuInfo(Student ci);
	public List<Student> getStuInfo();
	public Student searchStuInfoById(String stuNo);
	public void delStuInfo(String stuNo);
	public void updateInfo(Student stu,String stuNo);
}

stuInfoDaoImpl

package com.zzxt.spring.mvc.restful.dao;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.zzxt.spring.mvc.restful.entity.Student;

@Repository
public class StuInfoDaoImpl implements StuInfoDao{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;	
	
	
	/*
	 * 
	 * 增加学生信息
	 * 
	 * */
	public void insertStuInfo(Student ci){
		System.out.println("=======>开始注入信息");
		String sql = "insert into stu_info values (:stuNo,:stuName,:gender,:age,:classNo)";		
		Map<String,Object> map = new HashMap<String,Object>();			
		map.put("stuNo", ci.getStuNo());
		map.put("stuName", ci.getStuName());
		map.put("gender", ci.getGender());
		map.put("age",ci.getAge());
		map.put("classNo", ci.getClassNo());		
		System.out.println("======>" + ci.getStuNo());		
		namedParameterJdbcTemplate.update(sql,map);	
	}	
	/*
	 * 查询所有学生信息
	 * 
	 * */
	public List<Student> getStuInfo() {
		
		String sql = "select * from stu_info";
		
		return jdbcTemplate.query(sql, new RowMapper<Student>() {

			public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
				
				//创建一个学生信息结构对象,并利用set方法进行初始化
				Student st = new Student();
				st.setStuNo(rs.getString("stuNo"));
				st.setStuName(rs.getString("stuName"));
				st.setGender(rs.getString("gender"));
				st.setAge(rs.getInt("age"));
				st.setClassNo(rs.getString("classNo"));		
				return st;
			}
			
			
		});		
	}
	/*
	 * 
	 * 查询特定学生信息
	 * 
	 * */
	public Student searchStuInfoById(String stuNo){
		
		String sql = "select * from stu_info where stuNo=?";
		return jdbcTemplate.queryForObject(sql, new Object[] {stuNo}, new RowMapper<Student>() {

			public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
				Student st = new Student();
				st.setStuNo(rs.getString("stuNo"));
				st.setStuName(rs.getString("stuName"));
				st.setGender(rs.getString("gender"));
				st.setAge(rs.getInt("age"));
				st.setClassNo(rs.getString("classNo"));		
				return st;
			}
			
		});
	}	
	
	/*
	 * 
	 * 
	 * 修改学生信息
	 * 
	 * 
	 * */
	public void updateInfo(Student stu,String stuNo) {
		String sql = "update stu_info set stuName=?, gender=?, age=?,classNo=? where stuNo=?";
		jdbcTemplate.update(sql, new Object[] {stu.getStuName(),stu.getGender(),stu.getAge(),stu.getClassNo(),stuNo});
	}
	/*
	 * 
	 * 
	 * 删除学生信息
	 * 
	 * 
	 * 
	 * */
	public void delStuInfo(String stuNo) {
		// TODO Auto-generated method stub
		String sql = "delete from stu_info where stuNo = ?";
		jdbcTemplate.update(sql, new Object[] {stuNo});
	}
	
}

 com.zzxt.spring.mvc.restful.service包下的

StuService.java接口

package com.zzxt.spring.mvc.restful.service;

import java.util.List;

import org.springframework.stereotype.Service;

import com.zzxt.spring.mvc.restful.entity.Student;


@Service
public interface StuService {
	public void addStuInfo(Student ci);
	public List<Student> getStuInfo();
	public Student updateStuInfo(String stuNo);
	public void delStuInfo(String stuNo);
	public void doUpdateStuInfo(Student stu,String stuNo);
}

StuServiceImpl.java上面接口的实现

package com.zzxt.spring.mvc.restful.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zzxt.spring.mvc.restful.dao.StuInfoDao;
import com.zzxt.spring.mvc.restful.entity.Student;


@Service
public class StuServiceImpl implements StuService{
	/*
	 * 
	 * servic层我认为起到了信息转换的作用
	 * 
	 * */
	
	@Autowired
	private StuInfoDao stuInfoDao;
	//添加学生信息
	public void addStuInfo(Student ci) {
		// TODO Auto-generated method stub
		stuInfoDao.insertStuInfo(ci);
		
	}
	//查询所有学生信息
	public List<Student> getStuInfo() {
		return stuInfoDao.getStuInfo();
	}
	
	//修改学生信息初始化页面
	public Student updateStuInfo(String stuNo) {
		// TODO Auto-generated method stu
		return stuInfoDao.searchStuInfoById(stuNo);
	}	
	//删除学生信息
	public void delStuInfo(String stuNo) {
		// TODO Auto-generated method stub
		stuInfoDao.delStuInfo(stuNo);
	}
	//修改学生信息
	public void doUpdateStuInfo(Student stu,String stuNo) {
		// TODO Auto-generated method stub
		stuInfoDao.updateInfo(stu,stuNo);
		
	}
}

com.zzxt.spring.mvc.restful.entity包下

Student.java

package com.zzxt.spring.mvc.restful.entity;

import org.springframework.stereotype.Component;

@Component
public class Student {
	private String stuNo;
	
	private String stuName;
	
	private String gender;
	
	private String classNo;
	
	private int age;

	public String getStuNo() {
		return stuNo;
	}

	public void setStuNo(String stuNo) {
		this.stuNo = stuNo;
	}

	public String getStuName() {
		return stuName;
	}

	public void setStuName(String stuName) {
		this.stuName = stuName;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String string) {
		this.gender = string;
	}

	public String getClassNo() {
		return classNo;
	}

	public void setClassNo(String classNo) {
		this.classNo = classNo;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

 com.zzxt.spring.mvc.restful.action包下

stuController.java

package com.zzxt.spring.mvc.restful.action;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zzxt.spring.mvc.restful.entity.Student;
import com.zzxt.spring.mvc.restful.service.StuService;

@Controller
@RequestMapping("/student")
public class stuController {
	
	@Autowired
	private StuService stuServices;
	
	
	//显示学生信息
	@RequestMapping("/list")
	public String stuList(Map<String,Object> map) {	
		map.put("student", stuServices.getStuInfo());
		return "/views/stu/showView.jsp";
	}	
	
	
	//增加学生信息
	@RequestMapping(value="/manager",method=RequestMethod.POST)
	public String addStuInfo(Student ci) {		
		//System.out.println("我运行到了页面转接处");
		stuServices.addStuInfo(ci);
		return "redirect:list";			
	}
	
	
	//更新页面初始化;    这段代码要熟记。
	@RequestMapping(value="/updateInit/{stuNo}",method=RequestMethod.GET)
	public String updateInit(@PathVariable("stuNo") String stuNo,Map<String,Object> map) {
		map.put("student", stuServices.updateStuInfo(stuNo));
		return  "/views/stu/insertInfo.jsp";
	}
	
	
	// 更新后跳转
	@RequestMapping(value="/manager",method=RequestMethod.PUT)
	public String update(Student ci) {
		stuServices.doUpdateStuInfo(ci,ci.getStuNo());
		return "redirect:list";
	}	 	
	
	
	//删除学生信息
	@RequestMapping(value="/delete/{stuNo}",method=RequestMethod.GET)
	public String deleteInit(@PathVariable("stuNo") String stuNo,Map<String,Object> map) {
		stuServices.delStuInfo(stuNo);
		map.put("student", stuServices.getStuInfo());
		return "/views/stu/showView.jsp";	
	}		
}

 

jsp页面代码 

insertInfo.jsp

<%@ 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">

<!-- 
	老哥下次配置绝对路径要配全

 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctxPath" value="${pageContext.request.contextPath }"></c:set>


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生信息网页录入</title>
</head>
<body>

	
	<form action="${ctxPath}/student/manager" method="post">
	<!-- 修改信息时使用put方法 -->	 
	<c:if test="${student.stuNo != null}">	
		<input type="hidden" name="_method" value="PUT">
	</c:if>	
		
		<table align="center" border="1px" bordercolor="blue">
			<tr>
				<th colspan="2" align="center">添加学生信息</th>
			</tr>
			<tr>
				<td align="center">学生学号</td><td align="left"><input type="text" name="stuNo" value="${student.stuNo }"></td>
			</tr>
			<tr>
				<td align="center">学生姓名</td><td align="left"><input type="text" name="stuName"value="${student.stuName }"></td>
			</tr>
			<tr>
				<td align="center">学生性别</td><td align="left"><input type="text" name="gender"value="${student.gender }"></td>
			</tr>
			<tr>
				<td align="center">学生年龄</td><td align="left"><input type="text" name="age"value="${student.age }"></td>
			</tr>
			<tr>
				<td align="center">学生班级</td><td align="left"><input type="text" name="classNo"value="${student.classNo }"></td>
			</tr>
			<tr>
				<td align="center" colspan="2">
					<input type="submit" name="提交" value="添加">&nbsp;&nbsp;
					<input type="reset" name="重置" value="重置">
				</td>
			</tr>
		</table>
	
	
	</form>
</body>
</html>

showView.jsp

<%@ 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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!--

//-->
 
<c:set var="ctxPath" value="${pageContext.request.contextPath }"></c:set>

<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>学生信息列表</title>
</head>
<body>
	<div align="center">
		<h3>学生信息列表</h3>
		<hr>
		<table border="1px"> 
			<tr><th>学号</th><th>姓名</th><th>性别</th><th>年龄</th><th>班级</th><th>操作</th></tr>
			<c:forEach items="${student }" var="stu">
				<tr>
					<td>${stu.stuNo}</td>
					<td>${stu.stuName }</td>
					<td>${stu.gender }</td>
					<td>${stu.age }</td>
					<td>${stu.classNo }</td>
					<td><a href="${ctxPath }/student/delete/${stu.stuNo}">删除</a>	
					&nbsp;&nbsp;	
					<!--
						通过/方式传参,需要配置
					  --> 
					<a href="${ctxPath }/student/updateInit/${stu.stuNo}">更新</a></td>
				</tr>
			</c:forEach>  
		</table>
	</div>
</body>
</html>

以下是我eclipse下的文件分布, 哈哈,

比较乱

 

web.xml文件

<?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" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  
  
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  
  </context-param>
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  
   <!-- 
    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>
 				classpath:applicationContext-jdbc.xml
        </param-value>

    </context-param>
  
    -->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  
  
  <filter>
  	<filter-name>HiddenHttpMethodFilter</filter-name>
  	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>HiddenHttpMethodFilter</filter-name>
  	<servlet-name>DispatcherServlet</servlet-name>
  </filter-mapping>
  
  
  
  
  
</web-app>

 

 有些地方不是很完善,只提供大致思路。

 

展开阅读全文

没有更多推荐了,返回首页