文章目录
数据库连接
package net.lmq.dbutil;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.*;
public class ConnectionManager {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/news";
private static final String USER = "root";
private static final String PASSWORD = "1111";
//私有化
private ConnectionManager(){
}
//数据库连接
public static Connection getConnection() {
Connection conn = null;
try {
//安装驱动
Class.forName(DRIVER);
//获取数据库
conn = DriverManager.getConnection(URL,USER,PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭数据库
private static void closeConn(Connection conn){
try {
if (conn != null){
if (!conn.isClosed()){
conn.close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据池连接
<?xml version="1.0" encoding="utf-8" ?>
<Context>
<Resource
name="jdbc/news"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="1111"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/news"/>
</Context>
dbutil
package net.lmq.dbutil;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 功能:数据库连接管理类
* 作者:赖明庆
* 日期:2019年10月28日
*/
public class ConnectionManager {
/**
* 私有化构造方法,拒绝实例化
*/
private ConnectionManager() {
}
/**
* 获取数据库连接静态方法
*
* @return
*/
public static Connection getConnection() {
// 定义数据库连接
Connection conn = null;
try {
// 初始化上下文
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/news");
conn = ds.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 返回数据库连接
return conn;
}
}
重定向时:编码转换
response.sendRedirect("success.jsp?username=" + URLEncoder.encode(username,"utf-8"));
<%= new String(uname.getBytes("ISO8859-1"),"utf-8")%>
c标签,时间:
JSTLELDemo/demo04.jsp
ajax:提交数据
$(function () {
$("#login").click(function () {
var username = $("#username").val();
var password = $("#password").val();
//提交请求
$.ajax({
type:"post",
url:"/AjaxDemo/login",
data: {
"username":username,
"password":password
},
datatype:"json",
success:function (data) {
if(data=="success"){
$(location).attr('href','success.html?username='+username);
}else{
$(location).attr('href','failure.html?username='+username)
}
}
});
});
}
页面变量:session和application
application.setAttribute("LOGINED_USERS", loUsers);
<%
List<User> loUsers = (List<User>) application.getAttribute("LOGINED_USERS");
%>
session.setAttribute("errMsg","用户名或密码错误,请重新登录!");
<%
String errMsg = (String) session.getAttribute("errMsg");
if (errMsg != null) {
out.println("<script>alert('"+errMsg+"')</script>");
}
%>
和cookie
//创建cookie对象
Cookie uname = new Cookie("uname", username);
//写入客户端
response.addCookie(uname);
页面得到
<%
String uname = "";
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
if (cookie.getName().equals("uname")){
uname = cookie.getValue();
}
}
%>
文件上传:
//实例化上传组件
SmartUpload su = new SmartUpload();
//初始化
su.initialize(pageContext);
//定义上传文件的最大尺寸(单位:字节)
long FTLE_MAX_SIZE = 400000;
//判断文件类型是否符合要求
try {
//设置文件许可的上传类型
su.setAllowedFilesList("jpg,gif,png,bmp");
//上传文件
su.upload();
} catch (Exception e) {
out.print("<script>\n" +
" alert('只能上传jpg,gif,png或bmp文件');\n" +
" window.location='upload.html'\n" +
"</script>");
}
//获取上传的第一个文件
File file = su.getFiles().getFile(0);
//判断文件是否丢掉
if(file.isMissing()){
out.print("<script>\n" +
" alert('上传失败,请再次上传');\n" +
" window.location='upload.html'\n" +
"</script>");
}else {
if(file.getSize() <= FTLE_MAX_SIZE){
//获取上传文件表名
filename = file.getFileName();
//获取上传文件的扩展名
ext = file.getFileExt();
//利用时间戳与随机整数修改文件名
filename = filename.substring(0,filename.lastIndexOf(".")) + String.valueOf(System.currentTimeMillis()) +
String.valueOf((int) (Math.random() * 900)+100);
//获取应用程序的真实路径(物理路径)
String realPath = application.getRealPath("/");
//创建文件的url
String url = realPath + "upload\\" + filename+ "." + ext;
//将上传文件保存到指定位置
file.saveAs(url,SmartUpload.SAVE_PHYSICAL);
//提示用户上传成功
out.print("文件上传成功<br/>");
out.print("上传位置:"+ url + "<br/>");
}else {
out.print("<script>\n" +
" alert('上传文件太大,上传失败');\n" +
" window.location='upload.html'\n" +
"</script>");
}
}
文件下载:
//获取下载文件名
String filename = request.getParameter("filename");
//创建SmartUpload实例
SmartUpload su = new SmartUpload();
//初始化
su.initialize(pageContext);
//禁止浏览器自动打开文件
su.setContentDisposition(null);
//利用SmartUpload组件下载文件,web路径
su.downloadFile("/upload/" +filename);
分页:页面限制,得到数据列表,显示到页面
//获取全部新闻列表
List<News> allnews = newsDao.findAllNews();
// 生成当前页的新闻列表
List<News> newsList = new ArrayList<>();
for (int i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize; i++) {
if (i < count) {
newsList.add(allnews.get(i));
}
}
表格遍历
out.print("<table border=\"1\" cellpadding=\"10\" style=\"margin: 0px auto\">");
out.print("<th colspan=\"2\">2新闻栏目 </th>");
for(Topic topic: topics){
out.println("<tr>"+ "<td>" +topic.getTid()+ "</td>" + "<td>"+ topic.getTname() + "</td>" +"</tr>");
}
out.print("</th>");
out.print("</table>");