Servlet development technology


foreword

提示:这里可以添加本文要记录的大概内容:

Download Tomcat and JavaWeb tools before writing javaweb projects

The figure below shows the code prompt of a JavaWeb tool, you can check if your own
insert image description here


Create a Servlet project

提示:以下是本篇文章正文内容,下面案例可供参考

Generate a JavaWeb project for the first time: Create a dynamic web project Generate
insert image description here
a JavaWeb project later:
insert image description here
Step 1: Inherit HttpServlet
Step 2: Add @WebServlet annotation, configure address
Step 3: Rewrite doXXX methods (7 types in total), process requests and respond

Code specific operation:

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;
//第二步:增加@WebServlet注解,配置地址
@WebServlet("/hello")   
					 //第一步:继承HttpServlet
public class HelloServlet extends HttpServlet{
    
    
//第三步:重写doXXX方法,处理请求并响应
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    

		
	}
}

process the request and respond

process request

		//处理请求
		//1.获取请求中的数据
		//调用HttpServletRequest中的方法getParameter("数据名")
		String name = req.getParameter("name");
		//2.具体处理
		System.out.println("前端发送的数据是"+name);

The following are the three corresponding types

text/plain, plain text

//生成纯文本格式的响应
//1.调用HttpServletResponse中的setContentType方法设置内容类型
resp.setContentType("text/plain;charset=utf-8");
//2.调用HttpServletResponse中的getWriter方法输出响应内容
PrintWriter writer = resp.getWriter();
writer.print("Hello, world!");
writer.flush();

The above code sets the content type of the response to text/plain, and then outputs a string "Hello, world!". Note that to call the method after outputting the content flush(), the content is flushed into the output stream.

Output effect:
insert image description here

text/html, html code

//生成 HTML 代码格式的响应
//1.调用HttpServletResponse中的setContentType方法设置内容类型
resp.setContentType("text/html;charset=utf-8");
//2.调用HttpServletResponse中的getWriter方法输出响应内容
PrintWriter writer = resp.getWriter();
writer.print("<html><head><title>Hello, world!</title></head><body><h1>Hello, world!</h1></body></html>");
writer.flush();

Output effect:
insert image description here

application/json, JSON format string

Student class:

public class Student {
    
    
	private String name;
	private String sex;
	public Student() {
    
    
		super();
		// TODO 自动生成的构造函数存根
	}
	public Student(String name, String sex) {
    
    
		super();
		this.name = name;
		this.sex = sex;
	}
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	public String getSex() {
    
    
		return sex;
	}
	public void setSex(String sex) {
    
    
		this.sex = sex;
	}
	
}

servlet class:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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.google.gson.Gson;
import po.Student;
@WebServlet("/hello")   
public class HelloServlet extends HttpServlet{
    
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		
		//处理请求
		//1.获取请求中的数据
		//调用HttpServletRequest中的方法getParameter("数据名")
		String name = req.getParameter("name");
		//2.具体处理
		System.out.println("前端发送的数据是"+name);
		
		//生成响应
		//1.调用HttpServletResponse中的setContentType 设置内容类型
		resp.setContentType("application/json;charset=utf-8");
		//2.调用HttpServletResponse中的getWriter 输出流
		PrintWriter writer = resp.getWriter();
		Student s1 = new Student("张三","男");
		Student s2 = new Student("李四","女");
		ArrayList<Student> list = new ArrayList<>();
		list.add(s1);
		list.add(s2);
		Gson gson = new Gson();
		
		writer.print( gson.toJson(list));
	}
}

Output effect:
insert image description here

Servlet life cycle

  1. Loading phase: calling the constructor
  2. Initialization phase: calling the init method
    When the web container that supports Servlet operation receives a request from the client, it will first determine whether the Servlet object requested by the user exists; if it does not exist, it needs to load the Servlet class, create a Servlet object, and then call the Servlet method to initialize init().
  3. Service phase: call the service method to process the request sent back. The container creates and objects
    for this client request , and creates a thread, calls the method of the Servlet object , and then indirectly calls the method or method according to the client's request method . After the service() method finishes running, a response is generated, and the container sends the response back to the client.ServletRequestServletResponseservice( )service()doGet()doPost()
  4. Destruction phase: calling the destroy method to destroy When the web application is uninstalled or the server is shut down, the container will destroy the and objects and corresponding threads
    created for this client request . At this time, the method will be called to release the resource.ServletRequestServletResponsedestroy()

