Jax-rs (Java API for RESTful Web Services) Practice Tutorial IV--@Context inject httpservletrequest to keep the rest state! __java

Source: Internet
Author: User

Reprint please indicate the source http://blog.csdn.net/exsuns

Jax-rs provides an annotation injection method to obtain the client's information

When the Jax-rs service is released based on the servlet , you can also inject servletconfig, ServletContext, HttpServletRequest, in the servlet through @context, HttpServletResponse

Then rest can be sessionid to hold the user's state


How to use:

Build a Web project and join the Jax-rs (jsr311) jar Package


Create a new class

@Path ("UserContext") public class UserContext {@Context uriinfo uriinfo; @Context httpheaders httpheaders; @Context secur Itycontext SC; @Context Request req; @Context Response resp; @Context httpservletresponse response; @Context HttpServletRequest request; @GET public string Hi (@QueryParam ("name") string yourName) {if (yourname!=null) request.getsession (). setattribute (" Name ", YourName); String username = (string) request.getsession (). getattribute ("name"); if (username!=null) {System.out.println (Request.getsession (). GetId () + ":" + username);} else{System.out.println (Request.getsession (). GetId () + "no user"); } }



<!--web.xml add--> <servlet> <display-name>jax-rs REST servlet</display-name> < Servlet-name>jax-rs REST servlet</servlet-name> <servlet-class> Com.sun.jersey.spi.container.servlet.servletcontainer</servlet-class> <load-on-startup>1</ load-on-startup> </servlet> <servlet-mapping> <servlet-name>jax-rs REST servlet</ Servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping>



Deployment Department Run

Http://localhost:8080/rest/services/UserContext

Background will prompt:

A46756539d2e39cc2cffcb3fe1c99e70 No users



And then run

Http://localhost:8080/rest/services/UserContext?name=hello

Background will appear

A46756539d2e39cc2cffcb3fe1c99e70:hello

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.