Java高级 SSM项目部署以及ajax的详细使用过程
[toc]
前言
很多刚开始学习JavaEE的新手同学,都或多或少地觉得使用Ajax来实现http请求是一件棘手的事情。今天我通过写一个简单的案例来给大家一个清晰的流程和思路。案例比较简单,希望能帮上大家。下面附上我的代码分解:
1、开发环境
jdk8 + tomcat8 + idea2019 + MySql8 + SQLyog
2、数据库
/*
Navicat MySQL Data Transfer
Source Host : localhost:3306
Source Database : mybatis
Target Host : localhost:3306
Target Database : mybatis
Date: 2021-09-26 11:24:31
*/
/*执行sql脚本时,不让外键受影响导致出错*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(32) NOT NULL COMMENT '用户名称',
`password` VARCHAR(255) DEFAULT NULL,
`birthday` DATE DEFAULT NULL COMMENT '生日',
`sex` CHAR(1) DEFAULT NULL COMMENT '性别',
`address` VARCHAR(256) DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '张三', '123', '2014-07-10', '2', '成都市');
INSERT INTO `user` VALUES ('2', '李四', '123', '2014-07-10', '1', '成都市');
INSERT INTO `user` VALUES ('3', '王五', '123', '2014-07-10', '1', '重庆市');
INSERT INTO `user` VALUES ('4', '赵六', '123', '2014-07-10', '1', '重庆市');
INSERT INTO `user` VALUES ('5', '田七', '123', '2014-07-10', '1', '扬州市');
INSERT INTO `user` VALUES ('6', '迪迦', '222', '2014-07-10', '1', '扬州市');
INSERT INTO `user` VALUES ('7', '泰罗', '222', '2014-07-10', '2', '北京市');
INSERT INTO `user` VALUES ('8', '艾斯', '222', '2017-05-03', '1', '北京市');
INSERT INTO `user` VALUES ('9', '爱迪', '222', '2017-05-03', '2', '昆明市');
3、工程配置
在idea中创建maven工程“ajaxDemo”,然后进行以下配置:
3.1 项目结构
3.2 配置工程支持WEB开发
在File选项卡中找到Project Structure选项进入
在Project Settings里找到Modules,点击左上方”+”,找到WEB模块,点击确定加入WEB模块
点击添加的WEB模块位置,将Deployment Descriptors里面的path修改成刚才我们建立的web.xml文件的位置
在Web Resource Directories里面的路径修改成我们的web路径
点击Artfacts选项,点击“+”,选择Web Application:Exploaded,选择from modules,找到我们刚才建立的web工程点击确定,这样才能让我们可以在WEBAPP目录下建立JSP文件,并且tomcat服务器找到该WEB项目进行部署和运行。
3.3 配置文件
3.3.1 spring-dao.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 读取配置-->
<context:property-placeholder location="classpath*:jdbc.properties"/>
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 设置数据源 -->
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:mapper/*.xml"/>
</bean>
<!-- 配置Mapper扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 设置Mapper扫描包 -->
<property name="basePackage" value="com.wedu.dao" />
</bean>
<!-- 配置Service扫描 -->
<context:component-scan base-package="com.wedu.service" />
<bean id="userService" class="com.wedu.service.impl.UserServiceImpl"></bean>
</beans>
3.3.2 spring-service.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置Service扫描 -->
<context:component-scan base-package="com.wedu.service" />
</beans>
3.3.3 spring-trans.xml配置文件(事务相关配置,目前的这个demo用不上,大家可以先看看)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="query*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.wedu.service.*.*(..))" />
</aop:config>
<!-- <jdbc:embedded-database id="dataSource"/>-->
</beans>
3.3.4 spring-mvc.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置Controller扫描 -->
<context:component-scan base-package="com.wedu.controller" />
<!-- 配置注解驱动 -->
<mvc:annotation-driven />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/pages/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<mvc:interceptors>
<!-- 拦截器记录操作日志 -->
<!-- 使用bean直接定义在<mvc:interceptors>下面的拦截器将拦截所有请求 -->
<!-- 这个是全局的,当使用下面的拦截器时,需要把这个拦截器注释掉 -->
<!-- <bean class="com.springmvc.interceptor.MyInterceptor"/>-->
<!-- 定义多个拦截器,顺序执行 -->
<mvc:interceptor> <!-- 拦截器 -->
<mvc:mapping path="/**"/> <!-- 配置拦截器作用的路径 /**表示拦截所有url路径包括子url路径-->
<mvc:exclude-mapping path="/resources/**"/> <!-- 配置不需要拦截器作用的路径 -->
<!-- 定义在<mvc:interceptor>下面的拦截器,表示匹配路径请求才进行拦截 -->
<bean class="com.wedu.interceptor.JournalInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题-->
<mvc:annotation-driven >
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter" >
<property name = "supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
<!-- application 可以在任意 form 表单里面 enctype 属性默认找到 -->
<value>application/x-www-form-urlencoded</value>
</list>
</property>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>
</beans>
3.3.5 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">
<display-name>ajaxProject</display-name>
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</context-param>
<!-- 配置监听器加载spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置过滤器,解决post的乱码问题 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 使用filter实现登录控制 -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.wedu.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<!-- 所有的页面需要登录后才能访问 -->
<url-pattern>/pages/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<!-- 日志功能需要登录后才能访问 -->
<url-pattern>/journal/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC -->
<servlet>
<servlet-name>ProjectManagementSystem</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring/spring-mvc.xml</param-value>
</init-param>
<!-- 配置springmvc什么时候启动,参数必须为整数 -->
<!-- 如果为0或者大于0,则springMVC随着容器启动而启动 -->
<!-- 如果小于0,则在第一次请求进来的时候启动 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ProjectManagementSystem</servlet-name>
<!-- 所有的请求都进入springMVC -->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
3.3.6 jdbc.properties配置文件(数据库连接配置)
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ajaxdemo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=root
3.3.7 log4j.properties配置文件(日志文件配置)
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
3.3.8 mapper配置文件(sql语句)
<?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.wedu.dao.UserDao">
<select id="login" parameterType="com.wedu.bean.User" resultType="com.wedu.bean.User">
select * from user where username = #{username} and password = #{password}
</select>
</mapper>
4、创建类和jsp文件
4.1 创建实体类User
package com.wedu.bean;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String password;
private String address;
private Date birthday;
private char sex;
public User(Integer id, String username, String password, String address, Date birthday, char sex) {
this.id = id;
this.username = username;
this.password = password;
this.address = address;
this.birthday = birthday;
this.sex = sex;
}
public User() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", address='" + address + '\'' +
", birthday=" + birthday +
", sex=" + sex +
'}';
}
}
4.2 数据访问层UserDao,对应UserMapper
package com.wedu.dao;
import com.wedu.bean.User;
public interface UserDao {
User login(User user);
}
4.3 service层UserService
package com.wedu.service;
import com.wedu.bean.User;
public interface UserService {
User login(User user);
}
4.4 UserService的实现类UserServiceImpl
package com.wedu.service.impl;
import com.wedu.bean.User;
import com.wedu.dao.UserDao;
import com.wedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override @Transactional(propagation = Propagation.NOT_SUPPORTED)//如果是查询,事务挂起
public User login(User user) {
// TODO Auto-generated method stub
return userDao.login(user);
}
}
4.5 test,service层写好之后,可以写一个测试类测试数据是否能够访问到
package com.wedu.test;
import com.wedu.bean.User;
import com.wedu.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class test {
@Test
public void findUsers(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-dao.xml");
UserService userService = (UserService) context.getBean("userService");
User u = new User();
u.setUsername("王五");
u.setPassword("123");
User user =userService.login(u);
System.out.println(user.toString());
}
}
数据访问成功:
4.6 controller控制层
package com.wedu.controller;
import com.wedu.bean.User;
import com.wedu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 登录
*
* @param user
*/
@RequestMapping("login")
@ResponseBody
public User login(@RequestBody User user) {//使用@RequestBody Map<String,String> map也是可以的,接收前台传过来的参数
//返回用户信息,要使用@ResponseBody将返回值转换为JSON
return userService.login(user);
}
}
4.7 jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>登录</title>
<script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="js/jquery-3.3.1.js"></script>
<script src="js/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.css" />
<link rel="stylesheet" type="text/css"
href="bootstrap-3.3.7-dist/css/bootstrap.min.css" />
<style type="text/css">
td {
padding: 10px;
}
</style>
<script type="text/javascript">
var state = 0;//默认登录成功
$(document).ready(
function() {
//登录
$("#login").click(
function() {
$.ajax({
url : "user/login.do",
type : "POST",
/* data : "json", */
contentType : "application/json;charset=utf-8",
//向后端传输的数据
data : JSON.stringify({
username : $("#username").val(),
password : $("#password").val(),
}),
//处理后端返回的数据
success : function(result) {
//将得到的前台数据转换为json
/*var message = JSON.stringify(result);*/
alert("接受到的数据是:" + result);//输出默认的json字符串
console.log(result);
if (result != null && result != "") {
//alert("接受到的数据是:" + message.username);
var username = result.username;
console.log(username);
var password = result.password;
console.log(password);
//在前台做验证
if (username != null && username != ""
&& password != null
&& password != "") {
alert("用户登录成功");
window.location.href="https://liulei-root.github.io/";
} else {
alert("用户登录失败");
}
}else{
alert("用户登录失败");
}
//alert("接受到的数据是:" + message);
},
//处理失败返回的数据
error : function(result) {
alert("用户登录失败");
}
});
});
});
</script>
</head>
<body>
<form action="${pageContext.request.contextPath }/user/login.do"
method="post">
<div class="panel panel-default" style="width:400px; margin:40px auto">
<div class="panel-heading"
style="text-align:center;font-weight:bold;">用户登录</div>
<div class="panel-body">
<table style="width: 100%;">
<tr>
<td stylae="width: 30%; ">用户名:</td>
<td style="width: 70%; "><input type="text"
class="form-control" id="username" placeholder="请输入用户名"></td>
</tr>
<tr>
<td style="width: 30%; ">密 码:</td>
<td style="width: 70%; "><input type="password"
class="form-control" id="password" placeholder="请输入密码"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;">
<button type="button" class="btn btn-primary"
data-toggle="button" id="register">注册</button>
<button type="button" class="btn btn-primary"
data-toggle="button" id="login">登录</button>
</td>
</tr>
</table>
</div>
</div>
</form>
</body>
</html>
引入bootstrap和jquery:
最后配置tomcat运行。
结束!!!