前边对如何搭建SpringMvc框架和JDBC做了一个介绍,接下来贴出前端和后台代码。
该项目可以使用以下两个方法运行,如何配置jetty和tomcat在
IDEA从零搭建SpringMvc+JDBC操作数据库(三) 进行介绍
- 安装jetty插件后,打开cmd进入到该项目的pom.xml同级目录文件下,执行mvn jetty:run
- 配置tomcat后调试
这里做了一个简单的测试,因我使用的本机调试,以访问home.jsp为例,
- 使用jetty调试,访问Url:http://localhost:8080/test/mvc
- 使用tomcat进行调试,访问Url:http://localhost:8080/springmvc/test/mvc
以下使用tomcat调试的Url进行演示。
访问http://localhost:8080/springmvc/test/mvc ,已将Resources资源文件中的jQuery引入至home.jsp,点击测试按钮,可以查看springmvc-servlet.xml中的
<mvc:resources mapping="/resources/**" location="/resources/" />
是否配置成功,报错则静态资源被拦截,查看springmvc-servlet.xml。
一、如何使用SpringMvc注解访问前端页面。
TestController.class
package com.king.mvcdemo.controller;
import org.apache.commons.lang3.text.StrBuilder;
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 org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("/test")
public class TestController {
@Autowired
HttpServletRequest request;
/*
url:/test/mvc
*/
@RequestMapping({"mvc"})
public String helloMvc(){
return "home";
}
@RequestMapping(value = "ajaxdemo",method = RequestMethod.POST)
@ResponseBody
private Map<String, Object> ajaxDemo() {
Map<String, Object> _out = new HashMap<String, Object>();
StrBuilder sb= new StrBuilder(request.getParameter("cs"));
sb.append("————获取参数成功");
_out.put("msg",sb.toString());
return _out;
}
/*
{}代表绑定的路径变量,@PathVariable指明路径变量
url:/test/list/parsval
*/
@RequestMapping(value = "/list/{parsval}",method = RequestMethod.GET)
private String cs(@PathVariable("parsval")String parsval,Map<String,Object> model) {
model.put("pars",parsval);
return "list";
}
}
home.jsp
<%-- home.jsp --%>
<%--
Created by IntelliJ IDEA.
User: King
Date: 2019/7/12
Time: 17:11
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
request.setAttribute("path", path);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>测试页面</title>
<%--<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>--%>
<script src="${path}/resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script type="application/javascript">
function btn(){
$.ajax({
cache:false,
sync:true,
type:"post",
url:"${path}/test/ajaxdemo",
data: {
"cs": $("#cs1").val()
},
success : function(data) {
document.getElementById("cs2").innerHTML=data.msg;
window.setInterval(function(){
window.location ="${path}/test/list/"+data.msg;
},3000)
}
})
}
</script>
</head>
<body>
Hello Mvc
<input type="text" id="cs1" value="测试传递list页面参数" />
<br />
<div id="cs2"></div>
<input type="button" οnclick="btn()" value="测试"/>
</body>
</html>
list.jsp
<%-- list.jsp --%>
<%--
Created by IntelliJ IDEA.
User: King
Date: 2019/7/15
Time: 15:55
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<h2>获取的参数</h2>
${pars}
</body>
</html>
二、操作MySQL数据库。
前边运行没有问题,说明springmvc框架已经搭好了,接下来使用JDBC在MySQL数据库进行数据插入。
StudentController.class
package com.king.mvcdemo.controller;
import com.king.mvcdemo.dao.JDBCOperater;
import com.king.mvcdemo.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@RequestMapping(value="/student", method= RequestMethod.GET)
public ModelAndView student() {
Student st = new Student();
// 表单测试传参
st.setName("测试");
return new ModelAndView("student", "command", st);
}
@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student, Model model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
JDBCOperater jdbcOp = (JDBCOperater) context.getBean("student");
jdbcOp.insertNamedParameter(student);
((ConfigurableApplicationContext)context).close();
return "result";
}
}
JDBCOperater.class
package com.king.mvcdemo.dao;
import com.king.mvcdemo.entity.Student;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JDBCOperater extends NamedParameterJdbcDaoSupport {
public void insertNamedParameter(Student student) {
String sql = "INSERT INTO Student(ID, NAME, AGE)"
+ "VALUES(:id, :name, :age)";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", student.getName());
parameters.put("age", student.getAge());
parameters.put("id", student.getId());
getNamedParameterJdbcTemplate().update(sql, parameters);
}
public Student findByStudentId(int Id) {
String sql = "SELECT * FROM Student WHERE ID = ?";
Student student = getJdbcTemplate().queryForObject(sql, new Object[] {Id}, new BeanPropertyRowMapper<Student>(Student.class));
return student;
}
public List<Student> findAll() {
String sql = "SELECT * FROM Student";
List<Student> students = getJdbcTemplate().query(sql, new BeanPropertyRowMapper<Student>(Student.class));
return students;
}
}
Student.class
package com.king.mvcdemo.entity;
public class Student {
private Integer age;
private String name;
private Integer id;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
student.jsp
<%-- student.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%
String path = request.getContextPath();
request.setAttribute("path", path);
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>学生信息</h2>
<form:form method="POST" action="${path}/addStudent">
<table>
<tr>
<td><form:label path="name">姓名:</form:label></td>
<td><form:input path="name"/></td>
</tr>
<tr>
<td><form:label path="age">年龄:</form:label></td>
<td><form:input path="age"/></td>
</tr>
<tr>
<td><form:label path="id">编号:</form:label></td>
<td><form:input path="id"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交学生信息"/></td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
<%-- result.jsp --%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Spring mvc 表单处理-输入框处理</title>
</head>
<body>
<h2>提交的学生信息如下</h2>
<table>
<tr>
<td>姓名</td>
<td>${name}</td>
</tr>
<tr>
<td>年龄</td>
<td>${age}</td>
</tr>
<tr>
<td>编号</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
在applicationContext.xml中对数据库进行配置后,启动项目,访问http://localhost:8080/springmvc/student,在该页面中录入数据并commit表单数据,在MySQL数据库中插入数据则正确。
后边发现传入至result.jsp的name数值为乱码,因为缺少在web.xml中未设置编码过滤器。
操作JDBC源码参考原文:https://blog.csdn.net/danlansde/article/details/74166256
搭建完后仍然报错的,项目资源下载:springmvc+jdbc数据库实例