在Linux上部署一个简单的JavaWeb项目,我的前一篇文章已经提到(宝塔Linux部署JavaWeb项目),当涉及到数据库操作时该怎么办呢??
相信大家对部署JavaWeb项目的流程已经不陌生,那就直奔主题!!!
1.准备一个的JavaWeb项目(最好已经在win上跑出来了),我的项目目录结构如下:
代码展示如下:
- index.jsp:
<body>
<form action="Login" method="post">
<table align="center" border="1">
<tr align="center">
<td colspan="2">个人信息</td>
</tr>
<tr>
<td>姓名:</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td>年龄:</td>
<td>
<input type="text" name="age">
</td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="登陆">
</td>
</tr>
</table>
</form>
</body>
效果如下:
- DbConnect.java:
注意!!!root的密码为:
public class DbConnect {
public static Connection conn;
public static Connection getConnection() {
try {
if (conn==null) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_person", "root", "你的root用户密码");
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
- LoginServlet.java:servlet需要在web.xml配置,
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
String name=request.getParameter("name");
String age=request.getParameter("age");
int count=0;
String sql="insert into person(name,age) value(?,?)";
try {
Connection coon=null;
coon=DbConnect.getConnection();
PreparedStatement ps=coon.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, Integer.valueOf(age));
count=ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (count==1) {
response.sendRedirect("love.jsp");
}else {
response.sendRedirect("index.jsp");
}
}
}
- web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.ls.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
love.jsp
<body>
<h1 align="center">成功!!!</h1>
</body>
2.将你的项目导出并且打包成war包,上传至宝塔Linux文件的 /www/server/tomcat/webapps 目录下
注意:把mysql-connector-java-5.1.7-bin.jar 导入到 /www/server/tomcat/lib 目录下
3.网站-创建一个站点:
4.数据库-创建一个数据库:
5.在软件管理里安装phpMyadmin,它是一个在网站主机上的MySQL的数据库管理工具,
使用phpMyadmin必须要在云服务器安全组和宝塔Linux安全中开放888端口!!
-
导出你的sql文件,将文件压缩,压缩格式为 数据库名.sql.zip
-
选择你新建的数据库,点击管理:
6.最后,重新启用tomcat,查看tomcat运行日志,看我博文:宝塔Linux下Tomcat运行日志
7.效果如下:
在浏览器地址栏输入: 域名/index.jsp,进入index.jsp页面,输入用户名,密码,点击登录,跳转到love.jsp页面。并显示“成功”信息,同时数据也将被保存进数据库,可在phpMyadmin里面查看。
查看phpMyadmin,这条数据已经被写进数据库啦!!!
8.终于写完,感觉自己要上天了!!!
亲测能用,绝对靠谱!!!