拓展
@WebServlet("")是一个Java注解,用于定义一个Servlet类,该类可以处理关于内部路径的HTTP请求。内部方法常为重写doGet()方法。代码如下:
@WebServlet("/imgC")
public class ImgC extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
I/O流
具体流程为读==>写==>关闭资源。文件传输完成后会返回-1,具体代码如下:
//1.先把图片数据读进来
FileInputStream is = new FileInputStream(imgPath);
ServletOutputStream os = resp.getOutputStream();
//构建缓冲流,提高读写效率
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] bytes = new byte[1000];
//2.循环,边读边写
while ((bis.read(bytes)) != -1)
{
os.write(bytes);
}
//3.关闭资源
bos.flush();
bos.close();
bis.close();
os.close();
is.close();
οnclick="location.reload()" 点击事件内容为刷新页面
Servlet
在搭建好Servlet环境后可以在web文件包中创建html文件。然后可以直接使用@WebServlet("")中的地址名。语法如下:
@WebServlet("/deptC")
public class DeptC extends HttpServlet {
//引入service层
private IDeptService deptService=new DeptServiceImpl();
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("测试访问doget...");
List<Dept> list = deptService.list();
System.out.println(list);
//数据转换成json格式,再响应给浏览器
JsonUtil.transJason(list,resp);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/vue/vue.min.js"></script>
<script src="/vue/axios.min.js"></script>
</head><body><div id="app">
<button @click="showDept">点击显示数据</button>
<table border="1" cellspacing="0" cellpadding="20">
<tr>
<th>序号</th>
<th>部门名称</th>
<th>部门位置</th>
<th>部门领导</th>
</tr>
<tr v-for="dept in deptList">
<td>{{dept.did}}</td>
<td>{{dept.dname}}</td>
<td>{{dept.dlocation}}</td>
<td>{{dept.leader}}</td>
</tr>
</table></div>
</body>
<script>
new Vue({
el:'#app',
data:{
deptList:[]
},
methods:{
showDept(){
axios.get('http://localhost:8080/deptC').then((resp)=>{//then为回调函数 console.log(resp,resp.data)
this.deptList=resp.data
})
}
}
})
</script>
</html>
总结
Servlet回归到了网页前端的使用,整体语法还是围绕html,css,JS和vue来做。