It should be noted that loading the Servlet class, creating a Servlet object, calling the initialization method init () and destroying the method destroy () are only once in the entire life cycle of the 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;
@WebServlet(urlPatterns = "/life",loadOnStartup = 5)
public class LifeCycleServlet extends HttpServlet{
    
    

	public LifeCycleServlet() {
    
    
		System.out.println("构造方法调用了");
	}
	@Override
	public void init() throws ServletException {
    
    
		// TODO init自动生成的
		System.out.println("init方法调用了");
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		System.out.println("service方法调用了");
	}
	@Override
	public void destroy() {
    
    
		// TODO 自动生成的方法存根
		System.out.println("destroy方法调用了");
	}
}

Console output after running the project:
insert image description here
the fourth stage: the destruction stage, call the destroy method to destroy

In Servers, right-click Tomcat to stop
insert image description here
and return to the console:
insert image description here

The methods that are called throughout the life cycle of the Servlet

Servlet will have some methods that are automatically called by the server throughout the life cycle, and the main methods are:
init( )method: used for initialization
Destro( )method: used for releasing resources
service( )method: service class method, which processes user requests and responds to users. Almost all processing functions are completed here. service( )method usually invokes the doGet( ) or doPost( ) method.
doGet( )The method can respond to the request of the get method, and the doPost( ) method can respond to the request of the post method.

It is generally not recommended to directly rewrite the service( ) method, but should rewrite the doGet( ) or doPost( ) method. Usually, the post method is often used for form submission, and the get method is used for hyperlinks.

Servlet operating principle

insert image description here

CORS cross domain settings

CORS is a mechanism that allows web applications to request resources from different domain names or ports, lifting the restrictions of the same-origin policy. It is realized by adding custom request headers and response headers. In the access policy provided by the web server, requests from different domains are allowed or denied to access resources. CORS facilitates the development of web applications and makes cross-origin requests more convenient.

First make a Servlet in JavaWeb to realize a simple user login function.
When logging in, you need to pass in the username and password. When the username is admin and the password is 111, the login is successful and the return result is "success"; otherwise, the return result is "failure".
At the same time, a request header that allows cross-domain asynchronous requests is added to the response. Finally, the result is written back to the response through PrintWriter for use by the front-end page.

Backend code:

// 前后端分离项目
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")
public class LoginServlet extends HttpServlet{
    
    
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		String name = req.getParameter("name");
		String pwd = req.getParameter("pwd");
		
		String result = null;
		// ==判断的是内容
		if (name.equals("user") && pwd.equals("123456")) {
    
    
			result = "成功";
		} else {
    
    
			result = "失败";
		}  
		
		//允许跨域 异步请求                                                        * 代表所有
		resp.setHeader("Access-Control-Allow-Origin", "*");
		//我的响应类型  纯文本
		resp.setContentType("text/plain;charset=utf8");
		//得到字符输出流
		PrintWriter writer = resp.getWriter();
		//将变量result的值输出到控制台或文件中
		writer.print(result);
	}
}

Start Tomcat and add the value of the name and password with a question mark after the original link:?name=user&pwd=123456

insert image description here

Next write the front-end code:

Add it when selecting a function Router, because there is a jump.
insert image description here
Install the axios framework after the project is successful: npm i axios
insert image description here
open the index.js file in the router folder after entering the project. In
insert image description here
addition, delete all subcomponents except the root component
. Delete Home, About and all styles in the root component, leaving only one routing exit

Display after deletion:
insert image description here
Then create two new subviews LoginView and IndexView

Add an h1 tag to the home page view, just indicate what the view is for

    <h1>欢迎访问首页视图</h1>

