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
Related
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;
}
My issue is that I get always Request method 'POST' not supported !
I'm trying to test my rest web webservice. Here is the WS :
#RequestMapping(value = "/addGouvernorate", method = RequestMethod.POST, produces = { "application/json" })
public ResponseEntity<Gouvernorate> addGouvernorateee(#RequestBody Gouvernorate gouvernorate) throws IOException {
gouvernorateService.addGouvernorat(gouvernorate);
return new ResponseEntity<Gouvernorate>(gouvernorate, HttpStatus.OK);
}
i'm trying to call it with jsoup as follows :
package test.sofiane.rqs;
import java.io.IOException;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.springframework.security.crypto.codec.Base64;
public class Test {
public static void main(String[] args) throws IOException {
String base64login = new String(Base64.encode("sof:1".getBytes()));
Response docs = Jsoup.connect("http://localhost:8080/site/data/addGouvernorate")
.data("name", "name")
.data("delegation", "delegation")
.data("district", "district")
.data("postalCode", "postalCode")
.method(Method.POST)
.execute();
}
}
I get the exception :
Exception in thread "main" org.jsoup.HttpStatusException: HTTP error fetching URL. Status=405, URL=http://localhost:8080/mintad/data/addGouvernorate
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:459)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:434)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:181)
at test.sofiane.rqs.Test.main(Test.java:21)
And with Postman application I get
Etat HTTP 405 - Request method 'POST' not supported
I'm using spring security also.
as follow
package com.site.spring.security;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
/**
* #author Sofiane
*/
#Configuration
#EnableWebSecurity
#ComponentScan
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
DataSource dataSource;
#Autowired
#Qualifier("customUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
//.antMatchers("/admin/**").denyAll()//.access("hasRole('ADMIN')")
.and().formLogin().loginPage("/login")
.defaultSuccessUrl("/welcome").usernameParameter("username").passwordParameter("password")
.and().exceptionHandling().accessDeniedPage("/404");
// #formatter:off
}
}
A guess : it can be the csrftoken which I have to send since I'm behind spring security but how to generate it ?
Please help because it's driving me insane guys
![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);
}
}
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.
I have develop servlet for generate Captcha code & add session name code
Generate Capta-code
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
Random rnd;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rnd=new Random();
rep.setContentType("image/jpeg");
String random_String=getRandomNumbers();
HttpSession ses=req.getSession();
ses.setAttribute("code",random_String);
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
private String getRandomNumbers()
{
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Use Generate capta-image in other servlet
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
HttpSession ses=req.getSession();
String original=(String)ses.getAttribute("code");
if(original!=null)
{
out.println("<h1>Original Value "+original+"</h1>");
}
ses.invalidate();
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Both servlet work fine but I am not getting the session value which is generate in Capta-code servelt(added in servlet)
I am getting session value which is generate in previous capta-image.
See output :
Output - 1
Output - 2
Output - 3
Thank you ..
Put the random number generation logic in capta_test servlet and put that number in session. Because you are rendering HTML, the capta servlet will be called after the page load like this and do not invalidate the session.
Random number generator
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class capta_test extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
PrintWriter out=null;
try
{
String original=getRandomNumbers();
HttpSession ses=req.getSession(false);
ses.setAttribute("code",random_String);
String input=req.getParameter("txt_capta");
out=rep.getWriter();
rep.setContentType("text/html");
out.println("<html><head><title>Capta Test</title></head>");
out.println("<body>");
out.println("<h1> Capta is Generated </h1>");
out.println("<img src=\"http://localhost:8080/mahesh/capta\" />");
out.println("<h1>Original Value "+original+"</h1>");
out.println("</body>");
out.println("</html>");
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
private String getRandomNumbers()
{
Random rnd=new Random();
StringBuffer str=new StringBuffer();
for(int i=1;i<=9;i++)
{
str.append(new Integer(rnd.nextInt(9)).toString());
}
return str.toString();
}
}
Image generator servlet
import javax.servlet.*;
import java.io.*;
import java.awt.*;
import java.util.Random;
import java.awt.image.*;
import javax.imageio.*;
import javax.servlet.http.*;
public class capta extends HttpServlet
{
final int LEN=10;
BufferedImage image;
public void doGet(HttpServletRequest req,HttpServletResponse rep)
{
try
{
HttpSession ses=req.getSession(false);
String random_String=(String)ses.getAttribute("code");
image = new BufferedImage(200, 80, BufferedImage.TYPE_INT_RGB);
rep.setContentType("image/jpeg");
Graphics g = image.getGraphics();
g.setFont(new Font("Maiandra GD",1,30));
g.setColor(Color.blue);
g.drawString(random_String,3,50);
g.dispose();
/// it was here
ImageIO.write(image, "jpg", rep.getOutputStream());
}
catch(Exception e)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse rep)throws ServletException , IOException
{
doGet(req,rep);
}
}
Your program flow is wrong , the session value is null because the capta_test servlet is called even before the capta servlet.
Have a look at this simple tutorial. Hope this helps you move in the right path
Captcha in JSP and Servlet