SpringMVC
Spring Web MVC是基于Servlet API构建的原始Web框架,从一开始就包含在Spring框架中。它的正式名称“Spring Web MVC”来自于它的源模块(Spring -webmvc)的名称,但它更常见的名称是“Spring MVC”。
1.SpringMVC执行流程
SpringMVC的核心是DispatcherServlet
之前在javaweb原生的servlet中,每一个Servlet都需要在web.xml里面通过< servlet >与< servlet-mapping >配置路径,而DispatcherServlet的主要作用之一就是实行对所有servlet的同一管理,用户实际上都是在向DispatcherServlet发送请求,接收DispatcherServlet返回的响应。
这是我自己绘制的流程图:
1.1HelloSpringMVC实例:
注意:这个简单实例是为了解释上面的流程而设置的,实际上开发中有一些是不用的,但本质一样。
同时:上面的完整流程绝大多数是Spring完成的,我们需要做的比较少。
1.首先,创建一个maven项目
需要的包:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
2.在web.xml中配置DispatcherServlet
下面的这个配置实际上可以作为通用的配置,而且web.xml中只需要这些。
有一个可能修改:classpath:Springmvc-servlet.xml这个指向了Spring关于SpringMVC的配置。
<?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">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:Springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--HandlerMapping装配-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--HandlerAdapter装配-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--ViewResolver的装配-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--为了保证HandlerMapping可以匹配到一个Controller-->
<bean id="/hello" class="com.xiao.control.HelloController"/>
</beans>
HelloControler类(之后不会这么写)
package com.xiao.control;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//对象mv用来装载业务层返回的数据与视图层的相关信息,所以叫ModelAndView
ModelAndView mv = new ModelAndView();
//调用service的真实业务(这里模拟一下)
String name = "SpringMVC";
//将数据封装到mv中
mv.addObject("name",name);
//将即将跳转的视图名封装在mv中
mv.setViewName("hello");
return mv;
}
}
hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Hello</h1>
${name}
</body>
</html>
1.2注意点
在项目打包之前必须注意第三方jar包是不是在target文件中
步骤:
- File—>Progect Structer—>Artifacts
- 在项目中新建lib目录
3.将所有项目中需要的jar包添加到lib里面
2.注解简化版
上面的步骤显然十分麻烦,甚至比原生的servlet还麻烦。而springMVC的开发流程实际上十分简单。
简化步骤:
1.导包
2.在web.xml里面配置DisPatcherServlet(还有filter)
```xml <?xml version=”1.0” encoding=”UTF-8”?>
> 3.配置springmvc.xml
> 简化版:
>xml
<?xml version=”1.0” encoding=”UTF-8”?>
> 带有JSON编码配置的加强版:
>xml
<?xml version=”1.0” encoding=”UTF-8”?>
> 4.mapper.service实现类
> mapper:[注意装配SqlSessionTamplate]
>java
package com.xiao.mapper;
import com.xiao.entity.User;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserMapperImpl implements UserMapper {
@Autowired
private SqlSessionTemplate sqlSession;
public SqlSessionTemplate getSqlSession() {
return sqlSession;
}
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
//……
}
> service:[注意装配UserMapper]
>java
package com.xiao.service;
import com.xiao.entity.User;
import com.xiao.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public UserMapper getUserMapper() {
return userMapper;
}
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
//……
}
> 5.Conrol业务代码
>java
package com.xiao.control;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiao.entity.User;
import com.xiao.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Control {
@RequestMapping(“/test”)
public String test(Model model,int id) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ApplicationContext context = new ClassPathXmlApplicationContext(“Application.xml”);
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
User user = bean.selectOne(id);
model.addAttribute(“user”,user);
return “total”;
}
@RequestMapping(“/test1_2”)
@ResponseBody
public String test1_2(Model model,int id) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ApplicationContext context = new ClassPathXmlApplicationContext(“Application.xml”);
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
User user = bean.selectOne(id);
model.addAttribute(“user”,user);
return new ObjectMapper().writeValueAsString(user);
}
}
> 关键注解:
> - @Repository【@Component的衍生】,表示为Mapper
> - @Service【@Component的衍生】,表示为Service
> - @Control【@Component的衍生】,表示为Control
> - @RequestMapping("/test"),路径配置
> - @ResponseBody,与json,ajax一起使用,返回的不是跳转的视图名,而是返回一个字符串。【这里使用了jackson处理json】。
<a name="3.JSON"></a>
## 3.JSON
> [JSON](https://baike.baidu.com/item/JSON)([JavaScript](https://baike.baidu.com/item/JavaScript) Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 [ECMAScript](https://baike.baidu.com/item/ECMAScript) (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
**JSON实际上就是把对象转化为字符串传输**
js中对JSON的处理:
>javascript
JSON.stringify();//将对象转化为json字符串
JSON.parse();//将json字符串解析为对象
java对JSON的处理:
>xml
> 上面是需要的jar包
>java
@RequestMapping(“/test1_2”)
@ResponseBody
public String test1_2(Model model,int id) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ApplicationContext context = new ClassPathXmlApplicationContext(“Application.xml”);
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
User user = bean.selectOne(id);
model.addAttribute(“user”,user);
return mapper.writeValueAsString(user);
}
> 这是一个Control中的方法:
> - 前面都是在获取对象(从Spring容器里面取出Service对象,执行方法获取对象)
> - ObjectMapper类的作用就类似于js里面的JSON
> - mapper.writeValueAsString(user);就相当于JSON.stringify();//将对象转化为json字符串
<a name="4.AJAX"></a>
## 4.AJAX
> AJAX的目的是在不刷新页面的前提下完成对页面内容的更新,是在javaScript中完成的。
<a name="be98ca21"></a>
### 4.1前端Express服务框架
> 不同于后端,前端使用很少的代码就可以搭建一个网页
步骤:
【下面的操作是在集成终端操作的】
1.使用node.js搭建服务器
npm init —yes
2.创建expres框架支持:
npm i express
3.开始创建:javascript
//1.引入Express
const express = require(‘express’);
//2.创建应用对象
const app = express();
var person={
id:1,
name:’xiao’,
age:18,
height:175
}
//3.创建路由规则
app.get(‘/server’,(request,response)=>{
//设置响应头
response.setHeader(‘Access-Control-Allow-Origin’,’‘);
response.send(JSON.stringify(person));
})
app.post(‘/server’,(request,response)=>{
//设置响应头
response.setHeader(‘Access-Control-Allow-Origin’,’*’);
response.send(JSON.stringify(person));
})
app.listen(8000,()=>{
console.log(‘8000端口监听中……’);
})
4.启动服务:
> 补充:在集成终端中输入Ctrl+C可以终止服务。
现在:服务端有了可以返回响应的路径,测试AJAXjavascript
<!DOCTYPE html>
Pesponse
> 核心:
> 1.绑定事件(点击,悬浮等时触发):
> 2.创建xhr = new XMLHttpRequest();对象
> 3.初始化<br />
xhr.open('GET','http://localhost:8000/server');指定路径;
> 4.发送<br />
xhr.send();【在POST方法时可以加入参数,如xhr.send('a=1')】
> 5.等待完全接收到响应后对响应做出操作:
>javascript
xhr.onreadystatechange = function(){
//表明响应完毕
if(xhr.readyState === 4){
//表明响应正常
if(xhr.status>=200 && xhr.status <300){
//......处理Response
}
}
};
```
> 直到操作完成,页面不发生跳转
效果:【点击按钮后显示如下】
> 注意点:response体的内容整体是String,当在后台处理后并没有收到结果,返回的也是”null”长度为4的字符串。
# SSM整合
## 结构:
配置文件核心:
### 1.myBatisConfig.xml
#### 【实际上可以在Spring-mybatis中完成所有配置,可以没有】(给个面子)
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.xiao.entity"/>
</typeAliases>
</configuration>
### 2.Spring-myBatis.xml
> 1.数据源配置【这里使用Spring自带的数据库连接池,也可以使用dbcp,c3p0等】
> 2.sqlSessionFactory
> 3.sqlSession
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="data_Source" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///jdbcstudy?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="data_Source"/>
<property name="configLocation" value="classpath:myBatisConfig.xml"/>
<property name="typeAliasesPackage" value="com.xiao.entity"/>
<property name="mapperLocations" value="classpath:com/xiao/mapper/UserMapper.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
### 3.Spring-Service.xml
> 1.包扫描
> 2.声明式事务管理
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.xiao.mapper"/>
<context:component-scan base-package="com.xiao.service"/>
<!--要开启 Spring 的事务处理功能,在 Spring 的配置文件中创建一个 DataSourceTransactionManager 对象-->
<bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="data_Source"/>
</bean>
</beans>
### 4.Spring-MVC.xml
> 1. < mvc:annotation-driven >注解驱动(里面配置JSON编码设置)
> 4. 视图解析器(主要配置前缀与后缀)
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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.xiao.control"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
### 5.Application.xml
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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-mvc.xml"/>
<import resource="classpath:spring-mybatis.xml"/>
<import resource="classpath:spring-service.xml"/>
</beans>
### 6.Web.xml
```xml
<?xml version=”1.0” encoding=”UTF-8”?>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<a name="687ad725"></a>
### 7entity,mappe与service
> Entity实体类可以起一个别名(当然在myBatisConfig.xml与Spring-myBatis.xml中都可以配置)
> Mapper注意加上@Repository与@Autowired装配SqlSessonTamplate
> Service注意加上@Service与@Autowired装配Mapper
<a name="8.Mapper.xml"></a>
### 8.Mapper.xml
```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.xiao.mapper.UserMapper">
<select id="selectAll" resultType="user">
select * from `mybatis`.`user`
</select>
<select id="selectOne" parameterType="_int" resultType="user">
select * from mybatis.user where id=#{id}
</select>
<update id="update" parameterType="user">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
<insert id="add" parameterType="user">
insert into mybatis.user (name,pwd)values(#{name},#{pad})
</insert>
<delete id="delete" parameterType="_int">
delete from mybatis.user where id=#{id}
</delete>
</mapper>
9.Control与前端静态资源[主要关注点]
package com.xiao.control;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiao.entity.User;
import com.xiao.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class Control {
@RequestMapping("/init")
public String init(){
return "total";
}
@RequestMapping("/test")
public String test(Model model,int id) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ApplicationContext context = new ClassPathXmlApplicationContext("Application.xml");
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
User user = bean.selectOne(id);
model.addAttribute("user",user);
return "total";
}
@RequestMapping("/test1_2")
@ResponseBody
public String test1_2(Model model,int id) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ApplicationContext context = new ClassPathXmlApplicationContext("Application.xml");
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
User user = bean.selectOne(id);
model.addAttribute("user",user);
return new ObjectMapper().writeValueAsString(user);
}
@RequestMapping("/test2")
public String test2(Model model) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ApplicationContext context = new ClassPathXmlApplicationContext("Application.xml");
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
model.addAttribute("users",bean.selectAll());
return "total";
}
}
简单测试:
index.html:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<style>
a{
font-family: "Arial Narrow";
font-size: medium;
position: center;
}
</style>
</head>
<body>
<a href="${pageContext.request.contextPath}/init">前往总页面</a>
</html>
total.html:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">
<style>
#test_result{
width: 500px;
height: 100px;
border: solid 2px rgb(226, 40, 40);
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<form action="${pageContext.request.contextPath}/test" method="get" >
<fieldset id="form">
userid:<input type="text" id="id" name="id" value="${id}"/>
<button onclick="setUser()">查询</button>
</fieldset>
</form>
<button onclick="setUser()">AJAX式查询</button>
<form action="${pageContext.request.contextPath}/test2" method="get">
<fieldset>
<legend>查询全部</legend><button type="submit" class="btn">查询</button>
</fieldset>
</form>
<table class="table table-bordered table-hover" contenteditable="true">
<thead>
<tr><th>id</th>
<th>name</th>
<th>pwd</th>
</tr>
</thead>
<tbody>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.pwd}</td>
</tr>
<c:forEach var="aUser" items="${users}">
<tr>
<td>${aUser.id}</td>
<td>${aUser.name}</td>
<td>${aUser.pwd}</td>
</tr>
</c:forEach>
</tbody>
</table>
<div id="test_result">
<table class="table table-bordered table-hover" contenteditable="true">
<thead>
<tr><th>id</th>
<th>name</th>
<th>pwd</th>
</tr>
</thead>
<tbody>
<tr>
<td id="userid"></td>
<td id="username"></td>
<td id="userpwd"></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</body>
<script type="application/javascript">
let setSrc, userid,result;
let Taruser;
let id,name,pwd;
setUser = function () {
const xhr = new XMLHttpRequest();
result = document.getElementById('test_result');
userid =document.getElementById('id').value;
if(userid.length == 0){
document.getElementById('userid').innerHTML = 'No Id is given';
}
else {
if(!isNaN(Number(userid))){
xhr.open('GET','http://localhost:8080/SSM/test1_2?id='+Number(userid));
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <= 300){
console.log(xhr.response);
Taruser = JSON.parse(xhr.response);
if(xhr.response === 'null'){
document.getElementById('userid').innerHTML = 'No Such id';
document.getElementById('username').innerHTML = '';
document.getElementById('userpwd').innerHTML = '';
}
else {
id = document.getElementById('userid');
name = document.getElementById('username');
pwd = document.getElementById('userpwd');
id.innerHTML = Taruser.id;
name.innerHTML = Taruser.name;
pwd.innerHTML = Taruser.pwd;
}
}
}
}
}
}
};
</script>
</html>
效果:
点击后跳转至total.jsp
在userid中输入数字后点击第一个查询按钮在白边框中实现页面刷新式的请求
点击AJAX式查询后获取userid,并对不同情况在红框中输出
点击查询全部下的按钮会在白色边框中输出全部的User.
上述的AJAX实现代码:(写了两个小时)
let setSrc, userid,result;
let Taruser;
let id,name,pwd;
setUser = function () {
const xhr = new XMLHttpRequest();
result = document.getElementById('test_result');
userid =document.getElementById('id').value;
if(userid.length == 0){
document.getElementById('userid').innerHTML = 'No Id is given';
}
else {
if(!isNaN(Number(userid))){
xhr.open('GET','http://localhost:8080/SSM/test1_2?id='+Number(userid));
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status <= 300){
console.log(xhr.response);
Taruser = JSON.parse(xhr.response);
if(xhr.response === 'null'){
document.getElementById('userid').innerHTML = 'No Such id';
document.getElementById('username').innerHTML = '';
document.getElementById('userpwd').innerHTML = '';
}
else {
id = document.getElementById('userid');
name = document.getElementById('username');
pwd = document.getElementById('userpwd');
id.innerHTML = Taruser.id;
name.innerHTML = Taruser.name;
pwd.innerHTML = Taruser.pwd;
}
}
}
}
}
}
};
