SSM框架纯手写xml代码模板
1.结构图
注意颜色:java根目录为蓝色,配置文件右下角黄色,测试资源绿色,前端项目文件图标有个蓝点
在这里插入图片描述
2.后端
2.1配置类
2.1.1 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--对应controller-->
<import resource="classpath:spring-mvc.xml"></import>
<!--对应service-->
<import resource="classpath:spring-config.xml"></import>
<!--对应dao-->
<import resource="classpath:spring-mybatis.xml"></import>
</beans>
2.1.2 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_maven?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
2.1.3 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.bright.pojo"/>
</typeAliases>
<!-- mapper实现类装配入接口-->
<mappers>
<mapper resource="com/bright/dao/BookMapper.xml"/>
</mappers>
</configuration>
2.1.4 spring-config.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:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册业务类实现类-->
<bean id="bookServiceImpl" class="com.bright.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 事务的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--在 tx:advice 标签内部 配置事务的属性 -->
<tx:attributes>
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!-- 配置 aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.bright.service.*.*(..))" id="pt1"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
<!--如果是在业务层使用绑定,需要开启注解驱动
<tx:annotation-driven transaction-manager="transactionManager" />-->
<!--自定义切面-->
<bean id="myAspect" class="com.bright.tools.MyAspect"/>
<aop:config>
<aop:pointcut id="myPoint" expression="execution(* com.bright.service.*Impl.*(..))"/>
<aop:aspect id="myAspect" ref="myAspect" >
<aop:around method="aroundAdvice" pointcut-ref="myPoint"/>
</aop:aspect>
</aop:config>
</beans>
2.1.5 spring-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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1.开启SpringMVC的注解驱动,(1)注册映射器,(2)注册适配器 (3)可以在bean里面使用注解 -->
<mvc:annotation-driven>
<!--解决json和java对象之间的转换乱码-->
<mvc:message-converters register-defaults="false">
<!-- 避免string类型直接解析成json-->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 2.扫描web相关的bean-->
<context:component-scan base-package="com.bright.controller" />
<!-- 3.静态资源过滤-->
<mvc:default-servlet-handler/>
<!--如果你所有的Web应用服务器的默认Servlet名称不是"default",则需要通过default-servlet-name属性显示指定:
<mvc:default-servlet-handler default-servlet-name="所使用的Web服务器默认使用的Servlet名称" />-->
<!-- 4.配置ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!--5.拦截器,防止未登录人员进入-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.bright.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!--
/ 拦截的是除了.jsp外的所有请求
/* 是拦截所有当前的文件夹,不包含子文件夹
/** 是拦截所有的文件夹及里面的子文件夹
-->
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,
默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
2.1.6 spring-mybatis.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
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis -->
<!-- 1.获取数据库属性文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2.建立数据库连接池 -->
<!--选择c3p0作为数据源,自动化操作(自动的加载配置文件 并且设置到对象里面)-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="300"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 加载MyBaties配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.bright.dao"/>
</bean>
</beans>
2.1.7 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bright</groupId>
<artifactId>SSMasXML</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--Mybatis+整合spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--spring+springmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- 自定义切面需要的织入包 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.7</version>
</dependency>
</dependencies>
<!--防止编译的时候过滤配置文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2.2 控制层
2.2.1 BookController.class
package com.bright.controller;
import com.bright.pojo.Books;
import com.bright.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier("bookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
@RequestMapping("/toAddBook")
public String toAddPaper() {
return "addBook";
}
@RequestMapping("/addBook")
public String addPaper(Books books) {
bookService.addBook(books);
return "redirect:/book/allBook";
}
@RequestMapping("/toUpdateBook")
public String toUpdateBook(Model model, int id) {
Books books = bookService.queryBookById(id);
model.addAttribute("book",books );
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model, Books book) {
bookService.updateBook(book);
return "redirect:/book/allBook";
}
@RequestMapping("/del/{bookId}")
public String deleteBook(@PathVariable("bookId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
@RequestMapping("/queryBook")
public String queryBook(String queryBookName,Model model){
System.out.println("要查询的书籍:"+queryBookName);
Books books = bookService.queryBookByName(queryBookName);
List<Books> list = new ArrayList<Books>();
list.add(books);
model.addAttribute("list", list);
if (books==null){
model.addAttribute("error", "没有查找到相关书籍!");
}
return "allBook";
}
@RequestMapping("/check")
@ResponseBody
public String checkBookName(String name) {
System.out.println("ajax查询书名:"+name);
String isExist = "yes";
Books book = bookService.queryBookByName(name);
if (book==null){
isExist = "no";
}
return isExist;
}
}
2.2.2 FileController.class
package com.bright.controller;
import com.bright.pojo.Books;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/goUpload")
public String list(Model model) {
return "upload";
}
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file,
HttpServletRequest request) throws IOException {
//上传路径保存设置
System.out.println(request.getServletContext());
// request.getServletContext().getRealPath(/)获取的是项目目录的绝对路径
String path = request.getServletContext().getRealPath("/static/picture");
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath +"/"+
file.getOriginalFilename()));
return "/upload";
}
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
System.out.println("准备下载");
String path = request.getServletContext().getRealPath("/static/picture");
String fileName = "timg.jpg";
//1、设置response 响应头
response.reset(); //设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8"); //字符编码
response.setContentType("multipart/form-data"); //二进制传输数据
//设置响应头
response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2、 读取文件--输入流
InputStream input=new FileInputStream(file);
//3、 写出文件--输出流
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4、执行 写出操作
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
}
2.2.3 UserController.class
package com.bright.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class UserController {
//登陆提交
@RequestMapping("/login")
public String login(HttpSession session, String username, String password, Model model) throws Exception {
if(username.equals("cxl")){
session.setAttribute("username", username);
session.setAttribute("password",password);
return "redirect:/book/allBook";
}else{
return "redirect:/error.jsp";
}
}
//退出登陆
@RequestMapping("logout")
public String logout(HttpSession session) throws Exception {
session.removeAttribute("username");
return "redirect:/index.jsp";
}
}
2.3持久层
2.3.1 BookMapper.Interface
package com.bright.dao;
import com.bright.pojo.Books;
import java.util.List;
public interface BookMapper {
//增加一个Book
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根据id查询,返回一个Book
Books queryBookById(int id);
//查询全部Book,返回list集合
List<Books> queryAllBook();
//根据id查询,返回一个Book
Books queryBookByName(String bookName);
}
2.3.2 BookMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bright.dao.BookMapper">
<!--增加一个Book-->
<insert id="addBook" parameterType="Books">
insert into ssm_maven.books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--根据id删除一个Book-->
<delete id="deleteBookById" parameterType="int">
delete from ssm_maven.books
where bookID=#{bookID}
</delete>
<!--更新Book-->
<update id="updateBook" parameterType="Books">
update ssm_maven.books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询,返回一个Book-->
<select id="queryBookById" resultType="Books">
select * from ssm_maven.books
where bookID = #{bookID}
</select>
<!--查询全部Book-->
<select id="queryAllBook" resultType="Books">
SELECT * from ssm_maven.books
</select>
<!--根据书名查询,返回一个Book-->
<select id="queryBookByName" resultType="Books">
select * from ssm_maven.books
where binary bookName = #{bookName}
</select>
</mapper>
2.4 拦截层
2.4.1 LoginInterceptor.class
package com.bright.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginInterceptor implements HandlerInterceptor {
//进入控制器前
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws ServletException, IOException {
System.out.println("uri: " + request.getRequestURI());
/*去登陆验证控制器放行*/
if (request.getRequestURI().contains("login")) {
return true;
}
/*已经登录就放行*/
if(request.getSession().getAttribute("username") != null) {
return true;
}
/*没登录就重定向到失败页面*/
request.getRequestDispatcher("/failLogin.jsp").forward(request, response);
return false;
}
//执行控制器后,视图渲染前
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
//执行控制器后,视图渲染后
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
2.5 实体类
2.5.1 Books.class
package com.bright.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
}
2.6 业务层
2.6.1 BookService.Interface
package com.bright.service;
import com.bright.pojo.Books;
import java.util.List;
public interface BookService {
//增加一个Book
int addBook(Books book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(Books books);
//根据id查询,返回一个Book
Books queryBookById(int id);
//查询全部Book,返回list集合
List<Books> queryAllBook();
//根据id查询,返回一个Book
Books queryBookByName(String bookName);
}
2.6.2 BookServiceImpl
package com.bright.service;
import com.bright.dao.BookMapper;
import com.bright.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
//调用dao层的操作,设置一个set接口,方便Spring管理
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
public Books queryBookByName(String bookName) {
return bookMapper.queryBookByName(bookName);
}
}
2.7 工具类
2.7.1 MyAspect
package com.bright.tools;
import org.aspectj.lang.ProceedingJoinPoint;
public class MyAspect {
public Object aroundAdvice(ProceedingJoinPoint pjp) {
Object rtValue=null;
try{
System.out.println("纯xml自定义环绕-前置通知");
Object[] args = pjp.getArgs();
rtValue=pjp.proceed(args);
System.out.println("纯xml自定义环绕-后置通知");
}catch(Throwable t){
System.out.println("纯xml自定义环绕-异常通知");
throw new RuntimeException(t);
}finally{
System.out.println("纯xml自定义环绕-最终通知");
}
return rtValue;
}
}
3.前端
3.1 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">
<!--springmvc的调控制中心-->
<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.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>
<!--
/ 拦截的是除了.jsp外的所有请求
/* 是拦截所有当前的文件夹,不包含子文件夹
/** 是拦截所有的文件夹及里面的子文件夹
-->
<!--编码过滤器-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<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>
<!--Session过期时间-->
<session-config>
<session-timeout>300</session-timeout>
</session-config>
</web-app>
3.2 index.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/5
Time: 1:14
To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
<!DOCTYPE HTML>
<html>
<head>
<title>首页</title>
<script src="${pageContext.request.contextPath}/static/js/jquery-3.4.1.js"></script>
</head>
<h1>登录页面</h1>
<hr>
<body>
<form action="${pageContext.request.contextPath}/user/login">
用户名:<input type="text" name="username"> <br>
密码: <input type="password" name="password"> <br>
<input type="submit" value="提交">
</form>
<span>信息:${info}</span>${info}
</body>
</html>
3.3 error.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/7
Time: 23:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<script type="text/javascript">
alert("请输入正确的账号和密码!");
window.location.href="index.jsp";
</script>
</body>
</html>
3.4 failLogin.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/7
Time: 21:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
请先进行登录,再进行页面访问!
<a href="${pageContext.request.contextPath}/index.jsp" >登录</a>
</body>
</html>
3.6 addBook.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/5
Time: 1:19
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增书籍</title>
<meta name="viewport" content="width=device-width, initialscale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>新增书籍</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/addBook"
method="post">
书籍名称:<input type="text" name="bookName"><br><br><br>
书籍数量:<input type="text" name="bookCounts"><br><br><br>
书籍详情:<input type="text" name="detail"><br><br><br>
<input type="submit" value="添加">
</form>
</div>
</body>
</html>
3.7 allBook.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/5
Time: 1:16
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍列表</title>
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/static/js/jquery-3.4.1.js"></script>
<script>
function check(){
$.post({
url:"${pageContext.request.contextPath}/book/check",
data:{'name':$("#queryBookName").val()},
success:function (data) {
console.log(data);
if(data==="yes"){
$("#info").css("color","green");
$("#info").html("有此书");
}else {
$("#info").css("color","red");
$("#info").html("无此书");
}
}
});
}
</script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-4 column">
<div class="page-header">
<h1>
<small>书籍列表 —— 显示所有书籍</small>
</h1>
</div>
</div>
<div class="col-md-4 column">
<div class="page-header">
<a class="btn btn-primary"
href="${pageContext.request.contextPath}/file/goUpload">上传文件页面
</a>
</div>
</div>
<div class="col-md-4 column">
<div class="page-header">
<h1>
<a class="btn btn-primary"
href="${pageContext.request.contextPath}/user/logout">退出登录
</a>
</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 column">
<a class="btn btn-primary"
href="${pageContext.request.contextPath}/book/toAddBook">新增
</a>
<a class="btn btn-primary"
href="${pageContext.request.contextPath}/book/allBook">显示全部书籍
</a>
</div>
<div class="col-md-4 column"></div>
<div class="col-md-4 column">
<form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
<span style="color:red;font-weight: bold">${error}</span>
<input type="text" id="queryBookName" name="queryBookName" onblur="check()"
class="form-control" placeholder="输入查询书名" required>
<span id="info"></span>
<input type="submit" value="查询" class="btn btn-primary">
</form>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-hover table-striped">
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名字</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${requestScope.get('list')}">
<tr>
<td>${book.getBookID()}</td>
<td>${book.getBookName()}</td>
<td>${book.getBookCounts()}</td>
<td>${book.getDetail()}</td>
<td>
<a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a> |
<a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
3.8 updateBook.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/5
Time: 1:21
To change this template use File | Settings | File Templates.
--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>修改信息</title>
<meta name="viewport" content="width=device-width, initialscale=1.0">
<!-- 引入 Bootstrap -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<div class="page-header">
<h1>
<small>修改信息</small>
</h1>
</div>
</div>
</div>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<input type="hidden" name="bookID" value="${book.getBookID()}"/>
书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/>
书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
<input type="submit" value="提交"/>
</form>
</div>
</body>
</html>
3.9 upload.jsp
<%--
Created by IntelliJ IDEA.
User: Bright
Date: 2020/4/8
Time: 0:51
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/file/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file"/>
<input type="submit" value="上传">
</form>
<a href="${pageContext.request.contextPath}/file/download">点击下载</a>
<img src="${pageContext.request.contextPath}/static/picture/timg.jpg" width="800" height="500"/>
</body>
</html>
4.那些走过的坑
4.1 配置Module
4.2 配置artifacts
每次加入依赖后,都需要去artifacts把包导入lib目录
4.3 IDEA的 action
在运行模式下,四个选项分别是: 1更新静态资源;2更新静态资源;3更新静态资源和java;4 重新服务器更新所有文件。
在调试模式下: 1更新静态资源;2更新静态资源和java;3更新静态资源和java,4 重新服务器更新所有文件
4.4前端获取项目路径
4.5 web.xml加载总配置
### 4.6 Mybatis给实体类起的别名
Mybatis 用package给包里面的类起别名后,以这个类的名字的全部字母不区分大小写作为新别名,例如Blog - 》 BLOG / bLOg/…
4.6 Spring扫描bean后的别名
用@ComponentScan()后,类的新名为首字母小写:BookService -> bookService ,其他形式都不能用。
但如果这个类是两个大写字母开头,则新类名为原名 BOokService->BOokService其他形式都不能用。
4.7 Mysql8.0
mysql8.0及以上的版本的数据局驱动需要加cj