java web 學習記錄一下
-
mvc結構實現mysql 連線
-
什麼是mvc
- MVC是模型(model)、檢視(view)、控制(controller)這三個單詞上的首字母組成。它是一種應用模型,它的目的是實現Web系統的職能分工。避免all in one 所有程式碼全部寫在一個檔案裡的一種分工模型。
-
實現簡單登入功能
- 登入成功,進入sccess.jsp介面,失敗返回首頁,並輸出密碼錯誤
資料庫簡單編寫
- 建立資料庫
create database student;
- 建立表
create table tbl_user(
userId varchar(11) not null
primary key,
passWord varchar(255) not null
);
- 匯入資料
insert into tbl_user (userId,passWord) values ('admin','1234');
insert into tbl_user (userId,passWord) values ('張三','1234');
idea上準備工作
- 建立一個乾淨的meavn專案
- 把該專案新增web專案
匯入依賴
- junit 是為了便於測試
- 其他是一些基礎包
- mysql 連線資料庫
- servlet-api servlet服務
- jsp-api
- jstl 寫el表示式
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b02</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
連線資料庫
- 使用idea連線本地資料庫
編寫實體類User
public class User {
private String userId;
private String passWord;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
UserDao層介面
public interface UserDao {
public boolean getUser(String userID,String userPassWord);
}
UserDaoImpl實現類
public class UserDaoImpl implements UserDao{
private String driver = "com.mysql.cj.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/student";
private String root = "root";
private String password = "123456";
@Override
public boolean getUser(String userID,String userPassWord) {
boolean flag = false;
Connection conn = null;
PreparedStatement pstm = null;
ResultSet rs = null;
String sql = "select * from tbl_user where userId = ? and passWord = ?";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,root,password);
pstm = conn.prepareStatement(sql);
pstm.setString(1,userID);
pstm.setString(2,userPassWord);
rs = pstm.executeQuery();
if(rs.next()){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
rs.close();
pstm.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return flag;
}
}
UserService層介面
public interface UserService {
public boolean Login(String userId,String userPassWord);
}
UserServiceImpl實現類
public class UserServiceImpl implements UserService{
@Override
public boolean Login(String userId, String userPassWord) {
boolean flag = false;
UserDao userDao = new UserDaoImpl();
flag = userDao.getUser(userId,userPassWord);
return flag;
}
}
編寫LoginServlet服務層
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
boolean flag = false;
String userId = req.getParameter("userName");
String userPassWord = req.getParameter("userPassWord");
UserService userService = new UserServiceImpl();
flag = userService.Login(userId,userPassWord);
if(flag){
User user = new User();
user.setUserId(userId);
user.setPassWord(userPassWord);
req.getSession().setAttribute("user",user);
resp.sendRedirect("jsp/success.jsp");
}else{
req.setAttribute("msg","使用者錯誤");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
配置web.xml檔案
- servlet3.0之後可以使用註解,不用配置這個檔案,但是是初學者,還是先學會配置web.xml檔案
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.hjk.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
編寫login.jsp 介面
- 簡單的寫了一下,一個表單的提交功能
<form action="login" method="post">
<table>
<tr><span style="color: aquamarine">${requestScope.msg}</span></tr>
<tr>
<td>使用者名稱:</td><td><input type="text" name="userName"/></td>
</tr>
<tr>
<td>密碼</td><td><input type="password" name="userPassWord"/></td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="submit"/>
<input type="reset" value="reset">
</td>
</tr>
</table>
</form>
- 寫一個登入成功介面sccess.jsp
-這個檔案在web問價夾下面,本來想寫一個攔截器,沒有登入不能直接訪問後面的介面,現在還沒有寫
<h1><span style="text-align: center"><span style="color: deeppink" >歡迎您,${sessionScope.user.userId}登入成功</span></span></h1>
- 如果登入失敗就返回登入介面
idea預設會先訪問index.jsp介面,這裡在web.xml配置一下,讓他直接訪問login.jsp
<welcome-file-list>
<welcome-file>/login.jsp</welcome-file>
</welcome-file-list>
已經可以登入了,但是還是存在中文亂碼,編寫一個過濾器CharacterEncoding,讓它處理中文亂碼
- 這個包必須匯入
import javax.servlet.*;
public class CharacterEncoding implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletRequest.setCharacterEncoding("utf-8");
//不執行filterChain就會一直卡在這裡,相當於一直攔截
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
- 為過濾檔案配置web.xml
<filter>
<filter-name>characterEncoding</filter-name>
<filter-class>com.hjk.filter.CharacterEncoding</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
結果展示
-
初始介面
-
登入失敗介面
-
登入成功;不加過濾器張山是不能登入成功的
-
admin
-
張三
檔案的整體結構
一些注意點
- 導包的時候一定要到對
- idea有可能在測試的時候沒有lib包這個時候需要自己新增lib問價夾,並且把相應的依賴都新增進去
- 伺服器報404 一般是路徑錯誤(比較好解決)
- 500 可能是一些程式碼錯誤,或者jar沒到入