I am creating a web servlet , which is presently accessed by php , using :
$payload = file_get_contents('http://localhost:8080/HelloWorldServlet/index?name=Joe&age=24');
This calls a HelloWorldServlet web application running on my tomcat server
with a url pattern for /index.
The doGet() is invoked for the servlet. The doGet() method writes the data in json, as response..
My question is how do I send back the json to php , just to display it?
Also, the php application is running on port 8888.
Here is the code for doGet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//GsonBuilder builder = new ();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
response.setContentType("application/json; charset=UTF-8");
String key = request.getParameter("name");
String value = request.getParameter("age");
String jsonString = gson.toJson(new Tuple(key, value)).toString();
request.setAttribute("data", jsonString);
//response.sendRedirect("localhost:8888/MYPHPAPPLICATION/testcall.php");
try {
getServletConfig().getServletContext().getRequestDispatcher(
"/display.jsp").forward(request,response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Also, I created a filter for changing the request when it tried to forward to a php page.
But it didn't work as expected.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
String requestURI = request.getRequestURI();
if (requestURI.contains("display.jsp"))
{
String toReplace = "localhost:8888/MYPHPAPPLICATION/testcall.php";
req.getRequestDispatcher(toReplace).forward(req, res);
} else
chain.doFilter(req, res);
}
This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>HelloWorldServlet</display-name>
<servlet>
<description></description>
<servlet-name>HelloWorldServlet2</servlet-name>
<servlet-class>com.srccodes.example.HelloWorld</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet2</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
<filter>
<filter-name>urlRewriteFilter</filter-name>
<filter-class>com.srccodes.example.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>urlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Just write it to the response body and return immediately.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
String jsonString = gson.toJson(new Tuple(key, value)).toString();
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonString);
}
You don't need JSP for this. It's primarily designed to act as a template for HTML output.
Related
I tried to change the ServletResponse Content-Type using ServletFilter. But, the servelet (in my content, AxisServlet) updates that Content-Type when chain.doFilter() calls. But other Response Headers are correctly updated.
I tried setting response headers after doFilter is called. At that time no response header was updated.
Does anyone know a way to update the Content-Type of the ServletResponse after Servelt is completed?
Code :
public class HeaderFilter implements Filter {
private HashMap<String,String> rsCustomHeaders = new HashMap<String,String>();
public void init(FilterConfig config) throws ServletException {
Enumeration<String> initParameterNames = config.getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String initParameterName = initParameterNames.nextElement();
rsCustomHeaders.put(initParameterName, config.getInitParameter(initParameterName));
}
System.out.println("init().rsCustomHeaders : " + rsCustomHeaders);
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
for (Map.Entry<String, String> rsCustomHeaderEntry : rsCustomHeaders.entrySet()) {
httpServletResponse.addHeader(rsCustomHeaderEntry.getKey(), rsCustomHeaderEntry.getValue());
}
System.out.println("doFilter().encoding :Set Response Headers Done");
chain.doFilter(httpServletRequest, httpServletResponse);
System.out.println("doFilter().HeaderFilter is Done!!!");
}
public void destroy() {
System.out.println("destroy(). : Destroy is called!");
}
}
web.xml
<filter>
<filter-name>HeaderFilter</filter-name>
<filter-class>filters.HeaderFilter</filter-class>
<init-param>
<param-name>content-type</param-name>
<param-value>application/xml; charset=utf-8</param-value>
</init-param>
<init-param>
<param-name>Content_type</param-name>
<param-value>text/xml; charset=utf-8</param-value>
</init-param>
<init-param>
<param-name>rq_content-type</param-name>
<param-value>text/xml; charset=utf-8</param-value>
</init-param>
<init-param>
<param-name>Header-X</param-name>
<param-value>Value-X</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>HeaderFilter</filter-name>
<url-pattern>/services/GradeThreeMath</url-pattern>
</filter-mapping>
Set content type on the original response.
Use HttpServletResponseWrapper with overridden setContentType to wrap response that is passed to child.doFilter. Overridden setContentType should just ignore any attempts to change content type.
The code snippet:
// Setting content type
httpServletResponse.setContentType("you-content-type");
chain.doFilter(httpServletRequest, new HttpServletResponseWrapper(httpServletResponse) {
#Override
public void setContentType(final String type) {
// Ignore any further attempts to change content type
}
});
I have created a filter in my application to take care of login/logout scenario. The filter mapping is not working. In my web.xml, if I put<url-pattern>/LoginServlet/*</url-pattern>, filter mapping works, but if I put a name of the jsp, then it doesn't work <url-pattern>/LoginServlet/list.jsp</url-pattern>. I don't want to call the filter for all jsps.
This is my filter.
public class LoginFilter implements Filter{
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("LoginFilter : doFilter : Start");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
System.out.println("LoginFilter : doFilter : 111111");
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("user") == null) {
System.out.println("LoginFilter : doFilter : 222222");
response.sendRedirect("login.jsp");
//response.sendRedirect(request.getContextPath() + "/login.jsp");
//response.sendRedirect("login.jsp");
//response.sendRedirect("http://localhost:8080/PROJECT_ELMS/login.jsp");
}else {
System.out.println("LoginFilter : doFilter : 33333333");
chain.doFilter(request, response);
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
This is my web.xml.
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>edu.umd.enpm613.helper.StartupListner</listener-class>
</listener>
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>edu.umd.enpm613.servlet.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>edu.umd.enpm613.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet/*</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>StudentServlet</display-name>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>edu.umd.enpm613.servlet.StudentServlet</servlet-class>
</servlet>
LoginServlet is:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public LoginServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings("null")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("LoginServlet : doPost : Start");
LoginDTO returnedDTO = null;
String userEmailId = request.getParameter("userid");
try {
request.getSession(true).setAttribute("user", userEmailId);
String userPassword = request.getParameter("password");
LoginDTO loginDto = new LoginDTO();
loginDto.setUserEmailId(userEmailId);
loginDto.setUserPassword(userPassword);
returnedDTO = LoginImpl.getUserCategory(loginDto);
String category = returnedDTO.getUserCategory();
if (category.equals(ELMSConstants.CATEGORY_STUDENT)) {
//request.getRequestDispatcher("student_home.jsp").forward(request,response);
System.out.println("LoginServlet : doPost : Start" +request.getContextPath());
System.out.println("LoginServlet : doPost : Start" +request.getRequestURI());
System.out.println("LoginServlet : doPost : Start" + request.getRequestURL());
request.getRequestDispatcher("list.jsp").forward(request,response);
}
if (category.equals(ELMSConstants.CATEGORY_TEACHER)) {
System.out.println("LoginServlet : doPost : 22222222222");
request.getRequestDispatcher("professor_home.jsp").forward(request,response);
}
}catch (ELMSException exp){
exp.printStackTrace();
System.out.println("LoginServlet : doPost : error message is" + exp.getMessage());
if (exp.getMessage().equals(ELMSException.USER_NEED_TO_CHANGE_PASSWORD)) {
System.out.println("LoginServlet : doPost : 1111111111");
request.setAttribute("errorMessage", exp.getMessage());
request.setAttribute("userName", userEmailId);
request.getRequestDispatcher("changePassword.jsp").forward(request,response);
}
if (!exp.getMessage().equals(ELMSException.USER_NEED_TO_CHANGE_PASSWORD)) {
request.setAttribute("errorMessage", exp.getMessage());
request.getRequestDispatcher("login.jsp").forward(request,response);
}
}
}
}
The filter should bypass the login page because it has not a security restriction, also it would allow you to map all URLs without infinite loop.
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("LoginFilter : doFilter : Start");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
System.out.println("LoginFilter : doFilter : 111111");
HttpSession session = request.getSession(false);
//bypass the login page and login servlet
if (request.getRequestURI().indexof("login.jsp") >= 0 ||
request.getRequestURI().indexof("/LoginServlet") >= 0){
System.out.println("LoginFilter : bypass the login");
chain.doFilter(request, response);
} else {
if (session == null || session.getAttribute("user") == null) {
System.out.println("LoginFilter : doFilter : 222222");
response.sendRedirect("login.jsp");
//response.sendRedirect(request.getContextPath() + "/login.jsp");
//response.sendRedirect("login.jsp");
//response.sendRedirect("http://localhost:8080/PROJECT_ELMS/login.jsp");
} else {
System.out.println("LoginFilter : doFilter : 33333333");
chain.doFilter(request, response);
}
}
}
According to Java Servlet Specification
In the web application deployment descriptor, the following syntax is
used to define mappings:
• A string beginning with a ‘/’ character and ending with a ‘/*’
postfix is used for path mapping.
• A string beginning with a ‘*.’ prefix is used as an extension
mapping.
• A string containing only the ’/’ character indicates the "default"
servlet of the application. In this case the servlet path is the
request URI minus the context path and the path info is null.
• All other strings are used for exact matches only.
So you cannot directly map servlet or filter with file like: /LoginServlet/list.jsp . Possible solution is to put your list.jsp file to individual folder like /LoginServlet/Security/list.jsp
And map it:
<url-pattern>/LoginServlet/Security/*</url-pattern>
When i create a servlet filter in Spring MVC, I am getting the following exception.
[javax.servlet.ServletException: java.lang.IllegalStateException: Cannot create a session after the response has been committed] with root cause
when i put the sysout i could understand that the exception occurs at the redirect line, but didn't understand why
can anyone please tell me some solution for this
SessionFilter.java
public class SessionFilter implements Filter {
private ArrayList<String> urlList;
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
if(urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("preparing for redirect");
response.sendRedirect("index.jsp");
}
}
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig config) throws ServletException {
System.out.println("entered init");
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringMVCHibernate</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<filter>
<filter-name>SessionFilter</filter-name>
<filter-class>com.common.dao.SessionFilter</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>index.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
:
:
:
To simple and short Answer for your Question:
To avoid this , you should have a return statement , or avoid redirecting or forwarding request , or these kind of things should be done by the last filter in the filter chain.
For More Details Explanation you can read below :
This Exception occurs when you try to send response again when the response is already committed and flushed to user.
For Example :
Here in below example code ,first the request will be forwarded to index_test.jsp and response will be flushed to user , then the control will again come back to filter and try to send another response (redirect)to user , and it will fail.
Usually we check multiple conditions in filter and accordingly forward and redirect , if two conditions are met , then it will create a problem .
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.getRequestDispatcher("index_test.jsp").forward(request, response);
((HttpServletResponse)response).sendRedirect("new.jsp");
chain.doFilter(request, response);
}
Solution for your case :
To avoid this , you should have a return statement , or avoid redirecting or forwarding request , or these kind of things should be done by the last filter in the filter chain.
So you could change your code as :
public class SessionFilter implements Filter {
private ArrayList<String> urlList;
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
boolean allowedRequest = false;
if(urlList.contains(url)) {
allowedRequest = true;
}
if (!allowedRequest) {
HttpSession session = request.getSession(false);
if (null == session) {
System.out.println("preparing for redirect");
response.sendRedirect("index.jsp");
return;
}
}
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig config) throws ServletException {
System.out.println("entered init");
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
Its Obvious right :
System.out.println("preparing for redirect");
response.sendRedirect("index.jsp");
return;
We are have return after that statement.
So further execution wont happen so u are not getting exception.
See we cant involve both filtering and Redirect or Forward in same block it will give IllegalStateException because :
This Exception occurs when you try to send response again when the response is already committed and flushed to user
I am trying to add a Header to a PDF file just before displaying to the client. I have a filter servlet which will be intercepting the request/response before the app asks for Save. I have tested my PDFBox class on a standalone PDF and that works. I am having a difficulty with the Filter Servlet. I have tried the HttpServletRequestWrapper but not able to get eh inputstream. It seems to be empty. Here is my filter code:
public class AddFOUOFilterServlet implements Filter {
/** The log. */
private static Log log = LogFactory.getLog(AddFOUOFilterServlet.class);
private String loginUrl = null;
/**
* #desc - This function initializes the global variables.
* #param filterConfig - FilterConfig settings that come from the web.xml
*/
public void init(FilterConfig filterConfig) throws ServletException {
log.debug("Inside AddFOUOFilterServlet init ");
ServletContext context = filterConfig.getServletContext();
}
/**
* #desc - the method called by the server before each server request
* #param req - the servlet request
* #param res - the servlet response
* #param chain - a FilterChain object that lists all filters to be called by the server
* #throws IOException, ServletException
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//log.debug("Inside doFilter");
// cast the HTTP request and response objects and get the url path info
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)res;
HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request);
InputStream is = request.getInputStream();
log.debug("is.available() "+is.available());
byte[] buf = new byte[1024];
while((is.read(buf))>0) {
log.debug("Reading the InputStream from the wrapper ");
}
if (request.getParameter("DocumentName") != null && request.getParameter("BlobID") != null)
{
log.debug("Processing the PDF URIs... ");
try
{
AddFOUOToReport addfouo = new AddFOUOToReport();
OutputStream os = null;
os = addfouo.doIt(is, "For Official Use Only");
chain.doFilter(requestWrapper, res);
}
catch (IOException ex)
{
log.error("AddFOUOToReport Filter error: " + ex.getMessage());
response.sendRedirect(loginUrl);
} catch (COSVisitorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
chain.doFilter(req, res);
}
}
public void destroy() {log.info("Inside destroy"); }
}
Web.xml entry:
<!-- BEGIN AddFOUOFilter Changes -->
<filter>
<filter-name>AddFOUO Filter</filter-name>
<filter-class>com.jmar.bo.controller.AddFOUOFilterServlet</filter-class>
</filter>
<filter-mapping>
<filter-name>AddFOUO Filter</filter-name>
<url-pattern>/cdz/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AddFOUO Filter</filter-name>
<url-pattern>/cdzServlet?getBlob*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>AddFOUO Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- END AddFOUOFilter Changes -->
There is no unique pattern to catch this event that is the reason I have as /* as pattern.
If the InputStream is empty that simply means the browser is not sending the PDF.
I'm guessing the PDF does not come from the browser, but from the server...
I have already visited Java FilterImplementation for session checking link, which says about Spring security. I did not get the help i need.
After applying filter login.jsp is unable to load CSS and images.
I am trying simple example providing filter in web.xml and applying the filter on pages other than login.jsp.
Web.xml file is :
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>AuthenticationFilter2</filter-name>
<filter-class>filter.AuthorizationFilter2</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>login.jsp</param-value>
</init-param>`
<filter>
And the filter class is :
private ArrayList<String> urlList;
public void destroy() {
// TODO Auto-generated method stub
System.out.println("authorization filter2 destroy method....");
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
System.out.println("authorization filter2 doFilter method....");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
System.out.println("ppp:"+request.getRequestURL());
System.out.println("url is :"+url);
boolean allowedRequest = false;
System.out.println("url list is :"+urlList);
if(urlList.contains(url.substring(1))) {
allowedRequest = true;
}
System.out.println("request allowed....."+allowedRequest);
if (!allowedRequest) {
Map session = ActionContext.getContext().getSession();
/*HttpSession session = request.getSession(false);*/
/* if (null == session) {
response.sendRedirect("login.jsp");
}*/
System.out.println("session contains login :"+session.containsKey("login"));
if(!session.containsKey("login")){
response.sendRedirect("login.jsp");
}
}
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {
System.out.println("authorization filter2 init method....");
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<String>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
Login page contains css and images as per the requirement.
Please help me out. Thank you.
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
String uri = ((HttpServletRequest)request).getRequestURI();
#SuppressWarnings("rawtypes")
Map session = ActionContext.getContext().getSession();
if ( uri.indexOf("/css") > 0){
chain.doFilter(request, response);
}
else if( uri.indexOf("/images") > 0){
chain.doFilter(request, response);
}
else if( uri.indexOf("/js") > 0){
chain.doFilter(request, response);
}
else if (session.containsKey("login")) {
chain.doFilter(request, response);
}
else {
((HttpServletResponse)response).sendRedirect(((HttpServletRequest)request).getContextPath() + "/login?authentication=failed");
}
}
put this block of code in your action class , it works.
Thank you all.
Your CSS files and images used on logjn.jsp page have to be excluded from your filter