Also add an h1 tag in the login view, just need to indicate what this view is for

    <h1>登录视图</h1>

Configure routing after the view is written: index.js

  1. import view
import LoginView from '@/views/LoginView'
  1. Configure the routing of the view, three configuration items
  {
    
    
    path: '/',
    name: 'login',
    component: LoginView
  },
  {
    
    
    path: '/index',
    name: 'index',
    component: () => import('@/views/IndexView')
  }
]

Go back to terminal and start:

insert image description here
Next, add some content to the login view (two input boxes, a button, and an error message)

<template>
  <div>
    <h1>登录视图</h1>
    名: <input type="text" v-model="name"><br>
    密: <input type="text" v-model="pwd">
    <p v-show="isError">用户名或密码输入错误</p><br>
    <button @click="login">登录</button>
  </div>
</template>

Next, configure the data of name, pwd, and isError in data

  data () {
    
    
    return {
    
    
        name: '',
        pwd: '',
        isError: false
    }
  },

Then add a login definition in methods

  methods: {
    
    
    login(){
    
    

    }
  },

Complete the request sending here axios, and process the corresponding data back

First import:

import axios from 'axios'

Next write the request:

  methods: {
    
    
    login(){
    
    
                                                        // 模板字符串拼接动态数据
        axios.get(`http://localhost:8888/CORS/login?name=${
      
      this.name}&pwd=${
      
      this.pwd}`)
        .then((resp) =>{
    
    
          // 处理服务器后端发回的响应,使用箭头函数
          // 判断相应的数据成功还是失败
          if ( resp.data =='成功' ) {
    
    
            this.$router.push('/index')
          } else {
    
    
            // 失败显示错误提示
            this.isError = true
          }
        })
    }
  },

Finally, the complete code of the login view: (add style code to make it rich in content)

<template>
  <div class="login-container">
    <h1>用户登录</h1>
    <form>
      <div class="form-field">
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username" v-model="name">
      </div>
      <div class="form-field">
        <label for="password">&nbsp;&nbsp;&nbsp;:</label>
        <input type="password" id="password" name="password" v-model="pwd">
      </div>
      <p v-show="isError" class="error-text">用户名或密码输入错误,请重新输入</p>
      <button @click="login" class="login-btn">登录</button>
    </form>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    
    
  data () {
    
    
    return {
    
    
        name: '',
        pwd: '',
        isError: false
    }
  },
  methods: {
    
    
    login(){
    
    
                                                // 使用模板字符串拼接动态数据
      axios.get(`http://localhost:8888/CORS/login?name=${
      
      this.name}&pwd=${
      
      this.pwd}`)
        .then((resp) =>{
    
    
          // 处理服务器后端发回的响应,使用箭头函数
          // 判断相应的数据成功还是失败
          if (resp.data == '成功') {
    
    
            this.$router.push('/index')
          } else {
    
    
            // 失败显示错误提示
            this.isError = true
          }
        })
    }
  },
  components: {
    
    },
  computed: {
    
    },
  watch: {
    
    },
  mounted () {
    
    }
}
</script>

<style scoped>
.login-container {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 50px;
}

form {
    
    
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f6f6f6;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0px 1px 5px #ccc;
}

.form-field {
    
    
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 20px;
}

.form-field label {
    
    
  font-size: 18px;
  margin-right: 10px;
}

.form-field input {
    
    
  font-size: 18px;
  padding: 5px;
  border-radius: 3px;
  border: 1px solid #ccc;
  flex: 1;
}

.error-text {
    
    
  color: red;
  font-size: 18px;
  margin-top: 10px;
}

.login-btn {
    
    
  font-size: 18px;
  font-weight: bold;
  color: white;
  background-color: #4CAF50;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  margin-top: 20px;
  cursor: pointer;
}

.login-btn:hover {
    
    
  background-color: #3E8E41;
}
</style>

Output effect:
insert image description here


Guess you like

Origin blog.csdn.net/rej177/article/details/131711654