jsp+servlet 練習

番薯Smile發表於2017-05-11
Login.jsp
<body>
    <form action="ServletTest" method="post">
    <table align="center">
    <tr><td>name:<td><td><input type="text" name="name"><td><tr>
    <tr><td>psw:<td><td><input type="text" name="psw"><td><tr>
    <tr><td><td><td><input type="submit" value="提交"><td><tr>
    </table>
    
    </form>
  </body>

通過index.jsp 用forward專向Login.jsp。

<jsp:forward page="/WEB-INF/Login.jsp"></jsp:forward>

在專案中建立一個servlet 類,繼承HttpServlet,重寫doGet(),doPost()

ServletTest.java
package com.scx.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletTest extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//req.setCharacterEncoding("utf-8"); 這種轉換會亂碼
		resp.setContentType("text/html;charset=UTF-8");
		String name = req.getParameter("name");
		String psw = req.getParameter("psw");
		PrintWriter out = resp.getWriter();
		if(name=="123"||name.equals("123")){
			if(psw=="123"||psw.equals("123")){
				out.println("登入成功,"+"歡迎"+name+"進入我的空間!");
			}
		}
		else{
			out.println("使用者名稱或密碼錯誤!");
		}
	}
	
}

過程中出現了   HTTP method GET is not supported by this URL 這種錯誤,網上搜了好久,原來是我是用的POST傳值,結果在ServletTest中,寫到了doGet()方法體內,真是太暈了,就先到這吧,晚安,地球。