Servlet基础学习

拓展

@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来做。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值