0

I have been practicing java Servlets. Can I set urlPattern from database?

@WebServlet(name = "PatternServlet", urlPatterns = "/pattern")

The following servlet creates html pages getting information from postgres, so content is dynamic. However url address is remaining same each time.

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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "PatternServlet", urlPatterns = "/pattern")
public class PatternServlet extends HttpServlet {
    String title;
    String content;
    List<String> headerItems;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        initializeFields();
        //Dynamically creates pages with a given information
        PageMaker pageMaker = new PageMaker(title, headerItems, out);
        pageMaker.setContent(content);
        pageMaker.makePage();
    }

    public void initializeFields(){
        //initializes field from database
    }
}

Can I do something to solve this issue? Thank you!

valijon
  • 1,304
  • 2
  • 20
  • 35

1 Answers1

0

I hope I understand your question correctly. First the urlPatterns are static once the servlet is created. You can use some fancy stuff to give it a name when it starts, but this cannot be changed once set.

But you can use wildcards

@WebServlet(urlPatterns = "/dbcontent/*")

call your servlet with

http://yourserver/dbcontent/dbRef

and then

@Post
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String pathInfo = request.getPathInfo();
  String[] pathElements = pathInfo.split("/"); 
  // get last item (or whatever one you need)
  String dbRef = pathInfo[pathInfo.lenth -1];
  // check input. User could have tampered url

  // do your stuff with dbRef
}

I did not test the code and there are better ways to fetch the dbRef you need, but I hope this illustrates how you can use a servlet to fetch stuff from a database.

ipper
  • 624
  • 4
  • 13