写在开头:本人以前做过ASP MVC,目前主要是前端,对于JAVA一直想去了解(因为目前项目是Angular 4 + Spring Boot),所以我还是想以c#的基础来尽快的了解到JAVA的开发。当然想短时间内去将JAVA全面了解很难,除非天资过人。我目前的计划如下:
Java 语言基础 (这个需要自行去了解了)
Java web 基础
Hibernate
Spring
Spring MVC
Spring Boot
在学习的过程中可能会有很多我们不懂的地方,但是我的目的是将流程能够跑出来,至于细节性的东西,就是后期的弥补了。
LoginServlet:接受前端form表单的提交
package com.java.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.java.domain.User;
import com.java.service.UserService;
/**
* Servlet implementation class LoginServlet
*/
//@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String name=request.getParameter("username");
String passwd=request.getParameter("password");
User user=new User();
user.setUsername(name);
user.setPassword(passwd);
UserService userservice=new UserService();
try {
User sessionuser=userservice.login(user);
request.getSession().setAttribute("sessionuser", sessionuser.getUsername());
response.sendRedirect("/java_web_basic/jsp/user/welcome.jsp");
} catch (Exception e) {
request.setAttribute("msg", e.getMessage());
request.getRequestDispatcher("/java_web_basic/login.jsp").forward(request, response);
}
}
}
LoginService: 处理请求业务逻辑,判断当前用户是否存在
package com.java.service;
import com.java.dao.UserDao;
import com.java.domain.User;
public class UserService {
private UserDao userdao = new UserDao();
public User login(User user) throws Exception {
User _user=userdao.findByUsername(user.getUsername());
if(_user==null)
{
throw new Exception("用户未找到");
}
if(!_user.getPassword().equals(_user.getPassword()))
{
throw new Exception("密码错误");
}
return _user;
}
}
UserDao:针对用户实体的数据操作
package com.java.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.java.domain.User;
import com.java.utils.Jdbc;
public class UserDao {
public User findByUsername(String username) {
String sql = "select *from USER";// SQL语句
Jdbc db1 = new Jdbc(sql);// 创建Jdbc对象
ArrayList userList = new ArrayList();
try {
ResultSet ret = db1.pst.executeQuery();// 执行语句,得到结果集
while (ret.next()) {
User user = new User();
user.setUsername(ret.getString(2));
user.setPassword(ret.getString(3));
userList.add(user);
}
ret.close();
db1.close();// 关闭连接
} catch (SQLException e) {
e.printStackTrace();
}
if (userList.size() != 1) {
return null;
} else {
return userList.get(0);
}
}
}
User:用户实体
package com.java.domain;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
JDBC(Utils):开始数据库操作的工具类
需要先引入mysql的架包。
package com.java.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Jdbc {
public static final String url = "jdbc:mysql://127.0.0.1:3306/user";
public static final String name = "com.mysql.jdbc.Driver";
public static final String user = "root";
public static final String password = "";
public Connection conn = null;
public PreparedStatement pst = null;
public Jdbc(String sql) {
try {
Class.forName(name);// 指定连接类型
conn = DriverManager.getConnection(url, user, password);// 获取连接
pst = conn.prepareStatement(sql);// 准备执行语句
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
this.pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
DemoFilter:这里创建没有作用,我只是看一下filter而已。
package com.java.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* Servlet Filter implementation class DemoFilter
*/
public class DemoFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("doFilter执行了");
chain.doFilter(req, res); //放行
System.out.println("执行完返回到客户端");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
Index.jsp:创建初始登录界面
<%@ page language="java" contentType="text/html; utf-8"
pageEncoding="utf-8"%>
Insert title here
登陆页面
welcome.jsp(WebContent/jsp/user/welcome.jsp):登录成功之后跳转到欢迎界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
<%
String user = (String)session.getAttribute("sessionuser");
if (user != null) {
%>
欢迎登录本系统!
<%
} else {
%>
<%
response.sendRedirect("/java_web_basic/");
%>
<%
}
%>
web.xml:配置相关信息 (servlet mapping就是映射关系,filter)
java_web_basic
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
LoginServlet
com.java.servlet.LoginServlet
LoginServlet
/Login
DemoFilter
com.java.filter.DemoFilter
DemoFilter
/*
mysql
-- MySQL dump 10.13 Distrib 5.7.21, for Win64 (x86_64)
--
-- Host: localhost Database: user
-- ------------------------------------------------------
-- Server version 5.7.21
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
`USER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`USERNAME` varchar(100) NOT NULL,
`PASSWORD` varchar(40) NOT NULL,
PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'rodchen','abc123_');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2018-05-06 16:27:17
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
指定了6个欢迎页面,显示时按顺序从第一个找起,如果第一个存在,就显示第一个,后面的不起作用。如果第一个不存在,就找第二个,以此类推。
访问一个网站时,默认看到的第一个页面就叫欢迎页,一般情况下是由首页来充当欢迎页的。一般情况下,我们会在web.xml中指定欢迎页。但 web.xml并不是一个Web的必要文件,没有web.xml,网站仍然是可以正常工作的。只不过网站的功能复杂起来后,web.xml的确有非常大用处,所以,默认创建的动态web工程在WEB-INF文件夹下面都有一个web.xml文件。
我们可以为Servlet和JSP文件命名并定制URL,其中定制URL是依赖命名的,命名必须在定制URL前。下面拿serlet来举例:
LoginServlet
com.java.servlet.LoginServlet
LoginServlet
/Login
可以定制servlet、JSP、Context的初始化参数,然后可以再servlet、JSP、Context中获取这些参数值。
LoginServlet
com.java.servlet.LoginServlet
userName
rod chen
password
abc123_
经过上面的配置,在servlet中能够调用getServletConfig().getInitParameter("param1")获得参数名对应的值。
404
/error404.jsp
-----------------------------
java.lang.Exception
/exception.jsp
DemoFilter
com.java.filter.DemoFilter
DemoFilter
/*
还有其他的配置,大家可以自行google。