一、将html页面与服务器相连接
首先,在前面的博客中,写到了html版本的表白墙 现在,需要将html版本的表白墙与后端服务器进行连接 代码如下:
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class Message{
public String from;
public String to;
public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
private ObjectMapper objectMapper=new ObjectMapper();
private List<Message> list=new ArrayList<Message>();
@Override
public void init(){
Message message=new Message();
message.from="A";
message.to="B";
message.message="hello";
list.add(message);
message=new Message();
message.from="C";
message.to="D";
message.message="你好";
list.add(message);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json;charset=utf-8");
objectMapper.writeValue(resp.getWriter(),list);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Message message=objectMapper.readValue(req.getInputStream(), Message.class);
resp.setContentType("application/json;charset=utf-8");
list.add(message);
resp.getWriter().write("{\"ok\":1}");
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ConfessionWall</title>
</head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<body>
<div class="container">
<h1>表白墙</h1>
<p>输入后点击提交,会将信息显示在表格中</p>
<div class="row">
<span>谁:</span>
<input type="text" class="edit">
</div>
<div class="row" >
<span>对谁:</span>
<input type="text" class="edit">
</div>
<div class="row">
<span>说什么:</span>
<input type="text" class="edit">
</div>
<div class="row">
<input type="button" value="提 交" id="submit">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function load(){
$.ajax({
type:'get',
url:'message',
success:function(data,status){
let messages=data;
let container=document.querySelector('.container');
for(let message of messages){
let row =document.createElement('div');
row.className='row';
row.innerHTML=message.from+'对'+message.to+'说:'+message.message;
container.appendChild(row);
}
}
});
}
load();
let submitButton=document.querySelector('#submit');
submitButton.onclick=function(){
let edits=document.querySelectorAll('.edit');
let from=edits[0].value;
let to=edits[1].value;
let message=edits[2].value;
console.log(from,to,message);
if(from==''||to==' '||message==''){
return;
}
let row=document.createElement('div');
row.className='row';
row.innerHTML=from+'对'+to+'说:'+message;
let container=document.querySelector('.container');
container.appendChild(row);
for(let i=0;i<edits.length;i++){
edits[i].value='';
}
$.ajax({
type:"POST",
url:"message",
data:JSON.stringify({from:from,to:to,message:message}),
contentType:"application/json;charset:utf-8",
success:function(data,status){
if(data.ok==1){
console.log('成功');
}else{
console.log('失败');
}
}
})
}
</script>
<style>
*{
margin:0;
padding: 0;
box-sizing: border-box;
}
.container{
width: 400px;
margin:0 auto;
}
h1{
text-align:center;
padding:20px auto;
}
p{
text-align:center;
color:#666;
padding: 10px 0;
font-size:14px;
}
.row{
height:50px ;
display: flex;
justify-content: center;
align-items:center;
}
span{
width:90px;
font-size: 20px;
}
input{
width:310px;
height: 40px;
font-size: 18px;
}
#submit{
width: 400px;
color: white;
background-color:orange;
border:none;
border-radius:5px;
font-size: 18px;
}
#submit:active{
background-color: black;
}
</style>
</div>
</body>
</html>
完成截图
此时,与前面html版本相比,这个连接了服务器,当页面刷新的时候,已提交的数据仍然存在 但是,此时数据是保存在内存当中,不是永久保存,当服务器重启的时候,会彻底更新,不会保存已经输入的数据 所以,此时,要想永久保存,有两种方式,一是:保存在文件当中,二是保存在数据库当中
把字符串按照JSON格式解析成对象: 在JS当中,let message=JSON.parse(data ); 在Java当中,Message message=ObjectMapper.readValue(req.InputStreaam(),Message.class()); 把对象转化成字符串 在JS当中,JSON.stringfy(); 在Java当中,objectMapper.writeValue(resp.getWriter(),list); Content-Type是一个text/html text/plain body的数据格式是string Content-Type是一个application/json body的数据格式会被jQuery自动转化成object/Array 当body的数据是 字符串,需要借助let message=JSON.parse(data ),转化成对象/Array
二、将html页面提交的数据保存在文件当中
下面展示,将服务的数据保存在 文件当中 html的代码不变
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
class Message2{
public String from;
public String to;
public String message;
}
@WebServlet("/message")
public class MessageServlet2 extends HttpServlet {
private ObjectMapper objectMapper=new ObjectMapper();
private String filePath="d:/message.txt";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json;charset=utf-8");
List<Message> messageList=load();
objectMapper.writeValue(resp.getWriter(),messageList);
}
private List<Message> load() {
List<Message> messageList=new ArrayList<>();
System.out.println("从文件加载!");
try(BufferedReader bufferedReader =new BufferedReader(new FileReader(filePath))){
while(true){
String line=bufferedReader.readLine();
if(line==null){
break;
}
String[] tokens=line.split("\t");
Message message=new Message();
message.from=tokens[0];
message.to=tokens[1];
message.message=tokens[2];
messageList.add(message);
}
}catch(IOException e){
e.printStackTrace();
}
return messageList;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Message2 message=objectMapper.readValue(req.getInputStream(), Message2.class);
resp.setContentType("application/json;charset=utf-8");
save(message);
resp.getWriter().write("{\"ok\":1}");
}
private void save(Message2 message) {
System.out.println("向文件中写数据");
try(FileWriter fileWriter=new FileWriter(filePath,true)){
fileWriter.write(message.from+"\t"+message.to+"\t"+message.message+"\n");
}catch(IOException e){
e.printStackTrace();
}
}
}
访问路径: http://localhost:8080/Light_demo1/ConfessionWall.html(这个是根据自己电脑的路径来选择) 将html前端输入的信息保存在 D:/message.txt当中 当重新启动服务器的时候,不仅文件当中的信息仍然存在,页面也会显示出文件中已经存在的信息 >
很多语言中, 打开文件的方式主要有三种: 1.读方式打开,使用输入流对象的方式 2.写方式打开,使用输出流对象的方式(直接写方式打开,会清空文件的原有内容) 3.追加写方式打开,使用输出流对象的时候,不会清空文件的原有内容,而是直接往最后添加
三、将html页面提交的数据保存在数据库当中
下面,写一下,如何将html页面提交的数据放在数据库当中 1.创建数据库 2.服务器与数据库进行连接
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
class Message3{
public String from;
public String to;
public String message;
}
@WebServlet("/message")
public class MessageServlet3 extends HttpServlet {
private ObjectMapper objectMapper=new ObjectMapper();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("application/json;charset=utf-8");
List<Message> messageList=load();
objectMapper.writeValue(resp.getWriter(),messageList);
}
private List<Message> load() {
List<Message> messageList=new ArrayList<>();
System.out.println("从数据库中读取数据");
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
try {
connection = DBUtil.getConnection();
String sql = "select *from message";
statement=connection.prepareStatement(sql);
resultSet = statement.executeQuery();
while (resultSet.next()) {
Message message = new Message();
message.from = resultSet.getString("from");
message.to = resultSet.getString("to");
message.message = resultSet.getString("message");
messageList.add(message);
}
}catch(SQLException e){
e.printStackTrace();
}finally {
DBUtil.close(connection,statement,resultSet);
}
return messageList;
}
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws IOException {
Message3 message3=objectMapper.readValue(req.getInputStream(),Message3.class);
save(message3);
resp.setContentType("application/json;charset=utf-8");
resp.getWriter().write("{\"ok\":1");
}
private void save(Message3 message3) {
System.out.println("向数据库中写入数据");
Connection connection=null;
PreparedStatement statement=null;
try{
connection=DBUtil.getConnection();
String sql="insert into message values(?,?,?)";
statement=connection.prepareStatement(sql);
statement.setString(1,message3.from);
statement.setString(2,message3.to);
statement.setString(3,message3.message);
int ret=statement.executeUpdate();
if(ret==1){
System.out.println("插入成功");
}else{
System.out.println("插入失败");
}
}catch(SQLException e){
e.printStackTrace();
}finally{
DBUtil.close(connection,statement,null);
}
}
}
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBUtil {
private static final String URL="jdbc:mysql://127.0.0.1:3306/java100?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
private static final String USERNAME="root";
private static final String PASSWORD="root";
private static DataSource dataSource =null;
public static DataSource getDataSource(){
if(dataSource==null){
synchronized(DBUtil.class){
if(dataSource==null){
dataSource=new MysqlDataSource();
((MysqlDataSource)dataSource).setURL(URL);
((MysqlDataSource)dataSource).setUser(USERNAME);
((MysqlDataSource)dataSource).setPassword(PASSWORD);
}
}
}
return dataSource;
}
public static Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
if(resultSet!=null){
try {
resultSet.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(preparedStatement!=null){
try{
preparedStatement.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(connection !=null){
try{
connection.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
结果截图:
|