目录
前言
我们之前已经搞好了关于所有mybatis与spring的一个集成,当然还运用了rdies(缓存机制), 所以我们现在就参考如何可以去连接tomcat和jsp,以及前端和后端的一个增删改查,
springmvc的一个搭建
1.配置相关pom.xml
tomcat 与Jsp之间的api文件
<!--tomcat-jsp-->
<tomcat-jsp-api.version>8.0.47</tomcat-jsp-api.version>
<!--tomcat与jsp的-->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jsp-api</artifactId>
<version>${tomcat-jsp-api.version}</version>
</dependency>
自定义标签所可能用到的,比如PageTag,
<!--在用jstl用到的自定义标签-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
这个下面不是加上,而是替换掉之前的spring-context
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
2.配置相关xml文件
把相关的路径文件修改好就行了,也就是爆红的改了
springmvc-servlet.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" xmlns:aop="http://www.springframework.org/schema/aop"
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-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 通过context:component-scan元素扫描指定包下的控制器-->
<!--1) 扫描com.javaxl.zf及子子孙孙包下的控制器(扫描范围过大,耗时)-->
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.liwangwang"/>
<!--2) 此标签默认注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter -->
<!--两个bean,这两个bean是spring MVC为@Controllers分发请求所必须的。并提供了数据绑定支持,-->
<!--@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--3) ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- viewClass需要在pom中引入两个包:standard.jar and jstl.jar -->
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--4) 单独处理图片、样式、js等资源 -->
<!--<mvc:resources location="/css/" mapping="/css/**"/>-->
<mvc:resources location="/static/" mapping="/static/**"/>
<!--<mvc:resources location="/js/" mapping="/js/**"/>-->
</beans>
web.xml 看我的修改就行。
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_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- Spring和web项目集成start -->
<!-- spring上下文配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 读取Spring上下文的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring和web项目集成end -->
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 中文乱码处理 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>com.liwangwang.util.EncodingFiter</filter-class>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--此参数可以不配置,默认值为:/WEB-INF/springmvc-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<!--web.xml 3.0的新特性,是否支持异步-->
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.可以开始测试五种返回方式
本人觉得,一般掌握好
转发到jsp和重定向到Action界面
两个就差不多了
package com.liwangwang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author liwangwang
* @site www.liwangwang.com
* @company
* @create 2019-09-28 11:10
*/
/**
* 五种返回形式
* 1,转发到jsp界面
* 2, 转发到Action界面
* 3, 重定向到jsp界面
* 4, 重定向到Action界面
* 5, 修改springmvc-servlet.xml,里面的视图控制器
*
*/
@RequestMapping("/hello")
@Controller
public class HelloController {
/**
* 转发到jsp界面
* @param request
* @return
*/
@RequestMapping("/hello")
public String hello(HttpServletRequest request){
return "/static/static";
// return "/WEB-INF/aaa";//这个可以,也可以在视图控制器那配置
}
/**
* 转发到Action
* @param request
* @return
*/
@RequestMapping("/hello1")
public String hello1(HttpServletRequest request){
request.setAttribute("msg","第一次springmvc整合,调用了hello1方法");
return "forward:hello";
}
/**
* 重定向到Action
* @param request
* @return
*/
@RequestMapping("/hello2")
public String hello2(HttpServletRequest request){
request.setAttribute("msg","调用了重定向方法");
return "redirect:hello3";
}
/**
* 重定向到jsp界面
* @param request
* @return
*/
@RequestMapping("/hello3")
public String hello3(HttpServletRequest request){
request.setAttribute("msg","调用了重定向方法到jsp页面");
return "redirect:/hello.jsp";
}
}
以此来完成增删查改(book案例)
1.先把相关分页标签资源文件配置好。
资料都在下面:
链接:https://pan.baidu.com/s/16qYdYpy9DUC0ezaUJ7T2YQ
提取码:4hfk
2.写好jsp页面代码(bookList.jsp,bookEdit.jsp)
bookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/liwangwang" prefix="z" %>
<!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>Insert title here</title>
<script type="text/javascript">
function add(){
// window.location.href = "bookEdit.jsp";
window.location.href="${pageContext.request.contextPath}/Book/preSave";
}
function update(bid){
window.location.href = "${pageContext.request.contextPath}/Book/preSave?bid="+bid;
}
function del(bid){
window.location.href = "${pageContext.request.contextPath}/Book/delBook/"+bid;
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/Book/getAll"
method="post">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</form>
<button onclick="add();">新增</button>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
<td>操作</td>
</tr>
<c:forEach items="${bookList }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<button onclick="update(${b.bid });">修改</button>
<button onclick="del(${b.bid });">删除</button>
</td>
</tr>
</c:forEach>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>
bookEdit.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function doSubmit(bid){
var bookForm = document.getElementById("bookForm");
if(bid){
//修改时候执行
bookForm.action = '${pageContext.request.contextPath}/Book/editBook';
}else{
//新增时候执行
bookForm.action = '${pageContext.request.contextPath}/Book/addBook';
}
bookForm.submit();
}
</script>
</head>
<body>
<form id="bookForm" action="" method="post">
bid:<input type="text" name="bid" value="${book.bid }"><br>
bname:<input type="text" name="bname" value="${book.bname }"><br>
price:<input type="text" name="price" value="${book.price }"><br>
<input type="submit" value="提交" onclick="doSubmit('${book.bid }');"><br>
</form>
</body>
</html>
3.写好后台控制文件BookController.java
因为我们的业务层和持久层都已经在前面已经都解决了,所以我们仅仅只需要把控制层写好就行
package com.liwangwang.controller;
import com.liwangwang.model.Book;
import com.liwangwang.service.BookService;
import com.liwangwang.util.PageBean;
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 javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @authorliwangwang
* @site www.liwangwang.com
* @company xxx公司
* @create 2019-09-28 15:53
*/
@Controller
@RequestMapping("/Book")
public class BookController {
@Autowired
BookService bookService;
@RequestMapping("/getAll")
public String getAll(HttpServletRequest request){
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
Map<String,Object> book = new HashMap<>();
book.put("bname",request.getParameter("bname"));
List<Map> list = bookService.listPager(book, pageBean);
request.setAttribute("bookList",list);
request.setAttribute("pageBean",pageBean);
return "/WEB-INF/bookList";
}
@RequestMapping("/preSave")
public String preSave(Book book ,HttpServletRequest request){
if(book.getBid()!=null ){
Book b = bookService.selectByPrimaryKey(book.getBid());
System.out.println(book);
request.setAttribute("book",b);
}
return "WEB-INF/bookEdit";
}
@RequestMapping("/addBook")
public String addBook(Book book, HttpServletRequest request){
int insert = bookService.insert(book);
return "redirect:/Book/getAll";
}
@RequestMapping("/delBook/{bid}")
public String delBook(@PathVariable(value = "bid") Integer bid, HttpServletRequest request){
int b = bookService.deleteByPrimaryKey(bid);
return "redirect:/Book/getAll";
}
@RequestMapping("/editBook")
public String editBook(Book book ,HttpServletRequest request){
int i = bookService.updateByPrimaryKeySelective(book);
return "redirect:/Book/getAll";
}
}
值得一提的就是删除方法里用到的参数,
我们需要在使用这个方法的时候,不用delBook?bid=bid
了
改进后的写法
那么我们就可以直接在
后记
嗯,用这个写了第一步后,以后在写其他的模块就会变得很快