Servlet and XQuery - servlets

I wrote a java class to run a simple XQuery on a XML database (Using Saxon xqj). The query works well in this class. But I want to access this class from a servlet. The problem is that the servlet doesn't find the java class, It gets java.lang.ClassNotFoundException: javax.xml.xquery.XQException when I run the servlet. Any Ideas please?
The Java class is as simple as This:
import java.util.Properties;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import javax.xml.xquery.XQSequence;
import javax.xml.namespace.QName;
import net.sf.saxon.xqj.SaxonXQDataSource;
import org.xml.sax.SAXException;
public class XMLClass {
public static String xmldata() throws XQException{
XQConnection con;
String output = null;
final String sep = System.getProperty("line.separator");
String fileName= "cd_book.xml";
con = new SaxonXQDataSource().getConnection();
System.out.println("Connected");
String queryString = "declare variable $docName as xs:string external;"+sep +
"for $x in doc($docName)/*" +
" return $x";
XQPreparedExpression expr = con.prepareExpression(queryString);
expr.bindObject(new QName("docName"), fileName, null);
XQResultSequence rs = expr.executeQuery();
String result =rs.getSequenceAsString(new Properties());
return result;
}
}
And the Servlet is:
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;
import javax.xml.xquery.XQException;
public class ServletXML extends HttpServlet {
private static final long serialVersionUID = 1L;
public ServletXML() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
XMLClass.xmldata();
} catch (XQException e) {
e.printStackTrace()
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

Then xml your class may be missing from your classpath. How are you compiling and running this?
Also it is good practice to place both into one or more packages and import your class from your servlet if it is in a different package.

Related

How to resolve view in thymleaf + Springboot?

Currently, i have function, which is to convert the data from MYSQL to CSV. The CSV function contain the webconfig where use the viewResolver. The problem is, when i used below function, the page cannot view but the CSV file can be download and vice versa. Is there anything that i need to configure ?
-Configure ContentNegotiatingViewResolver
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
WebConfig- full code
package com.portal.dmtt.csvDownload.config;
import com.portal.dmtt.csvDownload.viewResolver.CsvViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import java.util.ArrayList;
import java.util.List;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true);
}
/*
* Configure ContentNegotiatingViewResolver
*/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
}
Export Controller
package com.portal.dmtt.csvDownload.controller;
import com.portal.dmtt.repo.dmttDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExportController {
#Autowired
private dmttDAO dmttDAO;
/**
* Handle request to download an Excel document
*/
#GetMapping("/dl")
public String download(Model model) {
model.addAttribute("results", dmttDAO.getAllResultSet());
return "";
}
}
Abstract View
package com.portal.dmtt.csvDownload.view;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public abstract class AbstractCsvView extends AbstractView {
private static final String CONTENT_TYPE = "text/csv";
public AbstractCsvView() {
setContentType(CONTENT_TYPE);
}
#Override
protected boolean generatesDownloadContent() {
return true;
}
#Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
buildCsvDocument(model, request, response);
}
protected abstract void buildCsvDocument(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
CSV View
package com.portal.dmtt.csvDownload.view;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class CsvView extends AbstractCsvView {
#Override
protected void buildCsvDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse
response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"my-csv-file.csv\"");
List<FN_Result_Set> fnResultSetList = (List<FN_Result_Set>) model.get("results");
String[] header = {"SP_ID", "SP_ID", "XFER_XMIT_STATUS", "XFER_FILE_NAME", "UPDATE_TS", "YYMM", "REMARKS"};
try {
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
csvWriter.writeHeader(header);
for (FN_Result_Set user : fnResultSetList) {
csvWriter.write(user, header);
}
csvWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
View Resolver
package com.portal.dmtt.csvDownload.viewResolver;
import com.portal.dmtt.csvDownload.view.CsvView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
public class CsvViewResolver implements ViewResolver {
#Override
public View resolveViewName(String s, Locale locale) throws Exception {
return new CsvView();
}
}
One of the problems is that your CSVViewResolver is resolving a view for any view name. You may want to return null from CSVViewResolver.resolveViewName() if s, the view name, is not empty .
Another issue is that the browser (at least my Chrome) doesn't send text/csv as Accept header, but text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Set the media type explicitly in configureContentNegotiation for CSV:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true)
.mediaType("csv", MediaType.parseMediaType("text/csv"));
}
Remove the Bean contentNegotiatingViewResolver
You shouldn't create a contentNegotiatingViewResolver as one is provided by Spring Boot. If you provide one, you will have two of this type, and yours will not have the Thymeleaf ViewResolver. As your CSVViewResolver will return a view for any view name, the view will be resolved in the ContentNegotiatingViewResolver provided by you, not in the one provided by Spring.
Details:
The csvViewResolver bean will be picked up by the Spring Boot's ContentNegotiatingViewResolver along others like BeanNameViewResolver, ThymeleafViewResolver, ViewResolverComposite, InternalResourceViewResolver.
To debug this set a breakpoint on DispatcherServlet.resolveViewName:
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
HttpServletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
}
}
return null;
}

Java Servlet Programming with internal server error

I am getting an internal server error here.Where is my mistake?
My code is as follows:
import java.io.*;
import javax.servlet.*;
import java.util.*;
import javax.servlet.http.*;
public class Factor extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
int num=Integer.parseInt(request.getParameter("fact"));
out.println(num);
int i,f=1;
for(i=1;i<=num;i++)
{
f=f*i;
}
out.println("The factorial is: "+ f);
out.close();
}
}
Any help will be appreciated

