Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

An example Analysis of Mini Service Program Servlet in Java

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "Servlet instance Analysis of Mini Service Program in Java". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn the "Servlet instance Analysis of the Mini Service Program in Java".

Servlet

1 introduction to Servlet

Servlet is a technology used by Sun to develop dynamic web.

Sun provides an interface in these API called Servlet. If you develop a Servlet program, you only need to complete two small steps.

Write a class that implements the Servlet interface

Deploy the developed Java class to the web server

The Java program that implements the Servlet interface is called Servlet

2 HelloServlet

Build a normal Maven project and delete the src directory in it. This empty project is the Maven main project.

Understanding of the Maven father-son project:

In the parent project

Servlet-02

There will be in the subproject

Javaweb-02-servlet com.srx 1.0-SNAPSHOT

Java child projects in the parent project can be used directly

Son extends father

Maven environment optimization

Modify web.xmd to the latest

Complete the structure of maven

Write a Servlet program

Write the mapping of Servlet

Why do we need mapping? we are a java program, but to access it through a browser, and the browser needs to connect to the web server, so we need to register the Servlet we wrote in the web service and give it a path that the browser can access.

Hello com.srx.HellowServlet hello hello

Configure Tomcat

Note: configure the path of the project release

Start the test Oke.

3 Servlet principle

Servlet is called by the web server, and the wev server after receiving the browser request

4 Mapping problem

A Servlet can specify a mapping path

A Servlet can specify multiple mapping paths

Hello / hello hello / hello1 hello / hello2 hello / hello3

A Servlet can specify a common mapping path

Hello/ hello/*

Default request path

Hello / *

Specify some suffixes or prefixes and so on.

Hello * .abc

Priority problem

The inherent mapping path is specified with the highest priority. If it cannot be found, the request will be processed by default.

Error com.srx.Error error / * 5 servletContext

When the web container starts, it creates a corresponding ServletContext object for each web program, which represents the current web application.

1. Share data

The data I saved in this Servlet can be obtained in another servlet.

The class that holds the data

Public class test extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ / this.getInitParameter (); / / initialization parameter / / this.getServletContext (); / / servlet context / / this.getServletConfig (); servlet configuration ServletContext servletContext = this.getServletContext (); String username= "I love learning" / / Save a data in ServletContext named uesrname value username servletContext.setAttribute ("username", username); System.out.println ("hello");}}

Exported class

Public class show extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext servletContext = this.getServletContext (); resp.setContentType ("text/html"); resp.setCharacterEncoding ("utf-8"); String username = (String) servletContext.getAttribute ("username"); resp.getWriter (). Print ("name:" + username);}}

Configured file

Test com.srx.test test / test getc com.srx.show getc / getc

Test access results

two。 Get initialization parameters

Url JDBC:mysql//localhost:3306/mybatis

Test class

Public class context extends HttpServlet {protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {ServletContext Context = this.getServletContext (); String url = Context.getInitParameter ("url"); resp.getWriter () .print (url);}}

Path

Url com.srx.context url / url

3. Request forwarding

Public class ServletDemo extends HttpServlet {protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println ("entering this method"); ServletContext context = this.getServletContext (); / / RequestDispatcher zf = context.getRequestDispatcher ("zf"); / / forwarding path / / zf.forward (req,resp) / / call the forward method to forward / / abbreviate context.getRequestDispatcher ("/ getc") .forward (req,resp);} zzz com.srx.ServletDemo zzz / zzz

4. Read resource files

Properties

Create a new properties in the java directory

Create a new properties under the zairesource directory

Found that: all are packaged under the same path; classes we commonly call this path classpath

Idea: need a file stream

Public class ServletDemo1 extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {InputStream is = this.getServletContext () .getResourceAsStream ("/ WEB-INF/classes/db.properties"); Properties prop = new Properties (); prop.load (is); String user = prop.getProperty ("username"); String pwd = prop.getProperty ("password"); resp.getWriter () .print (user+ ":" + pwd)) @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet (req,resp);}}

Mapping

Bbb com.srx.ServletDemo1 bbb / bbb 6 、 HttpServletResponse

The web server receives a http request from the client. For this request, create a HttpServletRequest object that represents the request and a HttpServletResponse that represents the response.

If you get the parameters requested by the client, find httpServletRequest.

If you want to respond to some information for the client: find HttpServletResponse

1 download the file

Output information to the browser

2 download the file

To get the path to the downloaded file

What is the name of the downloaded file?

Set up ways to get browsers to support downloading what we need

Get the input stream of the downloaded file

Create buffer

Get the OutputStream object

Write the FileOutputStream stream to the Buffer buffer

Use OutputStream to output the data in the buffer to the client.

Case

Public class FileServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ /-the path to get the download file String realPath = "D:\ software installation path\ javaweb-02-servlet\ response\ target\ classes\ 111.png"; System.out.println ("download path to the file" + realPath) / /-what is the name of the downloaded file String substring = realPath.substring (realPath.lastIndexOf ("\") + 1); / /-set ways to make browsers support downloading what we need resp.setHeader ("Content-Disposition", "attachment;filename=" + URLEncoder.encode (substring, "utf-8")); / /-get the input stream of the downloaded file FileInputStream in = new FileInputStream (realPath) / /-create buffer int len= 0; byte [] buffer=new byte [1024]; / /-get OutputStream object ServletOutputStream outputStream = resp.getOutputStream (); / /-write FileOutputStream stream to Buffer buffer using OutputStream to output data in the buffer to client while ((len=in.read (buffer)) > 0) {outputStream.write (buffer,0,len) } in.close (); out.close ();} @ Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet (req, resp);}}

3 randomly refreshed CAPTCHA pictures

Public class ImgServlet extends HttpServlet {@ Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {/ / refresh the browser every 2 seconds Resp.setHeader ("refresh", "0.5"); / / create a picture BufferedImage image = new BufferedImage in memory; / / get the picture Graphics2D g = (Graphics2D) image.getGraphics (); / / Pen / / set the background color of the picture g.setColor (Color.white); g.fillRect (0mine0jin80) / / write data to the picture g.setColor (Color.BLUE); g.setFont (new Font (null,Font.BOLD,20)); g.drawString (makeNum (), 0Power20); / / tell the browser how to request the image to open resp.setContentType ("image/jpeg") / / there is a cache on the website that does not allow browsers to cache resp.setDateHeader ("expires",-1); resp.setHeader ("Cache-Control", "no-cache"); resp.setHeader ("Pragma", "no-cache"); / / write the image to the browser ImageIO.write (image, "jpg", resp.getOutputStream ()) } private String makeNum () {Random random = new Random (); String num=random.nextInt (9999999) + "; StringBuffer sb = new StringBuffer (); for (int I = 0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report