#WebServlet on Tomcat 7 getting 404 Error

Tomcat 7 running on Windows 7, using servlet annotation, is giving me a 404 error when I try this URL:
http://localhost:8080/LoginExample/
Tomcat is using JRE 1.7, and the servlet class is contained within folder .../webapps/LoginExample. It was compiled using Java 1.7. I have no Web.xml. It deploys without error.
Here is the class:
package com.journaldev.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet(
description = "Login Servlet",
urlPatterns = { "/LoginServlet" },
initParams = {
#WebInitParam(name = "user", value = "Pankaj"),
#WebInitParam(name = "password", value = "journaldev")
})
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException {
//we can create DB connection resource here and set it to Servlet context
if(getServletContext().getInitParameter("dbURL").equals("jdbc:mysql://localhost/mysql_db") &&
getServletContext().getInitParameter("dbUser").equals("mysql_user") &&
getServletContext().getInitParameter("dbUserPwd").equals("mysql_pwd"))
getServletContext().setAttribute("DB_Success", "True");
else throw new ServletException("DB Connection error");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
//get servlet config init params
String userID = getServletConfig().getInitParameter("user");
String password = getServletConfig().getInitParameter("password");
//logging example
log("User="+user+"::password="+pwd);
if(userID.equals(user) && password.equals(pwd)){
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
Your servlet class LoginServlet is designed to handle only '/LoginServlet' url and in http://localhost:8080/LoginExample/ you are using '/' as url.
You must use http://localhost:8080/LoginExample/LoginServlet
OR
<form action="LoginServlet" method="post">
....
....
</form>

No InputStream specified when use spring-mvc-test andDo() method

recently when i do my work using spring-mvc-test-framework,code like this:
this.mockMvc.perform(MockMvcRequestBuilders.get("/manage/bill/detail/{id}","5507c2240cf2bc43ba2367bd").accept(MediaType.ALL)).andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcRestDocumentation.document("index"));
then i got this error.
java.lang.IllegalArgumentException: No InputStream specified
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.util.FileCopyUtils.copy(FileCopyUtils.java:106)
at org.springframework.util.FileCopyUtils.copyToByteArray(FileCopyUtils.java:156)
at org.springframework.restdocs.mockmvc.MockMvcOperationRequestFactory.createOperationRequest(MockMvcOperationRequestFactory.java:83)
at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:93)
at org.springframework.test.web.servlet.MockMvc$1.andDo(MockMvc.java:155)
I searched and find no answers.
can anybody tell me why this happens?
Now I got another solution.
actually I use Spring MVC test example in its offical reference http://docs.spring.io/spring-restdocs/docs/1.0.0.RELEASE/reference/html5/#getting-started-build-configuration-maven-packaging and use the setUp() method like this:
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
the aim is to document api 。Now the another solution is I use apply() method and then problem solved.
first,i changed to :
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation)).build();
then solved the version problem like this:
spring-restdocs is not recognizing apply()
All my code below:
package com.dream.bwm.test.test;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.restdocs.RestDocumentation;
import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "classpath:spring/root-context.xml", "classpath:spring/app-context.xml" })
public class DocsGenerator {
public static String outputDir = "D:\\workspace-bwme\\pro-root\\bwme-backend\\target\\generated-snippets";
#Rule
public final RestDocumentation restDocumentation = new RestDocumentation(outputDir);
#Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
#Before
public void setUp() {
// this.mockMvc =
// MockMvcBuilders.webAppContextSetup(this.context).build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.apply(MockMvcRestDocumentation.documentationConfiguration(this.restDocumentation)).build();
}
// #Test
public void printOnConsole() throws Exception {
this.mockMvc
.perform(
MockMvcRequestBuilders.get("/manage/bill/detail/{id}", "5507c2240cf2bc43ba2367bd").accept(
MediaType.ALL_VALUE)).andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isOk());// MockMvcRestDocumentation.document("index")
}
#Test
public void writeToDocument() throws Exception {
this.mockMvc
.perform(
RestDocumentationRequestBuilders.get("/manage/bill/detail/{id}", "5507c2240cf2bc43ba2367bd")
.accept(MediaType.ALL)).andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcRestDocumentation.document("index"));
}
}
hope this can give you some help if someone encounters such questions.

The import javax.servlet http can't be resolved

![Eclipse Screen Shot the file structure and errors are lie in the image, if there is any improper file structure please let me know ][1]The Error shows like in the following image,Hello Everyone i am a servlet beginer , i have a problem with the following servlet code, could any one help to fix it.it shows javax.servlet.http cannot be resolved how to fix this issues?
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.second.po.User;
import com.second.serivce.UserService;
public class regServlet extends HttpServlet {
//UserDao userDao=new UserDao();//模式一直接通过UserDao访问数据库
private UserService userService=new UserService();//通过类之间的组合关系将其组合
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uname =request.getParameter("uname").trim();
String pwd =request.getParameter("pwd").trim();
String email =request.getParameter("email").trim();
String phone =request.getParameter("phone").trim();
String address =request.getParameter("address").trim();
int age =Integer.parseInt(request.getParameter("age"));
int gender =Integer.parseInt(request.getParameter("gender"));
int degree =Integer.parseInt(request.getParameter("degree"));
java.sql.Date joinTime=new java.sql.Date(new java.util.Date().getTime());
User user=new User("老高","1234","1808029435#qq.com",18,"13378052446","北京",0,1,joinTime);
userService.register(user);
request.getRequestDispatcher("reg_ok.jsp").forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}

Resources